3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nest.js の使い方

Last updated at Posted at 2021-02-09

次のページを参考にしました。
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
3
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?