NestJSの特徴
- サーバーサイトアプリケーションフレームワーク
- TypeScriptを使っている
- OOP(オブジェクト指向プログラミング)可能
- FP(関数型プログラミング)可能
- FRP(関数型反応性プログラミング)可能
- 内部でExpressを利用している
- 様々なライブラリとの互換性を提供(Fastifyなど)
NestJSの目標
- 高度なテストが可能
- スケーラブル
- 疎結合
- 保守の用意性
- 簡単に作成できる
NestJS
公式: https://nestjs.com/
ドキュメント: https://docs.nestjs.com/
Introduction - アプリケーションの作成
$ npm i -g @nestjs/cli
$ nest new test-nestjs
# 色々質問されるがすべて「Enter」でスキップ
? description: description
? version: 0.0.0
? author:
スタート
$ cd test-nestjs
> npm run start master untracked
> test-nestjs@0.0.0 start /Users/k4zzk/Desktop/test-nestjs
> ts-node -r tsconfig-paths/register src/main.ts
[Nest] 7083 - 2019-2-16 23:39:36 [NestFactory] Starting Nest application...
[Nest] 7083 - 2019-2-16 23:39:36 [InstanceLoader] AppModule dependencies initialized +22ms
[Nest] 7083 - 2019-2-16 23:39:36 [RoutesResolver] AppController {/}: +71ms
[Nest] 7083 - 2019-2-16 23:39:36 [RouterExplorer] Mapped {/, GET} route +4ms
[Nest] 7083 - 2019-2-16 23:39:36 [NestApplication] Nest application successfully started +3ms
「http://localhost:3000」でアクセスが可能
リポジトリを登録する。.gitignoreが無いので、作成する処理を入れる。
$ git init
$ curl https://raw.githubusercontent.com/github/gitignore/master/Node.gitignore > .gitignore
$ git add -A
$ git commit -m "first commit"
$ git remote add origin git@github.com:rorono/test-nestjs.git
$ git push -u origin master
First steps - 各ファイルの役目
ここでの説明は基礎中の基礎。一番カンタンなCRUDアプリケーションを構築する。
Nestは最新の言語機能を利用しているため、TypeScriptを使用している。
ただ、後から通常のJavaScript構文に書き換えることもできる。
必要環境
- Node.js(> = 8.9.0)
「src/」について
src/には、コアとなるプログラムが含まれている。
$ tree src/
src
├── app.controller.spec.ts
├── app.controller.ts
├── app.module.ts
├── app.service.ts
└── main.ts
0 directories, 5 files
main.ts
アプリケーションのエントリファイル。 NestFactoryを使用してNestアプリケーションインスタンスを作成する
import { NestFactory } from '@nestjs/core'; // <= NestFactory
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();