次のページを参考にしました。
Overview
Nestjsをローカルで動かしてみる
インストール
sudo npm install -g @nestjs/cli
プロジェクトの作成と起動
nest new -p npm my-nest-project
cd my-nest-project
npm run start:dev
クライアントでアクセス
$ curl http://localhost:3000
Hello World!
ソースを改造
src/app.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
var str_out = 'こんにちは'
return str_out
// return 'Hello World!';
}
}
クライアントでアクセス
$ curl http://localhost:3000
こんにちは
GET の API を作成
src/app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@Get('ping')
myCustomAPI(): {message: string} {
return {
message: 'Hello Everybody!'
}
}
}
クライアントでアクセス
$ curl http://localhost:3000/ping
{"message":"Hello Everybody!"}
もう少し複雑な値を返してみます。
src/app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@Get('ping')
myCustomAPI(): {message: string} {
return {
message: 'Hello Everybody!'
}
}
@Get('books')
get_books_proc(): {id: string; name: string; author: string;}[] {
const books = [
{id: 't101', name: '草枕', author: '夏目漱石' },
{id: 't102', name: '走れメロス', author: '太宰治' },
{id: 't103', name: '千曲川のスケッチ', author: '島崎藤村' },
{id: 't104', name: '高瀬舟', author: '森鴎外' }
]
return books
}
}
クライアントでアクセス
$ curl http://localhost:3000/books | jq .
[
{
"id": "t101",
"name": "草枕",
"author": "夏目漱石"
},
{
"id": "t102",
"name": "走れメロス",
"author": "太宰治"
},
{
"id": "t103",
"name": "千曲川のスケッチ",
"author": "島崎藤村"
},
{
"id": "t104",
"name": "高瀬舟",
"author": "森鴎外"
}
]
次のバージョンで確認しました。
$ node --version
v17.3.0
$ nest --version
7.5.4