-
Notifications
You must be signed in to change notification settings - Fork 1
/
optionFactory.ts
66 lines (59 loc) · 2.14 KB
/
optionFactory.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
import ajv, { ajvOptions } from '@config/ajv';
import { addSchema, plainJsonSchema } from '@config/json-schema';
import fastJsonStringify, { Options as FJSOptions } from 'fast-json-stringify';
import fastify, { FastifyInstance, FastifyServerOptions } from 'fastify';
import { createServer, IncomingMessage, Server, ServerResponse } from 'http';
import { JSONSchema7 } from 'json-schema';
import { ReadonlyDeep } from 'type-fest';
type THttpServerFactory = (
handler: (req: IncomingMessage, res: ServerResponse) => void,
_option: FastifyServerOptions,
) => Server;
/**
* HTTP serverFactory
*/
function httpServerFactory(handler: (req: IncomingMessage, res: ServerResponse) => void): Server {
const newServer = createServer((req, res) => handler(req, res));
newServer.keepAliveTimeout = 120 * 100;
return newServer;
}
export default function optionFactory() {
const option: FastifyServerOptions & { serverFactory: THttpServerFactory } = {
ignoreTrailingSlash: true,
serverFactory: httpServerFactory,
};
const server = fastify<Server, IncomingMessage, ServerResponse>({
...option,
schemaController: {
bucket: (_parentSchemas?: JSONSchema7) => {
return {
add(schema: JSONSchema7): FastifyInstance<Server, IncomingMessage, ServerResponse> {
addSchema(schema);
return server;
},
getSchema(schemaId: string) {
return plainJsonSchema[schemaId];
},
getSchemas(): ReadonlyDeep<Record<string, JSONSchema7>> {
return plainJsonSchema;
},
};
},
compilersFactory: {
buildValidator() {
return ({ schema }) => ajv.compile(schema);
},
buildSerializer(externalSchemas: FJSOptions['schema'], options: FJSOptions) {
return ({ schema }) => {
const fjsoption = options ?? {};
fjsoption.schema = externalSchemas;
fjsoption.ajv = ajvOptions;
const stringify = fastJsonStringify(schema, fjsoption);
return (data: unknown) => stringify(data);
};
},
},
},
});
return { fastify: server, option };
}