-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttp-api.ts
380 lines (341 loc) · 11.4 KB
/
http-api.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
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import { getLogger } from '@infrastructure/logging/index.js';
import type { HttpApiConfig } from '@infrastructure/config/index.js';
import type { FastifyInstance, FastifyBaseLogger } from 'fastify';
import fastify from 'fastify';
import type Api from '@presentation/api.interface.js';
import type { DomainServices } from '@domain/index.js';
import cors from '@fastify/cors';
import { fastifyOauth2 } from '@fastify/oauth2';
import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUI from '@fastify/swagger-ui';
import addUserIdResolver from '@presentation/http/middlewares/common/userIdResolver.js';
import cookie from '@fastify/cookie';
import { notFound, forbidden, unauthorized, notAcceptable, domainError } from './decorators/index.js';
import NoteRouter from '@presentation/http/router/note.js';
import OauthRouter from '@presentation/http/router/oauth.js';
import AuthRouter from '@presentation/http/router/auth.js';
import UserRouter from '@presentation/http/router/user.js';
import AIRouter from '@presentation/http/router/ai.js';
import EditorToolsRouter from './router/editorTools.js';
import { UserSchema } from './schema/User.js';
import { NoteSchema } from './schema/Note.js';
import { HistotyRecordShema, HistoryMetaSchema } from './schema/History.js';
import { NoteSettingsSchema } from './schema/NoteSettings.js';
import { OauthSchema } from './schema/OauthSchema.js';
import Policies from './policies/index.js';
import type { RequestParams, Response } from '@presentation/api.interface.js';
import NoteSettingsRouter from './router/noteSettings.js';
import NoteListRouter from '@presentation/http/router/noteList.js';
import { EditorToolSchema } from './schema/EditorTool.js';
import JoinRouter from '@presentation/http/router/join.js';
import { JoinSchemaParams, JoinSchemaResponse } from './schema/Join.js';
import { DomainError } from '@domain/entities/DomainError.js';
import UploadRouter from './router/upload.js';
import { ajvFilePlugin } from '@fastify/multipart';
import { UploadSchema } from './schema/Upload.js';
const appServerLogger = getLogger('appServer');
/**
* Http server implementation
*/
export default class HttpApi implements Api {
/**
* Fastify server instance
*/
private server: FastifyInstance | undefined;
/**
* Constructs the instance
* @param config - http server config
*/
constructor(private readonly config: HttpApiConfig) { }
/**
* Initializes http server
* @param domainServices - instances of domain services
*/
public async init(domainServices: DomainServices): Promise<void> {
this.server = fastify({
logger: appServerLogger as FastifyBaseLogger,
ajv: {
plugins: [
/** Allows to validate files in schema */
ajvFilePlugin,
],
},
});
/**
* To guarantee consistent and predictable behavior,
* it's highly recommended to always load plugins in order as shown below:
*
* └── plugins (from the Fastify ecosystem)
* └── your plugins (your custom plugins)
* └── decorators
* └── hooks
* └── your services
* @see https://fastify.dev/docs/latest/Guides/Getting-Started#loading-order-of-your-plugins
*/
this.domainErrorHandler();
await this.addCookies();
await this.addOpenapiDocs();
await this.addOpenapiUI();
await this.addOauth2();
await this.addCORS();
this.addCommonMiddlewares(domainServices);
this.addSchema();
this.addDecorators();
this.addPoliciesCheckHook(domainServices);
await this.addApiRoutes(domainServices);
}
/**
* Runs http server
*/
public async run(): Promise<void> {
if (this.server === undefined) {
throw new Error('Server is not initialized');
}
await this.server.listen({
host: this.config.host,
port: this.config.port,
});
}
/**
* Performs fake request to API routes.
* Used for API testing
* @param params - request options
*/
public async fakeRequest(params: RequestParams): Promise<Response | undefined> {
const response = await this.server?.inject(params);
if (response === undefined) {
return;
}
return {
statusCode: response.statusCode,
body: response.body,
headers: response.headers,
json: response.json,
};
}
/**
* Registers openapi documentation
*
*/
private async addOpenapiDocs(): Promise<void> {
await this.server?.register(fastifySwagger, {
openapi: {
info: {
title: 'NoteX openapi',
description: 'Fastify REST API',
version: '0.1.0',
},
servers: [{
url: 'http://localhost:1337',
description: 'Localhost environment',
}, {
url: 'https://api.notex.so',
description: 'Production environment',
}],
components: {
securitySchemes: {
oAuthGoogle: {
type: 'oauth2',
description: 'Provied authorization uses OAuth 2 with Google',
flows: {
authorizationCode: {
authorizationUrl: 'https://api.notex.so/oauth/google/login',
scopes: {
notesManagement: 'Create, read, update and delete notes',
},
tokenUrl: 'https://api.notex.so/oauth/google/callback',
},
},
},
},
},
},
});
}
/**
* Serves openapi UI and JSON scheme
*/
private async addOpenapiUI(): Promise<void> {
await this.server?.register(fastifySwaggerUI, {
routePrefix: '/openapi',
uiConfig: {
docExpansion: 'list',
deepLinking: false,
},
transformSpecificationClone: true,
});
}
/**
* Adds support for reading and setting cookies
*/
private async addCookies(): Promise<void> {
await this.server?.register(cookie, {
secret: this.config.cookieSecret,
});
}
/**
* Registers all routers
* @param domainServices - instances of domain services
*/
private async addApiRoutes(domainServices: DomainServices): Promise<void> {
await this.server?.register(NoteRouter, {
prefix: '/note',
noteService: domainServices.noteService,
noteSettingsService: domainServices.noteSettingsService,
noteVisitsService: domainServices.noteVisitsService,
editorToolsService: domainServices.editorToolsService,
});
await this.server?.register(NoteListRouter, {
prefix: '/notes',
noteService: domainServices.noteService,
noteSettingsService: domainServices.noteSettingsService
});
await this.server?.register(JoinRouter, {
prefix: '/join',
noteSettings: domainServices.noteSettingsService,
});
await this.server?.register(NoteSettingsRouter, {
prefix: '/note-settings',
noteSettingsService: domainServices.noteSettingsService,
noteService: domainServices.noteService,
});
await this.server?.register(OauthRouter, {
prefix: '/oauth',
userService: domainServices.userService,
authService: domainServices.authService,
cookieDomain: this.config.cookieDomain,
});
await this.server?.register(AuthRouter, {
prefix: '/auth',
authService: domainServices.authService,
});
await this.server?.register(UserRouter, {
prefix: '/user',
userService: domainServices.userService,
editorToolsService: domainServices.editorToolsService,
});
await this.server?.register(AIRouter, {
prefix: '/ai',
aiService: domainServices.aiService,
});
await this.server?.register(EditorToolsRouter, {
prefix: '/editor-tools',
editorToolsService: domainServices.editorToolsService,
});
await this.server?.register(UploadRouter, {
prefix: '/upload',
fileUploaderService: domainServices.fileUploaderService,
noteService: domainServices.noteService,
fileSizeLimit: this.config.fileSizeLimit,
noteSettingsService: domainServices.noteSettingsService,
});
}
/**
* Registers oauth2 plugin
*
*/
private async addOauth2(): Promise<void> {
await this.server?.register(fastifyOauth2, {
name: 'googleOAuth2',
scope: ['profile', 'email'],
credentials: {
client: {
id: this.config.oauth2.google.clientId,
secret: this.config.oauth2.google.clientSecret,
},
auth: fastifyOauth2.GOOGLE_CONFIGURATION,
},
startRedirectPath: this.config.oauth2.google.redirectUrl,
callbackUri: this.config.oauth2.google.callbackUrl,
});
}
/**
* Allows cors for allowed origins from config
*/
private async addCORS(): Promise<void> {
await this.server?.register(cors, {
origin: this.config.allowedOrigins,
});
}
/**
* Add Fastify schema for validation and serialization
*/
private addSchema(): void {
this.server?.addSchema(UserSchema);
this.server?.addSchema(NoteSchema);
this.server?.addSchema(HistotyRecordShema);
this.server?.addSchema(HistoryMetaSchema);
this.server?.addSchema(EditorToolSchema);
this.server?.addSchema(NoteSettingsSchema);
this.server?.addSchema(JoinSchemaParams);
this.server?.addSchema(JoinSchemaResponse);
this.server?.addSchema(OauthSchema);
this.server?.addSchema(UploadSchema);
}
/**
* Add custom decorators
*/
private addDecorators(): void {
this.server?.decorateReply('notFound', notFound);
this.server?.decorateReply('forbidden', forbidden);
this.server?.decorateReply('unauthorized', unauthorized);
this.server?.decorateReply('notAcceptable', notAcceptable);
this.server?.decorateReply('domainError', domainError);
}
/**
* Add middlewares
* @param domainServices - instances of domain services
*/
private addCommonMiddlewares(domainServices: DomainServices): void {
if (this.server === undefined) {
throw new Error('Server is not initialized');
}
addUserIdResolver(this.server, domainServices.authService, appServerLogger);
}
/**
* Add "onRoute" hook that will add "preHandler" checking policies passed through the route config
* @param domainServices - instances of domain services
*/
private addPoliciesCheckHook(domainServices: DomainServices): void {
this.server?.addHook('onRoute', (routeOptions) => {
const policies = routeOptions.config?.policy ?? [];
if (policies.length === 0) {
return;
}
/**
* Save original route preHandler(s) if exists
*/
if (routeOptions.preHandler === undefined) {
routeOptions.preHandler = [];
} else if (!Array.isArray(routeOptions.preHandler)) {
routeOptions.preHandler = [routeOptions.preHandler];
}
routeOptions.preHandler.push(async (request, reply) => {
for (const policy of policies) {
await Policies[policy]({ request,
reply,
domainServices });
}
});
});
}
/**
* Domain error handler
*/
private domainErrorHandler(): void {
this.server?.setErrorHandler(function (error, request, reply) {
/**
* If we have an error that occurs in the domain-level we reply it with special format
*/
if (error instanceof DomainError) {
this.log.error(error);
void reply.domainError(error.message);
return;
}
/**
* If error is not a domain error, we route it to the default error handler
*/
throw error;
});
}
}