Switch to apollo-server-express to enable middleware for authentication
Signed-off-by: trivernis <trivernis@protonmail.com>pull/3/head
parent
d475851bb3
commit
b61dfa8810
@ -1,26 +1,55 @@
|
|||||||
import { ApolloServer } from 'apollo-server'
|
import { ApolloServer } from 'apollo-server-express'
|
||||||
import bikeresolver from './resolvers/cargobikeResolver'
|
import bikeresolver from './resolvers/cargobikeResolver'
|
||||||
import { CargoBikeAPI } from './datasources/db/cargobikeAPI'
|
import { CargoBikeAPI } from './datasources/db/cargobikeAPI'
|
||||||
import typeDefs from './schema/type-defs'
|
import typeDefs from './schema/type-defs'
|
||||||
import 'reflect-metadata'
|
import 'reflect-metadata'
|
||||||
import { createConnection } from 'typeorm'
|
import { createConnection } from 'typeorm'
|
||||||
import { UserServerAPI } from './datasources/userserver/userserviceAPI'
|
import { UserServerAPI } from './datasources/userserver/userserviceAPI'
|
||||||
|
import express from 'express'
|
||||||
|
|
||||||
require('dotenv').config()
|
require('dotenv').config()
|
||||||
|
|
||||||
|
async function authenticate (req: any, res: any, next: any) {
|
||||||
|
if (process.env.NODE_ENV === 'develop') {
|
||||||
|
next()
|
||||||
|
} else {
|
||||||
|
const token = req.headers.authorization?.replace('Bearer ', '')
|
||||||
|
if (token) {
|
||||||
|
if (await userAPI.validateToken(token)) {
|
||||||
|
next()
|
||||||
|
} else {
|
||||||
|
res.status(401)
|
||||||
|
res.send('Unauthorized')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res.status(401)
|
||||||
|
res.send('Unauthorized')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
createConnection().then(async () => {
|
createConnection().then(async () => {
|
||||||
console.log('connected to db')
|
console.log('connected to db')
|
||||||
}).catch(error => console.log(error))
|
}).catch(error => console.log(error))
|
||||||
|
|
||||||
|
const userAPI = new UserServerAPI(process.env.RPC_HOST)
|
||||||
|
|
||||||
const server = new ApolloServer({
|
const server = new ApolloServer({
|
||||||
resolvers: [bikeresolver],
|
resolvers: [bikeresolver],
|
||||||
typeDefs,
|
typeDefs,
|
||||||
dataSources: () => ({
|
dataSources: () => ({
|
||||||
cargoBikeAPI: new CargoBikeAPI(),
|
cargoBikeAPI: new CargoBikeAPI(),
|
||||||
userAPI: new UserServerAPI(process.env.RPC_HOST)
|
userAPI
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const app = express()
|
||||||
|
|
||||||
|
app.post('/graphql', authenticate)
|
||||||
|
app.get(/\/graphql?&.*query=/, authenticate)
|
||||||
|
server.applyMiddleware({ app })
|
||||||
|
|
||||||
console.log(__dirname)
|
console.log(__dirname)
|
||||||
server.listen()
|
app.listen(4000, () => {
|
||||||
.then(({ url }) => console.log(`Server ready at ${url} `))
|
console.log('Server listening on port 4000')
|
||||||
|
})
|
||||||
|
Loading…
Reference in New Issue