-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (38 loc) · 1.02 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
require('dotenv').config();
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { PrismaClient } = require('@prisma/client');
const typeDefs = require('./graphql/typeDefs');
const resolvers = require('./graphql/resolvers');
const jwt = require('jsonwebtoken');
const app = express();
const prisma = new PrismaClient();
// Middleware to check authentication
const getUser = (token) => {
try {
if (token) {
return jwt.verify(token, process.env.JWT_SECRET);
}
return null;
} catch (error) {
return null;
}
};
// Initialize Apollo Server
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
const token = req.headers.authorization || '';
const user = getUser(token);
return { prisma, user };
},
});
async function startServer() {
await server.start();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`Server ready at http://localhost:4000${server.graphqlPath}`)
);
}
startServer();