Skip to content

Instantly share code, notes, and snippets.

@lindenmelvin
Created February 12, 2020 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lindenmelvin/627f899fcd785e4f0027690b6d3d1529 to your computer and use it in GitHub Desktop.
Save lindenmelvin/627f899fcd785e4f0027690b6d3d1529 to your computer and use it in GitHub Desktop.
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