@forrestjs/service-fastify

中文文档
5.2.2发布于 2024/03/18MITCommonJS近 30 天下载 7939

ForrestJS service which helps setting up a Fastify server.

原始使用文档
文档目录21 节
  1. Install & Setup
  2. Configuration & Environment
  3. 📝 fastify.port
  4. 📝 fastify.instance.options
  5. 📝 fastify.tdd.scope
  6. Context
  7. 🌎 fastify
  8. 🌎 axios
  9. Testing Support
  10. Test Healthcheck
  11. Test APIs
  12. Extensions
  13. 🧩 $FASTIFY_OPTIONS
  14. 🧩 $FASTIFY_HACKS_BEFORE
  15. 🧩 $FASTIFY_HACKS_AFTER
  16. 🧩 $FASTIFY_PLUGIN
  17. 🧩 $FASTIFY_ROUTE
  18. 🧩 $FASTIFY_TDD_RESET
  19. 🧩 $FASTIFY_TDD_CHECK
  20. 🧩 $FASTIFY_TDD_ROOT
  21. 🧩 $FASTIFY_TDD_ROOT

@forrestjs/service-fastify

ForrestJS service which helps setting up an FastifyJS server.

DEMO:
https://codesandbox.io/s/service-fastify-th8dq

Install & Setup

npm add @forrestjs/service-fastify

Set it up in your FastifyJS App:

// index.js
const forrestjs = require('@forrestjs/core');
const fastifyService = require('@forrestjs/service-fastify');

// Create an Home Page for the Web App
const homePage = () => ({
  target: '$FASTIFY_ROUTE',
  handler: [
    {
      method: 'GET',
      url: '/',
      handler: async () => `Hello World`,
    },
  ],
});

// Run the App:
forrestjs.run({
  settings: {
    fastify: {
      port: 8080,
    },
  },
  services: [fastifyService],
  features: [homePage],
});

Configuration & Environment

📝 fastify.port

Sets up the port on which the server will listen for requests.

It falls back to environment variables:

  • process.env.REACT_APP_PORT
  • process.env.PORT
  • 8080 (default value)

📝 fastify.instance.options

Let you pass arbitrary configuration to the Fastify instance.

📝 fastify.tdd.scope

Let you setup the root of the testing APIs.

Default: /test


Context

The ForrestJS App will be decorated with:

🌎 fastify

A reference to the Fastify instance as configured during the booting of the App. It allows to fully manipulate the running server.

const fastify = getContext('fastify');

🌎 axios

A reference to the static instance of Axios.

const axios = getContext('axios');
await axios.get('/');

Testing Support

Service Fastify ships testing facilities with the goal of making end-2-end testing easy for you.

The idea is to let the testing enviornment interact with the Fastify instance using REST APIs that are available exclusively whith process.env.NODE_ENV set to:

  • development
  • test

🔥 You must also pass the environmental variable 🔥

DANGEROUSLY_ENABLE_FASTIFY_TDD_ENDPOINT=yes

Those test-specific APIs are exposed under a /test/... root that you can change by setting fastify.tdd.root.

Test Healthcheck

The root Route /test acts as healthcheck for running tests. Any test client should await for a 200 reply from this endpoint before attempting to run any call.

By default there is no logic to this healthcheck, but you can interact with by implementing two extensions:

  • $FASTIFY_TDD_CHECK
  • $FASTIFY_TDD_ROOT

Test APIs

get://test/reset

Runs the $FASTIFY_TDD_RESET handlers to reset the App's state.

get://test/config?key=foobar&value=123

Reads a configuration value from the App

post://test/config { key: 'foobar', value: 555 }

Writes a configuration value into the App

post://test/axios/stubs

delete://test/axios/stubs


Extensions

All the extensions exposed by service-fastify are synchronous and executes in serie.

🧩 $FASTIFY_OPTIONS

It allows to programmatically modify the options that are given to the Fastify's instance, it works in waterfall.

registerAction({
  target: '$FASTIFY_OPTIONS',
  handler: (defaultOptions) => ({
    ...defaultOptions,
    logger: true,
  }),
});

🧩 $FASTIFY_HACKS_BEFORE

This hook fires before any other step.
It receives a direct reference to the fastify instance.

registerAction({
  target: '$FASTIFY_HACKS_BEFORE',
  handler: ({ fastify }) => {
    // Do something with the Fastify's instance
    fastify.register();
  },
});

🧩 $FASTIFY_HACKS_AFTER

This hook fires after any other step.
It receives a direct reference to the fastify instance.

registerAction({
  target: '$FASTIFY_HACKS_AFTER',
  handler: ({ fastify }) => {
    // Do something with the Fastify's instance
    fastify.register();
  },
});

🧩 $FASTIFY_PLUGIN

Let register Fastify plugins or decorate the instance.

registerAction({
  hook: '$FASTIFY_PLUGIN',
  handler: ({ registerPlugin }) => {
    registerPlugin(/* fastify plugin */);
    registerPlugin(/* fastify plugin */);
  },
});

It also receives API for decorating the Fastify instance:

registerAction({
  hook: '$FASTIFY_PLUGIN',
  handler: ({ decorateRequest }) => {
    const user = { name: 'Marco' };
    decorateRequest('user', user);
  },
});

🧩 $FASTIFY_ROUTE

Lets implement first level routes in your Fastify instance:

// With the API:
registerAction({
  target: '$FASTIFY_ROUTE',
  handler: ({ registerRoute }) =>
    registerRoute({
      method: 'GET',
      url: '/',
      handler: (req, res) => res.send('Hello World'),
    }),
});

// With direct values:
registerAction({
  target: '$FASTIFY_ROUTE',
  handler: () => ({
    method: 'GET',
    url: '/',
    handler: (req, res) => res.send('Hello World'),
  }),
});

// With multiple routes
registerAction({
  target: '$FASTIFY_ROUTE',
  handler: () => [
    {
      method: 'GET',
      url: '/p1',
      handler: (req, res) => res.send('Page1'),
    },
    {
      method: 'GET',
      url: '/p2',
      handler: (req, res) => res.send('Page2'),
    },
  ],
});

🧩 $FASTIFY_TDD_RESET

Let you inject state reset logic from any Service or Feature.

Tests will then call /test/reset in order to trigger an App's state reset.

registerAction({
  target: '$FASTIFY_TDD_CHECK',
  handler: ({ registerTddReset }) => {
    registerTddCheck(async ({ getContext }) => {
      const pg = getContext('pg');
      return pg.query('DROP SCHEMA "public" CASCADE');
    });
  },
});

🧩 $FASTIFY_TDD_CHECK

Let you inject preHandlers to the /test route.

Use this to await for database connections or other preconditions.

registerAction({
  target: '$FASTIFY_TDD_CHECK',
  handler: ({ registerTddCheck }) => {
    // Middleware style
    registerTddCheck((request, reply, next) => {
      console.log('Healthcheck with callback');
      next();
    });

    // Async style
    registerTddCheck(async (request, reply) => {
      console.log('Asynchronous healthcheck');
    });
  },
});

🧩 $FASTIFY_TDD_ROOT

Let you implement the returning body of the /test route.

registerAction({
  target: '$FASTIFY_TDD_ROOT',
  name: 'registerTddRoute',
  handler: () => (request, reply) => reply.send('ok'),
});

🧩 $FASTIFY_TDD_ROOT

Let you extend the /test API with custom sub-routes.

It works exactly as $FASTIFY_ROUTE, but all the routes you define are scoped with the testing prefix.

版本与发布记录

@forrestjs/service-fastify 共发布 169 个版本,首次发布于 2020/08/02;过去 12 个月发布了 0 个版本。

版本发布日期距今
5.2.2latest2024/03/182 年前
5.2.12023/03/223 年前
5.2.02023/03/223 年前
5.1.12023/03/213 年前
5.1.02023/03/213 年前
5.0.62023/03/203 年前

关于 @forrestjs/service-fastify 的常见问题

@forrestjs/service-fastify 是什么?

ForrestJS service which helps setting up a Fastify server.

如何安装 @forrestjs/service-fastify?

在项目目录运行 npm install @forrestjs/service-fastify,或使用 pnpm add / yarn add / bun add。

@forrestjs/service-fastify 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/forrestjs__service-fastify 是否存在。

@forrestjs/service-fastify 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@forrestjs/service-fastify 可以商用吗?

@forrestjs/service-fastify 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@forrestjs/service-fastify 的下载量有多少?

根据 npm 官方下载统计,@forrestjs/service-fastify 在 2026/10/16 – 2026/11/14 这 30 天内被下载 7,939 次,日均约 265 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@forrestjs/service-fastify 还在维护吗?

最新版本 5.2.2 发布于 2024/03/18(2 年前);至今共发布 169 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/08/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。