forked from hyrumpro/graphql-apollo-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
113 lines (91 loc) · 2.37 KB
/
server.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const { resolvers} = require('./resolvers');
const cors = require('cors');
const { connectDB } = require('./db');
const jwt = require('jsonwebtoken');
require('dotenv').config();
connectDB();
// GraphQL schema
const typeDefs = gql`
type User {
id: ID!
name: String!
email: String!
tasks: [Task!]
}
type Task {
id: ID!
name: String!
complete: Boolean!
user: User!
}
type AuthPayload {
token: String!
user: User!
}
input RegisterInput {
name: String!
email: String!
password: String!
}
input LoginInput {
email: String!
password: String!
}
input CreateTaskInput {
name: String!
complete: Boolean!
}
input UpdateTaskInput {
name: String
complete: Boolean
}
type Query {
greetings: [String!]
tasks: [Task!]
}
type Mutation {
register(input: RegisterInput!): User!
login(input: LoginInput!): AuthPayload!
createTask(input: CreateTaskInput!): Task!
updateTask(id: ID!, input: UpdateTaskInput!): Task!
deleteTask(id: ID!): Task!
}
`;
const app = express();
app.use(express.json());
// Enable CORS for all routes
app.use(cors());
const secretKey = process.env.JWT_SECRET;
const getUser = async (token) => {
if (token) {
try {
// Log the token to check its value
console.log('Token:', token);
// Verify the token using the correct secret key
const decoded = await jwt.verify(token, secretKey);
return decoded;
} catch (error) {
console.error('Token verification failed:', error.message);
return null;
}
}
};
// Create an instance of ApolloServer
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
const token = req.headers.authorization;
const user = await getUser(token);
return { user };
},
});
// Start the server
const port = process.env.PORT || 4000;
app.listen(port, async () => {
await server.start();
server.applyMiddleware({ app });
console.log(`🚀 Server ready at http://localhost:${port}${server.graphqlPath}`);
});