Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import express from 'express'
- import { ApolloServer } from 'apollo-server-express'
- import passport from 'passport'
- import passportJWT from 'passport-jwt'
- import schema from './schemas'
- const { JWT_SECRET } = process.env
- const path = '/graphql'
- // ...
- const users = [
- {
- id: 1,
- name: 'John',
- email: 'john@mail.com',
- password: 'john123'
- },
- {
- id: 2,
- name: 'Sarah',
- email: 'sarah@mail.com',
- password: 'sarah123'
- }
- ]
- // ...
- const { Strategy, ExtractJwt } = passportJWT
- const params = {
- secretOrKey: JWT_SECRET,
- jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
- }
- // ...
- const strategy = new Strategy(params, (payload, done) => {
- const user = users[payload.id] || null
- if (user) {
- return done(null, {
- id: user.id
- })
- }
- return done(new Error('The user has not been found'), null)
- })
- passport.use(strategy)
- // ...
- const app = express()
- passport.initialize()
- app.use(path, passport.authenticate('jwt', { session: false }))
- // ...
- const server = new ApolloServer({
- schema
- })
- server.applyMiddleware({
- app,
- path
- })
- app.listen(
- {
- port: 4000
- },
- () => console.log(`The GraphQL server is running on port ${GRAPHQL_PORT}`)
- )
Add Comment
Please, Sign In to add comment