LoginSignup
2
0

More than 1 year has passed since last update.

Fastify(Node.jsフレームワーク)[入門編]

Posted at

🐼はじめに

Node.jsを用いてWEBサーバを構築しようとした場合、Expressなどが候補に上がると思います。
今回紹介するFastifyは、非常に高速なフレームワークです。
今回はJSONを返すAPIサーバを構築します。

ベンチマーク(一部抜粋)

Framework Version Router Requests/s Latency Throughput/Mb
koa 2.13.4 22126.0 44.71 3.95
hapi 20.2.2 18740.3 52.84 3.34
express 4.18.1 7580.1 131.26 1.35
fastify 4.6.0 29717.6 33.17 5.33

目次

  • Nodejsの初期化を行う
    • yarn
    • 初期化
    • fastify
  • コーディング
    • インポート/リッスン
    • ルーター
    • レスポンスタイプの設定(オプション)
  • まとめコード

Nodejsの初期化を行う

yarn

パッケージ管理をnpmではなくyarnで行います

$ npm install -g yarn

初期化

$ yarn init

ここで、entry point (index.js):という質問がされるので

entry point (index.js):index.mjs

と入力します
実行するためのファイルはindex.jsではなくindex.mjsとなります。

fastify

パッケージをインストールします

$ yarn add fastify

コーディング

インポート/リッスン

import Fastify from 'fastify';
const fastify = Fastify({
    // loggerをtrueにするとログが出力される
    logger: false
})

fastify.listen({ port: 3000 }, (err, address) => {
    if (err) {
        throw err
    }
})

ルーター

待ち受けの書き方

// GETの時
fastify.get("パス", function名)
// POSTの時
fastify.post("パス", function名)

パスの書き方

パスを固定で指定する時

// GET `http://localhost:3000/` の場合
fastify.get("/", index)
function index(req, res) {
    res.code(200);
    return { "mes": "This is index" }
}
// POST `http://localhost:3000/` の場合
// ヘッダーに Content-Type:application/json をセットしてクエリを投げる
fastify.post("/", indexPost)
function indexPost(req, res) {
    res.code(200);
    const body = req.body // リクエストのJSON
    console.log(body)
    return { "mes": "This is POST index" }
}
// GET `http://localhost:3000/hello` の場合
fastify.get("/hello", hello)
function hello(req, res) {
    res.code(200);
    return { "mes": "This is hello" }
}

パスを変数にする時(taroを変数として取得する)

// GET `http://localhost:3000/taro` などの場合 `/:name`
fastify.get("/:name", name)
function name(req, res) {
    res.code(200);
    const name = req.params.name;
    return { "mes": `Hello ${name}` }
}
// GET `http://localhost:3000/ohayou/taro` の場合 `/ohayou/:name`
fastify.get("/ohayou/:name", ohayou)
function ohayou(req, res) {
    res.code(200);
    const name = req.params.name;
    return { "mes": `ohayou ${name}` }
}

レスポンスタイプの設定(オプション)

    res.code(200);

の部分は省略可能だが

    // text/html で返す場合 
    res.type("text/html").code(200);

のような記述も可能

まとめコード

import Fastify from 'fastify';
const fastify = Fastify({
    logger: false
})

fastify.listen({ port: 3000 }, (err, address) => {
    if (err) {
        throw err
    }
})

fastify.get("/", index)
function index(req, res) {
    res.code(200);
    return { "mes": "This is index" }
}
fastify.post("/", indexPost)
function indexPost(req, res) {
    res.code(200);
    const body = req.body
    console.log(body.aaa)
    return { "mes": "This is POST index" }
}
fastify.get("/hello", hello)
function hello(req, res) {
    res.code(200);
    return { "mes": "This is hello" }
}

fastify.get("/:name", name)
function name(req, res) {
    res.code(200);
    const name = req.params.name;
    return { "mes": `Hello ${name}` }
}
fastify.get("/ohayou/:name", ohayou)
function ohayou(req, res) {
    res.code(200);
    const name = req.params.name;
    return { "mes": `ohayou ${name}` }
}

🐼最後に

Nodejsでも速さを活かしたい場面というのはあるでしょう。
そういう時に使うと良いと思います。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0