You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
3.5 KiB
102 lines
3.5 KiB
// | ------------------------------------------------------------
|
|
// | @版本: version 0.1
|
|
// | @创建人: 【Nie-x7129】
|
|
// | @E-mail: x71291@outlook.com
|
|
// | @所在项目: initkoa
|
|
// | @文件描述: app.js - Koa项目的入口文件
|
|
// | @创建时间: 2023-11-25 20:58
|
|
// | @更新时间: 2023-11-25 20:58
|
|
// | @修改记录:
|
|
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
|
// | =
|
|
// | ------------------------------------------------------------
|
|
|
|
import Koa from 'koa';
|
|
import koaLogger from 'koa-logger';
|
|
import compress from 'koa-compress';
|
|
import ratelimit from 'koa-ratelimit';
|
|
import handleError from 'koa-json-error';
|
|
import { koaBody } from 'koa-body';
|
|
import { userAgent } from 'koa-useragent';
|
|
|
|
import rootRouter from '#routes/index.js';
|
|
|
|
export default function startApp() {
|
|
const app = new Koa();
|
|
if (global.ENV === 'development') {
|
|
// | 开启自带日志
|
|
app.use(koaLogger());
|
|
}
|
|
|
|
if (config.ratelimit.status) {
|
|
// | 限制同一用户的频繁请求
|
|
app.use(
|
|
ratelimit({
|
|
driver: 'memory', // 存储限流数据的驱动,这里使用内存驱动
|
|
db: new Map(), // 存储被限制的客户端信息的数据结构
|
|
duration: config.ratelimit.duration, // 时间窗口,单位毫秒
|
|
max: config.ratelimit.max, // 时间窗口内允许的最大请求数量
|
|
id: (ctx) => ctx.ip, // 提取每个请求的唯一标识符,默认使用请求的 IP 地址
|
|
}),
|
|
);
|
|
}
|
|
|
|
app.use(
|
|
handleError({
|
|
format: (err) => {
|
|
// 返回错误的格式
|
|
return {
|
|
code: err.status,
|
|
message: err.message,
|
|
result: ENV === 'development' && err.stack,
|
|
};
|
|
},
|
|
postFormat: (err, obj) => {
|
|
//根据不同环境,返回不同格式的错误信息
|
|
const { result, ...rest } = obj;
|
|
return process.env.NODE_ENV == 'production' ? rest : obj;
|
|
},
|
|
}),
|
|
);
|
|
|
|
if (global.zip === true) {
|
|
// | koa-compress 是一个 Koa 中间件,用于压缩 HTTP 响应。使用该中间件可减少 HTTP 响应的大小,从而提升应用程序的性能。
|
|
app.use(compress());
|
|
}
|
|
app.use(userAgent);
|
|
|
|
app.use(
|
|
koaBody({
|
|
multipart: true, // 支持文件上传
|
|
encoding: 'gzip',
|
|
formidable: {
|
|
// uploadDir:path.join(__dirname,'public/upload/'), // 设置文件上传目录
|
|
keepExtensions: true, // 保持文件的后缀
|
|
maxFileSize: config.upfile.maxFileSize, // 文件上传大小
|
|
maxFieldsSize: config.request.maxFieldsSize, // 除文件外的数据大小
|
|
onFileBegin: (name, file) => {
|
|
// 文件上传前的设置
|
|
},
|
|
hashAlgorithm: config.upfile.hashAlgorithm,
|
|
},
|
|
}),
|
|
);
|
|
|
|
// app.use(async (ctx, next) => {
|
|
// // console.log(ctx.request.files.file)
|
|
// // console.log(ctx.request.body)
|
|
// // console.log(ctx.userAgent)
|
|
// console.log(ctx.ip);
|
|
// ctx.throw(520, '欣赏欣赏');
|
|
// ctx.body = 'xs';
|
|
// });
|
|
|
|
app.use(rootRouter.routes());
|
|
app.use(rootRouter.allowedMethods());
|
|
|
|
// console.log(rootRouter)
|
|
|
|
// const routes = rootRouter.stack.map((route) => route.path);
|
|
|
|
return app;
|
|
}
|
|
|