oa_based/src/common/adapters/fastify.adapter.ts

46 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-02-28 17:02:46 +08:00
import FastifyCookie from '@fastify/cookie';
import FastifyMultipart from '@fastify/multipart';
import { FastifyAdapter } from '@nestjs/platform-fastify';
2024-02-28 08:32:35 +08:00
const app: FastifyAdapter = new FastifyAdapter({
trustProxy: true,
2024-02-29 09:29:03 +08:00
logger: false
2024-02-28 08:32:35 +08:00
// forceCloseConnections: true,
2024-02-28 17:02:46 +08:00
});
export { app as fastifyApp };
2024-02-28 08:32:35 +08:00
app.register(FastifyMultipart, {
attachFieldsToBody:true,
2024-02-28 08:32:35 +08:00
limits: {
fields: 10, // Max number of non-file fields
2024-04-11 09:05:58 +08:00
fileSize: 1024 * 1024 * 50, // limit size 50M
2024-02-29 09:29:03 +08:00
files: 5 // Max number of file fields
}
2024-02-28 17:02:46 +08:00
});
2024-02-28 08:32:35 +08:00
app.register(FastifyCookie, {
2024-02-29 09:29:03 +08:00
secret: 'cookie-secret' // 这个 secret 不太重要,不存鉴权相关,无关紧要
2024-02-28 17:02:46 +08:00
});
2024-02-28 08:32:35 +08:00
app.getInstance().addHook('onRequest', (request, reply, done) => {
// set undefined origin
2024-02-28 17:02:46 +08:00
const { origin } = request.headers;
if (!origin) request.headers.origin = request.headers.host;
2024-02-28 08:32:35 +08:00
// forbidden php
2024-02-28 17:02:46 +08:00
const { url } = request;
2024-02-28 08:32:35 +08:00
if (url.endsWith('.php')) {
2024-02-28 17:02:46 +08:00
reply.raw.statusMessage =
'Eh. PHP is not support on this machine. Yep, I also think PHP is bestest programming language. But for me it is beyond my reach.';
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
return reply.code(418).send();
2024-02-28 08:32:35 +08:00
}
// skip favicon request
2024-02-28 17:02:46 +08:00
if (url.match(/favicon.ico$/) || url.match(/manifest.json$/)) return reply.code(204).send();
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
done();
});