fastify チュートリアル -node.js

fastify チュートリアル -node.js

チュートリアル

項目 バージョン
fastify 4.0.0
GitHub - fastify/fastify: Fast and low overhead web framework, for Node.js
Fast and low overhead web framework, for Node.js. Contribute to fastify/fastify development by creating an account on Gi...
$ mkdir fastify-test
$ cd fastify-test
$ npm init fastify -y

ひな形プロジェクトが作成されます。

fastify チュートリアル -node.js

package.jsonがあるので依存関係インストールします。

$ npm i

node_modulesが作成されます。

npm scripts

npm scriptsが以下のようになっています。

  "scripts": {
    "test": "tap \"test/**/*.test.js\"",
    "start": "fastify start -l info app.js",
    "dev": "fastify start -w -l info -P app.js"
  }

fastify-cliが依存関係にあるので、npm scriptsでfastifyコマンドが使用できます。npm scriptsではポート未指定ですがデフォルトポートは3000となります。

$ npm run dev // 開発モード

-wオプションでファイル変更監視してくれるのでnodemonが不要です。

GitHub - fastify/fastify-cli: Run a Fastify application with one command!
Run a Fastify application with one command! Contribute to fastify/fastify-cli development by creating an account on GitH...

routes/example/index.js

routes/example/index.jsを修正します。someSupport()を使用するように修正します。

'use strict'

module.exports = async function (fastify, opts) {
  fastify.get('/', async function (request, reply) {
    return fastify.someSupport() + 'this is an example'
  })
}

plugins/support.jsでアタッチされているメソッド(someSupport)です。’hugs’を返すメソッドです。

'use strict'

const fp = require('fastify-plugin')

module.exports = fp(async function (fastify, opts) {
  fastify.decorate('someSupport', function () {
    return 'hugs'
  })
})
Decorators
Fast and low overhead web framework, for Node.js

ブラウザからアクセス

npm run devでサーバ起動します。

起動後、ブラウザからルート(127.0.0.1:3000)へアクセスします。

fastify チュートリアル -node.js

ブラウザからexample(127.0.0.1:3000/example/)へアクセスします。

fastify チュートリアル -node.js

someSupport()の戻り値が返ってきていることがわかります。

Documentation
Fast and low overhead web framework, for Node.js

youtube

コメント

株式会社CONFRAGE ITソリューション事業部をもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む

タイトルとURLをコピーしました