ファストファイとは何ですか?
Fastify は、最小限のオーバーヘッドと強力なプラグイン アーキテクチャで可能な限り最高の開発エクスペリエンスを提供することに重点を置いた Web フレームワークです。これは Hapi と Express からインスピレーションを得たもので、私たちが知る限り、Node.js 上で動作する最速の Web フレームワークの 1 つです。
Fastify を使用する理由
これらは fasttify の主な機能と原則です
-
高いパフォーマンス: 私たちが知る限り、Fastify は最速の Web フレームワークの 1 つであり、コードの複雑さに応じて 1 秒あたり最大 30,000 のリクエストを処理できます。
-
拡張可能: Fasttify はフック、プラグイン、デコレーターを通じて完全に拡張可能です。
-
スキーマベース: 必須ではない場合でも、ルートの検証と出力のシリアル化には JSON スキーマを使用することをお勧めします。内部で fasttify がスキーマをパフォーマンス関数でコンパイルします。
-
ロギング: ロギングは非常に重要ですが、高価です。ロギングには最高のロガーがあり、自分で手動で追加する必要はありません。
-
開発者に優しい: このフレームワークは非常に表現力が豊かで、パフォーマンスとセキュリティを犠牲にすることなく開発者が日常的に使用できるように支援します。
-
TypeScript: 拡大する TypeScript のサポート
すぐに始めましょう
最初のサービスをインストールして実行する
まず、次のコマンドを使用して新しい Fastify プロジェクトを作成します。
npm i fastify
サーバーを作成する
プロジェクトのルート ディレクトリに app.js ファイルを作成します
// CommonJs
const fastify = require('fastify')({
logger: true
})
// Declare a route
fastify.get('/', function (request, reply) {
reply.send({ hello: 'world' })
})
// Run the server!
fastify.listen({ port: 8081 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
console.log(`Server is now listening on ${address}`)
})
このコードは、リスニング ポート 8081 がサーバーを起動することを示しています。
サービスを開始する
次のように、node コマンドを使用して app.js ファイルを実行します。
node app.js
テストサービス
ブラウザを使用して http://127.0.0.1:8081/ を開きます。
さて、ここまでで、Fastify の基本サービスがどのように構築され、運用されるかについて予備的に理解しました。その後、詳細な紹介に入ります。
詳しく使う
非同期/待機を使用する
async/await の使用を好みますか? Fastify は、そのままの状態でサポートしています。
// ESM
import Fastify from 'fastify'
const fastify = Fastify({
logger: true
})
// CommonJs
const fastify = require('fastify')({
logger: true
})
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
/**
* Run the server!
*/
const start = async () => {
try {
await fastify.listen({ port: 3000 })
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
最初のプラグインを開始します - ルーティング
- JavaScript ではすべてがオブジェクトですが、fasttify ではすべてがプラグインです。
- 次にルーティングファイルを宣言するのですが、これを別途抽出して入り口の外に置く必要があります。
- ルーティング宣言ドキュメントを表示します: https://www.fastify.cn/docs/latest/Reference/Routes/
ルーティングファイルの作成
ルートディレクトリにroute.jsを作成します。
/**
* Encapsulates the routes
* @param {FastifyInstance} fastify Encapsulated Fastify Instance
* @param {Object} options plugin options, refer to https://www.fastify.io/docs/latest/Reference/Plugins/#plugin-options
*/
async function routes (fastify, options) {
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
}
module.exports = routes
ルーティングファイルを登録する
app.jsを変更する
// fastify.get('/', async (request, reply) => {
// return { hello: 'world' }
// })
に変更されました
fastify.register(require('./route'))
サービスを開始してテストする
ノードコマンドを使用して実行します
node app.js
ブラウザを使用して http://127.0.0.1:8081/ を開きます。
これまでのところ、ルートが作成されています。非常に簡単ですか? Fasttify がインターフェイス呼び出しを実装するために async await を提供していることがわかります。データベースに接続するときに、データを読み取る前にデータベースが利用可能であることを確認する必要があるため、これは非常に重要です。この時点では、async を使用する必要があります。 、一緒に試してみましょう
データベース接続性
postgres データベースを例に挙げてみましょう
前提条件
データベースのURLが必要です。作成されたデータベースは使用できます~~
依存関係をインストールする
npm i fastify-plugin
npm i pg @fastify/postgres
関連ドキュメント
https://www.npmjs.com/package/@fastify/postgres
https://www.fastify.cn/docs/latest/Guides/Getting-Started/
プラグインを書く
ルートディレクトリにpostgres-connector.jsを作成します。
/**
* @type {import('fastify-plugin').FastifyPlugin}
*/
const fastifyPlugin = require('fastify-plugin')
/**
* Connects to a postgres database
* @param {FastifyInstance} fastify Encapsulated Fastify Instance
* @param {Object} options plugin options, refer to https://www.fastify.io/docs/latest/Reference/Plugins/#plugin-options
*/
async function dbConnector (fastify, options) {
fastify.register(require('@fastify/postgres'), {
connectionString: 'postgresql://名字:密码@数据库服务器名:端口号/数据库名'
})
}
// Wrapping a plugin function with fastify-plugin exposes the decorators
// and hooks, declared inside the plugin to the parent scope.
module.exports = fastifyPlugin(dbConnector)
プラグインの登録
app.js を開いて、作成したプラグインを登録します
fastify.register(require('./postgres-connector'))
テストインターフェースの追加
Route.js を開き、テスト インターフェイス コードを追加します
/**
* Encapsulates the routes
* @param {FastifyInstance} fastify Encapsulated Fastify Instance
* @param {Object} options plugin options, refer to https://www.fastify.io/docs/latest/Reference/Plugins/#plugin-options
*/
async function routes(fastify, options) {
fastify.get("/", async (request, reply) => {
return { hello: "world" };
});
fastify.get("/test", async (req, reply) => {
const client = await fastify.pg.connect();
try {
const { rows } = await client.query("SELECT id, name FROM tests");
// Note: avoid doing expensive computation here, this will block releasing the client
return rows;
} finally {
// Release the client immediately after query resolves, or upon error
client.release();
}
});
}
module.exports = routes;
サービステストを開始する
node app.js
データベース情報の取得に成功しました
要約する
-
上の図からわかるように、データベース コネクタとルート登録の両方に register を使用します。
-
これは Fastify の最も優れた機能の 1 つで、宣言した順序でプラグインをロードし、現在のプラグインがロードされた後にのみ次のプラグインをロードします。
-
このようにして、最初のプラグインにデータベース コネクタを登録し、それを 2 番目のプラグインで使用できます。
-
プラグインのスコープを処理する方法については、ここをお読みください: https://www.fastify.cn/docs/latest/Reference/Plugins/#handle-the-scope
-
fastify.listen() 、 fastify.inject() 、または fastify を呼び出すと、プラグインの読み込みが開始されます。
-
postgres プラグインは、デコレータ API を使用してカスタム オブジェクトを fasttify インスタンスに追加します。公式ドキュメントでは、コードの再利用を簡素化し、コードやロジックの重複を減らすために、このような API の使用を推奨しています。
-
fasttify プラグインの仕組み、新しいプラグインの開発方法、アプリケーションの非同期起動の複雑さを処理するために fasttify API 全体を使用する方法の詳細については、プラグイン ガイドをお読みください。
-
今日はここに書きます〜
-
友達、( ̄ω ̄( ̄ω ̄〃 ( ̄ω ̄〃)ゝ また明日~~
-
みんなも毎日幸せになろうね
記事の修正が必要な箇所はどなたでもご指摘ください~
学習には終わりがなく、協力は双方に利益をもたらします