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.
 
 
 
 
 
hutao/app.js

135 lines
4.1 KiB

// | ------------------------------------------------------------
// | @版本: 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配置 host,port,password
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')}`)
})