Created
February 12, 2020 15:14
-
-
Save lindenmelvin/627f899fcd785e4f0027690b6d3d1529 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { ApolloServer, gql } = require('apollo-server'); | |
const { validateToken } = require("./authService"); | |
const resolvers = require("./resolvers"); | |
const typeDefs = gql` | |
type User { | |
id: ID! | |
email: String! | |
password: String! | |
} | |
type Post { | |
title: String! | |
authorId: ID! | |
} | |
type AuthResponse { | |
token: String! | |
} | |
type Query { | |
posts: [Post!]! | |
} | |
type Mutation { | |
login(email: String!, password: String!): AuthResponse! | |
} | |
`; | |
const context = ({ req }) => { | |
if (req.body.query.match("Login")) return {}; | |
const authorizationHeader = req.headers.authorization || ''; | |
const token = authorizationHeader.split(' ')[1]; | |
if (!token) throw new Error("Authentication token is required."); | |
const user = validateToken(token); | |
return { user }; | |
} | |
const server = new ApolloServer({ | |
typeDefs, | |
resolvers, | |
context, | |
playground: false | |
}); | |
server.listen().then(({ url }) => { | |
console.log(`🚀 Server ready at ${url}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment