跳至正文
Wener Notes

fastify

约 3 分钟阅读
    • MIT, JS+d.ts
    • 目前性能最好
    • 推荐使用 schema 校验输入输出
  • 参考

生命周期

phasehookabort
Incoming
Routing
Instance Logger
onRequest4xx,5xx
preParsing4xx,5xx
Parsing4xx,5xx
preValidation4xx,5xx
Validation400
preHandler4xx,5xx
User Handler4xx,5xx
Reply
preSerialization4xx,5xx
onSend
Outgoing Response4xx,5xx
onResponse

路由

  • /data/*
    • req.prams['*'] 获取之后的参数

Awesome


TypeScript
const warning = require('process-warning')();
warning.create('FastifyDeprecation', 'FST_ERROR_CODE', 'message');
warning.emit('FST_ERROR_CODE');

nextjs

JavaScript
const fastify = require('fastify')();

fastify.register(require('@fastify/nextjs')).after(() => {
  fastify.next('/*');
});

fastify.listen(3000, (err) => {
  if (err) throw err;
  console.log('Server listening on http://localhost:3000');
});

@fastify/autoload

TypeScript
fastify.register(Autoload, {
  dir: path.join(__dirname, 'plugins'),
  dirNameRoutePrefix: false
  // ignorePattern
  // indexPattern
  forceESM: true,
  // fastify-plugin
  encapsulate: false
})

@fastify/static

TypeScript
fastify.register(require('@fastify/static'), {
  root: path.join(__dirname, 'public'),
  prefix: '/public/', // optional: default '/'
});

fastify-cli

bash
npm add -g fastify-cli

# fastify
# fastify-plugin
# fastify-cli
# @fastify/sensible
# https://github.com/tapjs/node-tap
fastify generate my-server --lang=ts

cd my-server
npm install # dependencies
npm start   # build:ts - fastify start -l info dist/app.js
npm build:ts
npm run dev # build:ts - watch:ts+dev:start pino-colada pretty logging
npm test
依赖包

eject

  • 生成 server
TypeScript
// Read the .env file.
import * as dotenv from 'dotenv';
dotenv.config();

// Require the framework
import Fastify from 'fastify';

// Require library to exit fastify process, gracefully (if possible)
import closeWithGrace from 'close-with-grace';

// Instantiate Fastify with some config
const app = Fastify({
  logger: true,
});

// Register your application as a normal plugin.
app.register(import('./app'));

// delay is the number of milliseconds for the graceful close to finish
const closeListeners = closeWithGrace({ delay: 500 }, async function ({ signal, err, manual }) {
  if (err) {
    app.log.error(err);
  }
  await app.close();
} as closeWithGrace.CloseWithGraceAsyncCallback);

app.addHook('onClose', async (instance, done) => {
  closeListeners.uninstall();
  done();
});

// Start listening.
app.listen({ port: parseInt(process.env.PORT) || 3000 }, (err: any) => {
  if (err) {
    app.log.error(err);
    process.exit(1);
  }
});

ajv

TypeScript
const defaultAjvOptions = {
  coerceTypes: 'array',
  useDefaults: true,
  removeAdditional: true,
  uriResolver: fastUri,
  addUsedSchema: false,
  // Explicitly set allErrors to `false`.
  // When set to `true`, a DoS attack is possible.
  allErrors: false,
};

Version

Fastify 5

  • Node 20+

FAQ

You cannot use send inside the onError hook

Request body is too large

默认 1MiB

FST_ERR_CTP_INVALID_MEDIA_TYPE

FST_ERR_CTP_INVALID_CONTENT_LENGTH

  • post multipart/form

关联信息

反向链接、本文链接的其他页面和外部资料。

反向链接

  • Nodejs Awesome
    笔记 · fastify

    最好选择 TypeScript 开发的或支持 TypeScript 的 · TypeScript 的 decorator 比 Java 的 Annotation 弱得多 · 不支持获取字段实际类型信息 - 因为不存在这样的信息 · 最近一两年 (2020-2021),可能是因为 Go 和 Rust 的盛行,导致 Nodejs 的后端开发弱化了,很多项目...

参考资料

GitHub16 条
其他外链5 条
最近更新commit affb38b编辑