-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
89 lines (79 loc) · 2.44 KB
/
Copy pathmain.ts
File metadata and controls
89 lines (79 loc) · 2.44 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
import 'reflect-metadata';
import { InversifyExpressServer } from 'inversify-express-utils';
import { Container } from 'inversify';
import { User } from './src/user/controller';
import { UserService } from './src/user/service';
import { Post } from './src/post/controller';
import { PostService } from './src/post/service';
import { Project } from './src/project/controller';
import { ProjectService } from './src/project/service';
import express from 'express';
import { PrismaClient } from '@prisma/client';
import { PrismaDB } from './src/db';
import { JWT } from './src/jwt';
import loggerMiddleware from './src/middleware/logger';
import {
logErrors,
clientErrorHandler,
errorHandler,
} from './src/middleware/errorHandler';
import cors from 'cors';
import { corsOptions } from './src/config/cors';
const container = new Container();
/**
* user模块
*/
container.bind(User).to(User);
container.bind(UserService).to(UserService);
/**
* post模块
*/
container.bind(Post).to(Post);
container.bind(PostService).to(PostService);
/**
* project模块
*/
container.bind(Project).to(Project);
container.bind(ProjectService).to(ProjectService);
/**
* 封装PrismaClient
*/
container.bind<PrismaClient>('PrismaClient').toFactory(() => {
return () => {
return new PrismaClient();
};
});
container.bind(PrismaDB).to(PrismaDB);
/**
* jwt模块
*/
container.bind(JWT).to(JWT); //主要代码
const server = new InversifyExpressServer(container);
server.setConfig((app) => {
// app.use(
// cors({
// origin:
// process.env.NODE_ENV === 'production'
// ? ['https://your-production-domain.com'] // 生产环境限制来源域名
// : '*', // 开发环境允许所有来源
// methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
// allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
// credentials: true, // 允许发送认证信息(cookies)
// maxAge: 86400, // 预检请求缓存时间(24小时)
// }),
// );
app.use(cors(corsOptions));
app.use(express.json());
app.use(loggerMiddleware);
app.use(container.get(JWT).init());
});
// 全局错误处理
server.setErrorConfig((app) => {
app.use(logErrors); // 1. 记录错误日志
app.use(clientErrorHandler); // 2. 处理客户端错误(包括校验错误)
app.use(errorHandler); // 3. 兜底服务端错误
});
const app = server.build();
app.listen(3001, () => {
console.log('Listening on port 3001');
});