Fastify コマンドをインストールします。
npm install fastify-cli --global
fastify コマンドをinstallして雛形作成
astapi-2% fastify generate fastify-ts-example
generated app.js
generated .gitignore
generated routes/README.md
generated test/helper.js
generated plugins/README.md
generated routes/root.js
generated plugins/support.js
generated routes/example/index.js
generated test/plugins/support.test.js
generated test/routes/root.test.js
generated test/routes/example.test.js
--> reading package.json in fastify-ts-example
edited package.json, saving
saved package.json
--> project fastify-ts-example generated successfully
run 'npm install' to install the dependencies
run 'npm start' to start the application
run 'npm run dev' to start the application with pino-colada pretty logging (not suitable for production)
run 'npm test' to execute the unit tests
typescript を入れる
astapi-2% cd fastify-ts-example
astapi-2% yarn add --dev typescript @types/node
typescript 初期化
astapi-2% npx typescript --init
tsconfig.json を下記で上書き
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
"allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
"noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": ".", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
"paths": {
"@/*": [
"./src/*"
]
},
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
各種コードを src ディレクトリ配下に移動
astapi-2% mkdir src
astapi-2% mv test src
astapi-2% mv routes src
astapi-2% mv plugins src
src内に index.ts を作成
import fastify, { FastifyInstance } from 'fastify';
import { Server, IncomingMessage, ServerResponse } from 'http';
import fastifyCors from 'fastify-cors';
// import fastifyGracefulShutdown from 'fastify-graceful-shutdown';
const server: FastifyInstance<
Server,
IncomingMessage,
ServerResponse
> = fastify();
// plugins
server.register(fastifyCors, {
origin: [/localhost/, /.*.ngrok.io/]
})
// By default the fastify close hook is called when SIGINT or SIGTERM was triggered.
// server.register(fastifyGracefulShutdown).after((err) => {
// server.log.error(err)
// // Register custom clean up handler
// server.gracefulShutdown((code, cb) => {
// console.log('\nGracefully shutting down...\n');
// cb();
// })
// })
// Rooting
fastify.get('/ping', async (request, reply) => {
return 'pong\n'
})
const PORT = process.env.PORT || 3030;
// Listen
server.listen(PORT, '0.0.0.0', (err, address) => {
if(err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening at ${address}`)
})
fastify-cors を使うので install
astapi-2% yarn add fastify-cors
package.jsonのscriptsを以下のように記述します
"scripts": {
"test": "ENV=test tap --no-ts --node-arg=--require=tsconfig-paths/register --node-arg=--require=ts-node/register --reporter=spec src/test/**/**/*.test.ts",
"start": "node ./dist/main.js",
"dev": "webpack --watch & nodemon dist/main.js",
"build": "webpack",
"check": "tsc --noEmit"
},
buildのためのwebpackの設定を作っていきます
webpack.config.js をルートディレクトリに作成します
const webpack = require('webpack');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const nodeExternals = require('webpack-node-externals')
module.exports = {
// モード値を production に設定すると最適化された状態で、
// development に設定するとソースマップ有効でJSファイルが出力される
mode: 'development',
target: 'node',
devtool: 'inline-source-map',
// メインとなるJavaScriptファイル(エントリーポイント)
entry: [
'./src/index.ts',
],
output: {
path: `${__dirname}/dist`,
filename: '[name].js',
},
module: {
rules: [
{
test: /\.ts$/,
use: {
loader: "ts-loader",
options: {
transpileOnly: true,
},
},
exclude: /node_modules/
},
],
},
resolve: {
// 拡張子を配列で指定
extensions: [
'.ts', '.js', '.json', '.js'
],
plugins: [
new TsconfigPathsPlugin({ configFile: "./tsconfig.json" }) // `@/` を解決するために ts-loader に tsconfig を読み込ませる
],
},
externals: [nodeExternals()]
};
tsファイルをjsに変換するだけなら tsc コマンドで充分なのですが、tsconfig.jsonのpathsを書いていると開発時は '@/src/~~' でbuildは通りますが、tscでjsに変換した場合に、'@/src/~~' は解決されずにそのまま出力されるため実行時にファイルを見つけることができません。
( tsc で解決してくれればいいのにと思うのですが、tscはそういうツールじゃないのでやらない。とイシューにあります。確かにそれはそうだなって感じですね)
なのでwebpackを使用します。
やっていることはシンプルでsrc/index.tsを起点にts,jsファイルを変換してまとめていってる感じですね。
その過程でtsconfig-paths-webpack-pluginでパスを解決しています。
webpack 周りのライブラリをインストールします
astapi-2% yarn add --dev webpack webpack-cli webpack-node-externals ts-loader tsconfig-paths-webpack-plugin
build してみます
astapi-2% yarn build
yarn run v1.17.3
$ webpack
asset main.js 12.5 KiB [emitted] (name: main)
runtime modules 931 bytes 4 modules
built modules 3.1 KiB [built]
./src/index.ts 3.02 KiB [built] [code generated]
external "fastify" 42 bytes [built] [code generated]
external "fastify-cors" 42 bytes [built] [code generated]
webpack 5.11.0 compiled successfully in 430 ms
✨ Done in 0.90s.
dist/main.js が出力されました
実行してみます
astapi-2% yarn start
yarn run v1.17.3
$ node ./dist/main.js
Server listening at http://0.0.0.0:3030
http://0.0.0.0:3030/ping にアクセスすると pong を表示されると思います。
現状だと index.ts しか使っていないのでルーティング(ping)のあたりを別ファイルにわけたりしていきます。
srcディレクトリにapp.tsを作成します。
import { FastifyInstance, FastifyPluginOptions } from 'fastify';
import example from '@/routes/example/index'
require('dotenv').config()
export default function (fastify: FastifyInstance, opts: FastifyPluginOptions, next: any) {
fastify.get('/ping', async (request, reply) => {
return 'pong\n'
})
fastify.get('/', async (request, reply) => {
reply.code(404).send('NotFound.')
return;
})
fastify.register(example, { ...opts, prefix: '/example' });
next();
}
fastify を js で構築した場合はルーティングをディレクトリ指定で再帰的にautoloadする機構が使えますが、ts の場合それを使うことができません。
仕方ないので自分でpath構造を定義しつつルーティングを設定していきます。
app.ts では plugin として機能する関数を返します。
この関数で受け取ったfastifyインスタンスでルーティングを設定します。
index.ts に書いていた /ping をこちらに移植。ついでに / も追加。
routesディレクトリに定義したルーティングを/exampleとして追加
index.tsでは /ping の設定の変わりに app.tsの読み込みを書きます
import fastify, { FastifyInstance } from 'fastify';
import { Server, IncomingMessage, ServerResponse } from 'http';
import fastifyCors from 'fastify-cors';
import App from '@/app';
const server: FastifyInstance<
Server,
IncomingMessage,
ServerResponse
> = fastify();
// plugins
server.register(fastifyCors, {
origin: [/localhost/, /.*.ngrok.io/]
})
// Rooting
server.register(App)
const PORT = process.env.PORT || 3030;
// Listen
server.listen(PORT, '0.0.0.0', (err, address) => {
if(err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening at ${address}`)
})
example/index.js example/index.tsにリネームし以下のように修正します。
import { FastifyInstance, FastifyPluginOptions } from 'fastify';
export default function (fastify: FastifyInstance, opts: FastifyPluginOptions, next: any) {
fastify.get('/', async function (request, reply) {
return 'this is an example'
})
next()
}
再度buildして実行してみます
yarn build
yarn start
http://0.0.0.0:3030/example のルーティングも設定されていることが確認できます。
ルートディレクトリにあるapp.jsは不要なので消しましょう。
routes/root.jsも不要なので消しましょう。
現時点でほぼ ts 化できていますが修正のたびにyarn build, yarn start はつらいです。
そこですでに記述されていますが、yarn devを使います。
yarn dev はこう書かれてます
webpack --watch & nodemon dist/main.js
webpack --watch でファイルの変更を監視して、変更されたら即時にbuildします。
nodemonコマンドは実行ファイル(dist/main.js)に変更があるとコマンドを実行し直してくれます。
nodemonをいれてやってみましょう。
yarn add --dev nodemon
yarn dev
exmaple/index.ts の戻り値をかえてみます
return 'this is an example.'
webpackが実行されてnodemonでサーバーがリスタートされたことがわかると思います。
これで開発に関してはかなり便利になりました。
次に test コードを書いていきます。
test/routes/example.test.js example.test.tsにリネームして以下のように変えます
import { test } from 'tap';
import { build } from '@/test/helper';
test('default root route', async (t) => {
const app = build(t)
const response = await app.inject({
url: '/'
})
t.equal(response.statusCode, 404)
t.equal(response.body, "NotFound.")
})
tap を install します。
astapi-2% yarn add --dev tap @types/tap
ts-node を使用して、test.tsファイルをコンパイルしながら実行しますのでinstallします。
astapi-2% yarn add --dev ts-node
test を実行します。
yarn test
test が実行できたと思います。
おまけ
あとはもうルーティング追加して好きなAPIを実装すればいいのですが、自分の場合はfirebaseを使用する必要があったのでその設定を書いておく
app.ts をこうする
import { FastifyInstance, FastifyPluginOptions } from 'fastify';
import example from '@/routes/example/index'
import admin from 'firebase-admin'
require('dotenv').config()
export default function (fastify: FastifyInstance, opts: FastifyPluginOptions, next: any) {
if (!admin.apps.length) {
admin.initializeApp();
}
fastify.get('/ping', async (request, reply) => {
return 'pong\n'
})
fastify.get('/', async (request, reply) => {
reply.code(404).send('NotFound.')
return;
})
fastify.register(example, { ...opts, prefix: '/example' });
next();
}
admin.initializeApp()は、GOOGLEAPPLICATIONCREDENTIALSにjsonのパスを書いておくと読み込んでくれます。
実は最初からdontenvが読み込まれていました。
yarn add dotenv
.env ファイルを作成します。
GOOGLE_APPLICATION_CREDENTIALS=/path/to/credintials.json
これでfirebase側の設定さえできていればfastify内で使用することができるようになりました。
おまけその2
firebaseはGCPのサービスのインスタンス上で実行すると便利なのでCloug RunでこのAPIサーバーを実行したいと思います。
CloudRunはDockerコンテナを実行するのでそれも用意します。
CloudRunで実行した際にconsole.log等でログを吐き出すとCloudLoggingに保存されます。
その場合に便利になるロガーも作ります
ロガー
src/utils ディレクトリを作成して、src/utils/logger.ts を作成します。
import { IncomingHttpHeaders } from "http";
const projectId = 'xxxxx';
const globalLogFields: any = {};
export class Logger {
private static instance: Logger;
private traceId: string|undefined;
private constructor(traceId?: string) {
if (traceId) this.traceId = traceId;
}
static getInstance(headers?: IncomingHttpHeaders) {
if (!Logger.instance) {
if (headers) {
// clound run実行時にはrequestIdをヘッダーから取得する
const traceHeader = headers['x-cloud-trace-context'];
if (typeof traceHeader === 'string') {
const [trace] = traceHeader.split('/');
Logger.instance = new Logger(trace);
}
} else {
Logger.instance = new Logger();
}
}
return Logger.instance
}
public static log(text: string, option?: any): void {
Logger.getInstance().log(text, option);
}
log(text: string, option?: any): void {
globalLogFields['logging.googleapis.com/trace'] = `projects/${projectId}/traces/${this.traceId}`;
const entry = {
severity: 'INFO',
message: text,
data: option,
...globalLogFields
}
console.log(JSON.stringify(entry));
}
public static error(text: string, option?: any): void {
Logger.getInstance().error(text, option);
}
error(text: string, option?: any): void {
globalLogFields['logging.googleapis.com/trace'] = `projects/${projectId}/traces/${this.traceId}`;
const entry = {
severity: 'ERROR',
message: text,
data: option,
...globalLogFields
}
console.error(JSON.stringify(entry));
}
public static getTraceId(): string|undefined {
return Logger.getInstance().traceId;
}
}
cloud loggingはjsonを出力するといい感じに解析してくれます。
その際に、 logging.googleapis.com/trace
を設定すると1リクエスト中のログを紐付けることができます。
headers['x-cloud-trace-context']からtraceIdを入手して作ってます。
example/index.ts を修正します。
import { FastifyInstance, FastifyPluginOptions } from 'fastify';
import { Logger } from '@/utils/logger';
export default function (fastify: FastifyInstance, opts: FastifyPluginOptions, next: any) {
fastify.get('/', async function (request, reply) {
Logger.getInstance(request.headers)
Logger.log('this is an example log.');
return 'this is an example.'
})
next()
}
実行します。
こんな感じでログが吐き出されます。traceIdはCloudRunで実行した場合にしか入ってこないのでローカルではundefinedになっています。
{"severity":"INFO","message":"this is an example log.","logging.googleapis.com/trace":"projects/xxxxx/traces/undefined"}
Dockerコンテナ
.dockerignore
node_modules
Dockerfile
FROM node:12.19.0-alpine3.11
# RUN groupadd api-group
# RUN useradd -ms /bin/bash api-user
WORKDIR /app
# RUN chown -R api-user:api-group /app
# USER api-user
COPY package.json /app/
RUN yarn install
COPY . /app/
COPY src/ /app/
RUN yarn build
EXPOSE 3030
CMD yarn start
おまけその3
わりとちゃんとしたAPIの実装
routes/users/index.ts
import { FastifyInstance, FastifyPluginOptions } from 'fastify'
import { Logger } from '@/utils/logger';
interface UserCreateBody {
name: string;
email: string;
}
export default function (fastify: FastifyInstance, opts: FastifyPluginOptions, next: any) {
fastify.post<{ Body: UserCreateBody }>('/create', async function (request, reply) {
Logger.getInstance(request.headers)
const { name, email } = request.body;
// user を作るような処理
try {
const userId = create(name, email);
reply.code(200).type('application/json').send(userId);
} catch (e) {
Logger.error('予期せぬエラーが発生しました', { message: e.message });
// 予期していない例外
reply.code(500).send('Internal Server Error.');
}
});
}
const create = (name: string, email: string): String => {
return 'userId';
}
こんな感じで post の body の interface を書きつつやります。
いま気づいたけど nextがany w