app.ts
2.21 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
import fastify from 'fastify';
import type { BackendConfig, ErrorResponse } from '../packages/contracts/src/index.js';
import { createErrorResponse, isAppError } from './lib/errors.js';
import { createPrismaPlugin, type PrismaClientFactory } from './plugins/prisma.js';
import { healthRoute } from './routes/health.js';
import { prelearningRoute, type RouteOptions as PrelearningRouteOptions } from './routes/prelearning.js';
import { sopMaterialPreviewRoute, type RouteOptions as SopMaterialPreviewRouteOptions } from './routes/sop-material-preview.js';
interface BuildAppDependencies {
createPrismaClient?: PrismaClientFactory;
prelearningRouteOptions?: PrelearningRouteOptions;
sopMaterialPreviewRouteOptions?: SopMaterialPreviewRouteOptions;
}
export function buildApp(config: BackendConfig, dependencies: BuildAppDependencies = {}) {
const app = fastify({
logger: {
level: config.logLevel,
},
});
app.decorate('config', config);
app.register(createPrismaPlugin(dependencies.createPrismaClient));
app.register(healthRoute);
if (dependencies.prelearningRouteOptions) {
app.register(prelearningRoute, dependencies.prelearningRouteOptions);
} else {
app.register(prelearningRoute);
}
if (dependencies.sopMaterialPreviewRouteOptions) {
app.register(sopMaterialPreviewRoute, dependencies.sopMaterialPreviewRouteOptions);
} else {
app.register(sopMaterialPreviewRoute);
}
app.setErrorHandler((error, request, reply) => {
const requestId = request.id;
if (isAppError(error)) {
const appError = error;
const response: ErrorResponse = createErrorResponse(
appError.code,
appError.message,
requestId,
appError.details,
);
reply.status(appError.statusCode).send(response);
return;
}
if ((error as { validation?: unknown }).validation) {
reply.status(400).send(
createErrorResponse('VALIDATION_ERROR', '请求参数校验失败', requestId, (error as { validation: unknown }).validation),
);
return;
}
request.log.error({ err: error }, 'unhandled error');
reply.status(500).send(createErrorResponse('INTERNAL_SERVER_ERROR', '服务暂时不可用', requestId));
});
return app;
}