I recently made the switch from JavaScript to TypeScript in my server project and I'm currently tidying up some code. I decided to combine my Google Passport OAuth stuff and login routes into a single file, but it seems like I've broken something in the process. I'm encountering an error that I can't quite pinpoint or fix. Any help would be greatly appreciated!
The error is occurring in index.ts on the
server.express.use(auth.initialize())
line. Specifically, I'm getting the following error message: UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'initialize' of undefined
. Can someone help me figure out what's causing this issue?
index.ts
import { createTypeormConn } from './db/createConn'
import schema from './graphql'
import { pubsub } from './graphql/PubSub'
import * as auth from './middleware/auth'
const express = require('express')
const { GraphQLServer, PubSub } = require('graphql-yoga')
const cookieSession = require('cookie-session')
const cors = require('cors')
const path = require('path')
export const startServer = async () => {
await createTypeormConn()
const corsOptions = {
origin: [
//omitted for brevity
],
credentials: true
}
const options = {
port: process.env.PORT || 1337,
endpoint: '/api',
subscriptions: '/api',
playground: '/playground'
}
const server = new GraphQLServer({
schema,
context: req => ({ pubsub, request: req.request })
})
server.express.use(
cookieSession({
maxAge: 24 * 60 * 60 * 1000,
keys: [''] //omitted
})
)
server.use(cors(corsOptions))
server.express.options('/api', cors(corsOptions))
server.express.use(auth.initialize()) //fails during initialize
server.express.use(auth.session())
server.express.use('/auth', auth.routes)
server.express.use('/', express.static(path.join(__dirname, 'site')))
server.start(options, ({ port }) => {
console.log(`Server is running on localhost:${port}`)
})
}
startServer()
auth.ts
import { User } from '../db/orm'
import * as passport from 'passport'
import { Router } from 'express'
import { OAuth2Strategy } from 'passport-google-oauth'
passport.serializeUser<any, any>((user, done) => {
done(null, user.id)
})
passport.deserializeUser((id, done) => {
User.findOne(id).then(user => {
done(null, user)
})
})
// passport.use(...)
// routes...
// export...
const initialize = passport.initialize
const session = passport.session
export { initialize, session, routes }