-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
161 lines (139 loc) · 5.13 KB
/
Copy pathapp.js
File metadata and controls
161 lines (139 loc) · 5.13 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
// app.js
require('dotenv').config();
const setupDNS = require('./config/dns');
// Fix Windows DNS SRV issues for MongoDB Atlas
setupDNS();
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const connectDB = require('./config/connectDB');
connectDB();
const app = express();
app.use(cors());
/* -----------------------------
Middleware
------------------------------ */
app.set('trust proxy', 1);
app.use(helmet({ contentSecurityPolicy: false }));
app.use(cors());
app.use(express.json({ limit: '8mb' }));
if (process.env.NODE_ENV !== 'test') app.use(morgan('dev'));
// -----------------------------
// Swagger (OpenAPI 3) 集成
// -----------------------------
const swaggerUi = require('swagger-ui-express');
const swaggerJSDoc = require('swagger-jsdoc');
const baseUrl = process.env.SWAGGER_SERVER_BASE || '/api'; // 与业务路由前缀一致(如 /api/ai/*) [1](https://waikatouniversitynz-my.sharepoint.com/personal/jl1132_students_waikato_ac_nz/Documents/Microsoft%20Copilot%20Chat%20Files/app.js)
const swaggerDefinition = {
openapi: '3.0.3',
info: {
title: 'Your Project API',
version: '1.0.0',
description: 'API 文档(基于 OpenAPI 3.0 & swagger-jsdoc 自动生成)',
},
servers: [
{
url: baseUrl,
description: 'API Base',
},
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT', // 你的路由使用 authenticate 中间件(Bearer Token) [2](https://waikatouniversitynz-my.sharepoint.com/personal/jl1132_students_waikato_ac_nz/Documents/Microsoft%20Copilot%20Chat%20Files/ai.routes.js)
},
},
// 如需统一错误/响应模型,可在此定义 schemas 并通过 $ref 引用
// schemas: { ... }
},
security: [{ bearerAuth: [] }],
};
const swaggerOptions = {
definition: swaggerDefinition,
apis: [
'./routes/*.js', // 扫描路由文件中的 @openapi JSDoc 注释
'./controllers/*.js' // 如你在 controller 中补充注释,可一并扫描
],
};
const swaggerSpec = swaggerJSDoc(swaggerOptions);
// Swagger UI 与原始 JSON
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, { explorer: true }));
app.get('/docs.json', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerSpec);
});
// -----------------------------
// Route loader (handles CJS/ESM)
// -----------------------------
function loadRouter(path, name) {
// Require the module
const mod = require(path);
// Support both CJS (module.exports = router) and ESM default exports
const candidate = typeof mod === 'function'
? mod
: (mod && typeof mod.default === 'function' ? mod.default : mod);
// Validate it's a Router (Routers are callable middleware and have a .stack array)
const isRouter =
typeof candidate === 'function' &&
(Array.isArray(candidate.stack) || typeof candidate.use === 'function');
if (!isRouter) {
// Helpfully show what we actually got
const type = typeof candidate;
const keys = candidate && typeof candidate === 'object' ? Object.keys(candidate) : [];
throw new TypeError(
`[Route Mount Error] ${name} must export an Express Router function.\n` +
`Got: ${type}${keys.length ? ` with keys: ${keys.join(', ')}` : ''}\n` +
`Fix: ensure the route file ends with "module.exports = router" (CommonJS).`
);
}
return candidate;
}
/* -----------------------------
Import routers with validation
------------------------------ */
const usersRoutes = loadRouter('./routes/users.routes', 'users.routes');
const promptsRoutes = loadRouter('./routes/prompts.routes', 'prompts.routes');
const storiesRoutes = loadRouter('./routes/stories.routes', 'stories.routes');
const aiRoutes = loadRouter('./routes/ai.routes', 'ai.routes');
/* -----------------------------
Routes
------------------------------ */
app.use('/api/users', usersRoutes);
app.use('/api/prompts', promptsRoutes);
app.use('/api/stories', storiesRoutes);
app.use('/api/ai', aiRoutes);
// Health probes
app.get('/health', (_, res) => res.status(200).send('OK'));
app.get('/ready', (_, res) => res.status(200).json({ status: 'ready' }));
/* -----------------------------
404 & Error Handling
------------------------------ */
app.use((req, res) => {
res.status(404).json({
error: 'NotFound',
message: 'The requested resource was not found.',
});
});
app.use((err, req, res, next) => {
const status = err.status || err.statusCode || 500;
const isProd = process.env.NODE_ENV === 'production';
const payload = {
error: err.name || 'InternalServerError',
message: isProd ? 'An unexpected error occurred.' : err.message,
};
if (!isProd) payload.stack = err.stack;
console.error('❌', err.message);
res.status(status).json(payload);
});
module.exports = app;
/* -----------------------------
Bootstrap (DB before listen)
------------------------------ */
// Start server only if not in test mode
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
}