コンテンツにスキップ

00. インストール

Fastify は Web フレームワークである。

始める

1
2
3
4
5
6
$ mkdir fastify-example
$ cd fastify-example/
$ npm init -y
$ npm i -D tsx typescript @types/node
$ npx tsc --init
$ npm i fastify @fastify/cors

以下をマージし、Top-level await を使えるようにする。

package.json
1
2
3
4
5
6
7
{
  "scripts": {
    "dev": "tsx watch src/app.ts",
    "start": "tsx src/app.ts"
  },
  "type": "module"
}
tsconfig.json
1
2
3
4
5
6
{
  "compilerOptions": {
    "target": "ES2023",
    "module": "Node16"
  }
}
src/app.ts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import cors from "@fastify/cors";
import Fastify from "fastify";

const fastify = Fastify();
await fastify.register(cors);

fastify.get("/", (request, reply) => {
  reply.send({ message: "Hello" });
});

fastify.post("/", (request, reply) => {
  reply.code(201).send({ message: "Created" });
});

fastify.delete("/", (request, reply) => {
  reply.code(204).send();
});

await fastify.listen({ port: 3000, host: "0.0.0.0" });
console.log("listening");

バリデーション

Validation-and-Serialization | Fastify

package.json から version を取得する

TypeScript の環境構築を参照すること。