-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
115 lines (96 loc) · 2.87 KB
/
index.ts
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
114
115
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { ApolloArmor } from '@escape.tech/graphql-armor';
import bodyParser from 'body-parser';
import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
import helmet from 'helmet';
import http from 'http';
import jwt from 'jsonwebtoken';
import mongoose, { Model } from 'mongoose';
import path from 'path';
import { NoteModel } from './db/models/note';
import type { INote } from './db/models/note';
import { UserModel } from './db/models/user';
import type { IUser } from './db/models/user';
import { typeDefs, resolvers } from './graphql';
dotenv.config({
path: path.join(__dirname, '../.env'),
});
interface MyContext {
models: {
Note: Model<INote>;
User: Model<IUser>;
};
user: IUser | null;
}
const PORT = process.env.PORT || 3000;
const DB = process.env.DB_HOST || 'localhost';
const app = express();
app.use(helmet());
const httpServer = http.createServer(app);
const getUser = async (token: string | undefined): Promise<IUser | null> => {
if (!token) {
return null;
}
try {
const { userId } = jwt.verify(token, process.env.JWT_SECRET as string) as { userId: string };
const user = await UserModel.findById(userId);
if (!user) {
return null;
}
return user;
} catch (error) {
Error('Not authenticated');
console.error(error);
return null;
}
};
const startApolloServer = async () => {
try {
await mongoose
.connect(DB)
.then((result) => {
console.log('Connected to MongoDB', result.connection.name);
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});
const armor = new ApolloArmor();
const protection = armor.protect();
const server = new ApolloServer<MyContext>({
typeDefs,
resolvers,
...protection,
plugins: [...protection.plugins, ApolloServerPluginDrainHttpServer({ httpServer })],
validationRules: [...protection.validationRules],
});
await server.start();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
'/api',
expressMiddleware(server, {
context: async ({ req }): Promise<MyContext> => {
const token = req.headers.authorization;
const user = await getUser(token);
return {
models: {
Note: NoteModel,
User: UserModel,
},
user,
};
},
}),
);
await new Promise<void>((resolve) => httpServer.listen({ port: PORT }, resolve));
console.log(`🚀 Server ready at http://localhost:${PORT}`);
} catch (error) {
console.error(error);
}
};
startApolloServer();