バックエンドNode.js APIを構築するための基盤となるFastifyプラグイン
2024年5月28日
18 分で読めますバックエンドNode.js APIの
Fastifyは
Fastifyとそのプラグインが堅牢なバックエンドNode.js APIを実現する理由
最新の
最新のESMをサポート
Fastifyは
ESMを
import fastify from 'fastify';
const server = fastify();
server.get('/', async (request, reply) => {
return { hello: 'world' }
});
server.listen({port: 3000}, (err, address) => {
if (err) throw err
server.log.info(`Server listening at ${address}`)
});async/awaitとPromiseを使った適切なルート定義
Fastifyでは、
Expressはtry/catchブロックで
Fastifyで
server.get('/api/tasks', async (request, reply) => {
const tasks = await Tasks.findAll();
return tasks;
});高速なラディックス木によるルート解決で高いパフォーマンスを実現
Fastifyは
カプセル化に対応した豊富なFastifyプラグインアーキテクチャ
Fastifyには、
ユーティリティ関数で
import fp from 'fastify-plugin';
export default fp(async function (fastify, opts) {
fastify.decorate('utility', () => 'This is a utility function');
});この
// import and get a fastify server instance,
// and then:
server.register(import('./utility-plugin.js'));
server.get('/', async (request, reply) => {
return server.utility();
});軽量な依存性注入
Fastifyの
次の
fastify.register(async function (fastify, opts) {
const db = await someDbConnectionLibrary(opts.connectionString);
fastify.decorate('db', db);
});Fastifyで作るシンプルなバックエンドNode.js API
この
さらに、
まず、
$ mkdir fastify-app && cd fastify-app
$ npm init -y
$ npm install --save fastifyESMをpackage.jsonファイルをtype: moduleキーを
{
"type": "module",
}続いて、server.jsファイルに、
// Import Fastify using ESM syntax
import Fastify from "fastify";
const fastify = Fastify({ logger: true });
// Defining a route
fastify.get("/", async (request, reply) => {
return { hello: "world" };
});
async function startServer() {
try {
// Start the server
const address = await fastify.listen({
port: 3000,
host: "localhost",
});
// Log the server start information using the address returned by Fastify
// Fastify will already log the server start information by default
// But here is an example of how you can log the server start information
// fastify.log.info(`Server starting up at ${address}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
}
startServer();APIルートをFastifyプラグインにカプセル化する
Fastifyでは、
「Hello World」
const fastify = require('fastify')({ logger: true });
const helloRoute = async (fastify, options) => {
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
};
fastify.register(helloRoute);
const start = async () => {
try {
await fastify.listen(3000);
fastify.log.info(`server listening on ${fastify.server.address().port}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();ルートのリクエストスキーマとレスポンススキーマを使う
Fastifyでは、
「Hello World」
const helloRoute = async (fastify, options) => {
fastify.route({
method: 'GET',
url: '/',
schema: {
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' },
},
},
},
},
handler: async (request, reply) => {
return { hello: 'world' };
},
});
};
fastify.register(helloRoute);これで
Fastifyアプリケーションの構築要素となるFastifyプラグイン
この@fastify/pino、@fastify/cors、@fastify/env、@fastify/swaggerと@fastify/swagger-uiを
Fastify向けPinoロガー
Pinoは、
Fastifyの{ logger: true }を
開発中は、pino-prettyパッケージをpinoとpino-prettyを
npm install --save pino pino-pretty次に、pino-prettyを
import pino from "pino";
const logger = pino({
transport: {
target: "pino-pretty",
options: {
colorize: true,
},
},
});
logger.info("Hello from pino-pretty");
const fastify = Fastify({
logger: logger,
});上記では、colorizeオプションをpino-prettyをlogger変数をloggerオプションに
これに
[12:13:43.499] INFO (95477): hello from pino-pretty
[12:13:43.517] INFO (95477): Server listening at http://[::1]:3000
[12:13:43.518] INFO (95477): Server listening at http://127.0.0.1:3000Fastifyで
高速な
ロギング:Pinoは、 Node.jsで 最速の ロガーを 目指して 開発されています。 柔軟な
ロガー:さまざまな ログレベルに 対応し、 ログを JSON形式で 出力できます。
Fastifyプラグイン@fastify/cors
@fastify/corsプラグインを
メリット:
安全性:異なる
オリジン間の データの 流れを 管理できます。 カスタマイズ性:CORSオプションを
設定する カスタム関数を 定義できます。
@fastify/corsプラグインを
// after creating the fastify instance
// let's register the fastify cors plugin:
fastify.register(require('@fastify/cors'), {
origin: '*',
methods: ['GET','POST', 'PUT', 'DELETE']
})Fastifyサーバーに
curl -i http://localhost:3000レスポンスにAccess-Control-Allow-Originヘッダーが
HTTP/1.1 200 OK
access-control-allow-origin: *
content-type: application/json; charset=utf-8
content-length: 17
Date: Sun, 18 Feb 2024 10:20:15 GMT
Connection: keep-alive
Keep-Alive: timeout=72Fastifyプラグイン@fastify/env
Node.js開発者が.envファイルが
ここで@fastify/envです。dotenvや--env-fileも
@fastify/envプラグインを.envファイルを
npm install --save @fastify/env
echo "PORT=3001" > .env次にserver.jsの
fastify.register(import('@fastify/env'), {
dotenv: true,
schema: {
type: 'object',
required: [ 'PORT' ],
properties: {
PORT: {
type: 'string',
default: 3000
}
}
}
})Fastify@fastify/envを.envファイルでfastify.configオブジェクトから
Fastifyのfastify.configオブジェクトに
そこで、startServer()関数を
try {
// wait for all plugins to run
await fastify.ready();
// Start the server
const address = await fastify.listen({
// now we can access the fastify.config.PORT configuration
port: fastify.config.PORT,
host: "localhost",
});@fastify/envプラグインを
環境変数の
検証:必須の 環境変数が 設定されている ことを 確認します。 型変換:環境変数を
必要な 型に 変換します。 軽量な
依存性 注入: fastifyアプリケーションのインスタンスに アクセスできる 場所なら どこでも、 設定を 簡単に 共有できます。
@fastify/swaggerと@fastify/swagger-ui FastifyプラグインでバックエンドNode.js APIをドキュメント化する
@fastify/swaggerプラグインは、@fastify/swagger-uiは
これまでと
npm install --save @fastify/swagger @fastify/swagger-ui次に、server.jsファイルで
fastify.register(import('@fastify/swagger'), {
routePrefix: '/documentation',
swagger: {
info: {
title: 'Test swagger',
description: 'testing the fastify swagger api',
version: '0.1.0'
},
host: 'localhost',
schemes: ['http'],
consumes: ['application/json'],
produces: ['application/json']
},
exposeRoute: true
})
fastify.register(import('@fastify/swagger-ui'))Fastifyサーバーをhttp://localhost:3001/documentationを

セキュリティに
メリット:
APIドキュメントを
簡単に 作成:APIドキュメントを 自動生成します。 カスタマイズ性:ドキュメントページを
カスタマイズできます。
まとめ
ここまでpinoとpino-prettyで@fastify/corsで@fastify/envで@fastify/swaggerと@fastify/swagger-uiで
Fastify
モジュール型開発を
生産性と
さらなる
Fastify



