-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
162 lines (143 loc) · 3.84 KB
/
server.ts
File metadata and controls
162 lines (143 loc) · 3.84 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import { ApplicationContainer } from './deps';
import fastify from 'fastify';
import fastifyCors from '@fastify/cors';
import fastifyHelmet from '@fastify/helmet';
import fastifySwagger from '@fastify/swagger';
import fastifyCookie from '@fastify/cookie';
import fastifyRateLimit from '@fastify/rate-limit';
import fastifySwaggerUi from '@fastify/swagger-ui';
import { User } from './users/userEntity';
import { registerApiSchemas } from './apiSchemas';
import { AUTH_SESSION_COOKIE_NAME } from './auth/authService';
import { makeAuthRoutes } from './auth/authRoutes';
import { AppError, ErrorCode } from './errors';
declare module 'fastify' {
interface FastifyRequest {
user?: User | null;
sessionId?: string;
}
}
export async function startWebServer(app: ApplicationContainer) {
const server = fastify({
trustProxy: true,
});
server.decorateRequest('user', null);
server.decorateRequest('sessionId', '');
await server.register(fastifyHelmet);
await server.register(fastifyCors, {
origin: '*',
});
await server.register(fastifyRateLimit, {
errorResponseBuilder: () => {
throw new AppError(
ErrorCode.TOO_MANY_REQUESTS,
`Too many requests, please try again later`,
);
},
});
await server.register(fastifyCookie);
await server.register(fastifySwagger, {
//TEMPLATE: adjust the swagger options as needed
openapi: {
openapi: '3.0.0',
info: {
title: 'My Application API',
version: '1.0.0',
},
tags: [
{
name: 'auth',
description: 'Authentication related endpoints',
},
],
servers: [
{
url: `http://localhost:${app.config.port}`,
description: 'Local development server',
},
],
components: {
securitySchemes: {
session: {
type: 'apiKey',
in: 'cookie',
name: AUTH_SESSION_COOKIE_NAME,
},
},
},
},
});
if (app.config.swaggerUi) {
await server.register(fastifySwaggerUi, {
routePrefix: '/api-docs',
});
}
registerApiSchemas(server);
server.setNotFoundHandler((request) => {
throw new AppError(
ErrorCode.NOT_FOUND,
`Requested URL (${request.method} ${request.url}) not found`,
);
});
server.setSchemaErrorFormatter((errors) => {
const error = errors[0];
const fieldName = error.instancePath.substring(1);
return new AppError(
ErrorCode.VALIDATION_ERROR,
error.message
? `Field '${fieldName}' is invalid: ${error.message}`
: `Field '${fieldName}' is invalid`,
);
});
server.setErrorHandler((error, request, reply) => {
if (error instanceof AppError) {
reply.status(error.toHttpCode()).send({
code: error.code,
message: error.message,
timestamp: Date.now(),
});
} else {
app.logger.error(
'Server',
`Unknown error at ${request.method} ${request.url}:`,
error,
);
reply.status(500).send({
code: ErrorCode.INTERNAL_SERVER_ERROR,
message: 'Internal server error',
timestamp: Date.now(),
});
}
});
server.get(
'/',
{
schema: {
description: 'Health check endpoint',
response: {
200: {
type: 'object',
properties: {
alive: { type: 'boolean' },
},
},
},
},
},
() => ({ alive: true }),
);
await server.register(makeAuthRoutes(app), {
prefix: '/api/auth',
});
const startedOn = await server.listen({
host: '0.0.0.0',
port: app.config.port,
});
app.logger.info('Server', `Listening started on ${startedOn}`);
if (app.config.swaggerUi) {
app.logger.info(
'Server',
`Swagger UI available at http://localhost:${app.config.port}/api-docs`,
);
}
}