alioth/before/cha/15=hutao/app.js
2025-05-30 09:18:01 +08:00

136 lines
4.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// | ------------------------------------------------------------
// | @版本: version 0.1
// | @创建人: 【Nie-x7129】
// | @E-mail: x71291@outlook.com
// | @所在项目: hutao
// | @文件描述: app.js -
// | @创建时间: 2024-03-15 11:38
// | @更新时间: 2024-03-15 11:38
// | @修改记录:
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
// | =
// | ------------------------------------------------------------
import config from "config";
import Fastify from "fastify";
import {isLowerCase, isTrim} from "#plugins/ajv/index.js";
import ajvErrors from "ajv-errors";
import chalk from "chalk";
import {destr} from 'destr'
global.tostr = JSON.stringify
global.destr = destr
const fastify = Fastify({
ajv: {
customOptions: {
removeAdditional: true,
useDefaults: true,
coerceTypes: true,
allErrors: true,
// 允许使用联合模式 严格模式下
allowUnionTypes: true
},
plugins: [
ajvErrors,
// 这种方式完美解决,开心, 实际上这是一个函数会传进去ajv实例对象
isLowerCase,
isTrim,
]
}
})
fastify.decorate('color', chalk)
fastify.decorate('config', config)
fastify.decorate('authenticate', async function (request, reply) {
try {
// 校验token并生成request的user参数
await request.jwtVerify();
} catch (err) {
// token校验未通过记录错误
fastify.log.debug({reqId: request.id, Auth: err.message});
reply.code(err.statusCode).send({
statusCode: err.statusCode,
message: err.message,
error: err.name
});
}
});
// | 插件
// @ 注册日志记录
await fastify.register(import("#common/logger/index.js"))
// @ 注册数据库
await fastify.register(import("#plugins/sequelize/index.js"))
// @ 注册redis
await fastify.register(import('@fastify/redis'), {
// 配置文件基础redis配置 hostportpassword
host: '172.16.1.10',
port: 6379,
password: 'Hxl1314521',
// fastify调用的名称空间
namespace: 'db1',
// 指向的redis数据库0-15
db: 1,
// 4 (IPv4) or 6 (IPv6)
family: 4,
// redis连接中的名字
connectionName: 'global.conf.projectName'
});
// @ 注册防止恶意请求封ip
await fastify.register(import('@fastify/rate-limit'), {
// 限制每个 IP 地址在时间窗口内最多可以发出的请求数
max: 500,
// '1 second' = '1000'1 秒 | '1 minute' 1 分钟 | '1 hour' 1 小时 | '1 day' 1 天 | '1 week' 1 周
timeWindow: '1 day'
});
// @ 注册错误处理工具
await fastify.register(import('@fastify/sensible'));
// @ 注册jwt
await fastify.register(import('@fastify/jwt'), {
// token的加密值
secret: 'xadvdgfhga21xabhgnumo;opilkujya8axa21',
sign: {
// token过期时间
expiresIn: '20m'
}
});
// @ 注册路由
await fastify.register(import('#routes/index.js'), {prefix: '/api'})
// @ 发送消息拦截
fastify.addHook('onSend', async (request, reply, payload) => {
// fastify.log.info(reply.getHeader('content-type'));
if (reply.statusCode === 200 && !request.url.includes('/api/file')) {
if(['{', '"'].indexOf(payload.trim().slice(0, 1)[0]) > -1){
return `{"statusCode": 200, "status": "success", "data": ${payload}}`;
}else{
reply.header('Content-Type', 'application/json');
return `{"statusCode": 200, "status": "success", "data": "${payload}"}`;
}
}
return payload;
});
// @ 错误拦截
fastify.setErrorHandler(async (error, request, reply) => {
// 自定义错误处理逻辑
fastify.log.error(error);
reply
.code(error.statusCode)
.send({
statusCode: error.statusCode,
message: error.message,
error: error.name
});
});
fastify.logger.info(await fastify.redis.db1.set('name', 'xsx', 'EX', 60));
// console.log(fastify.data)
fastify.listen({
port: config.get('port')
}).then(resd => {
console.log(`http://127.0.0.1:${config.get('port')}`)
})