1
/
5

NestJSでREST(その1)

はじめに

当社では、クラウドネイティブなSaaSの開発をしており、いつもはWebAPIの実装ならサーバーレスで。となるのですが、今回は、サーバーレスでないWebAPIの実現方法として、NestJSを動かしてみましたという内容です。

やりたいこと

こんな感じのよくありそうなデータベースのテーブルを


こんな感じのRESTリソースとして公開したい。とします。


やったこと

NestJSの導入

$ node --version
v16.19.1
$ npm --version
8.19.2
$ npm i -g @nestjs/cli
$ nest --version
9.3.0
$ nest new nestjs-sample
? Which package manager would you ❤️ to use? npm
🚀 Successfully created project nestjs-sample
$ node --version
v16.19.1
$ npm --version
8.19.2
$ npm i -g @nestjs/cli
$ nest --version
9.3.0
$ nest new nestjs-sample
? Which package manager would you ❤️ to use? npm
🚀 Successfully created project nestjs-sample

別件で使用中の環境ですが、なんの問題もありませんでした。

確認

$ npm run start

で起動して、別のターミナルから

$ curl http://localhost:3000/
Hello World!

おお、何もしてないけど動く。素敵です。

CRUD generator

どんな感じで構成するのが良いのかしらと本家のサイトを見ているとありました。


Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Re
https://docs.nestjs.com/recipes/crud-generator


やってみます。

$ nest g resource customers
? What transport layer do you use? REST API
? Would you like to generate CRUD entry points? Yes
✔ Packages installed successfully.

確認

こんな感じで customers 以下にファイルが生成されて、app.module に追加されました。

$ tree src
src
├── app.controller.spec.ts
├── app.controller.ts
├── app.module.ts
├── app.service.ts
├── customers
│ ├── customers.controller.spec.ts
│ ├── customers.controller.ts
│ ├── customers.module.ts
│ ├── customers.service.spec.ts
│ ├── customers.service.ts
│ ├── dto
│ │ ├── create-customer.dto.ts
│ │ └── update-customer.dto.ts
│ └── entities
│ └── customer.entity.ts
└── main.ts
$ npm run start

で起動して、また、別のターミナルから

$ curl http://localhost:3000/customers
This action returns all customers

まだ、なにもしていないけど、ちゃんとルーティングされている。👏

次回は

データベースを作って繋ぎます。

株式会社ROBONでは一緒に働く仲間を募集しています
同じタグの記事
今週のランキング
株式会社ROBONからお誘い
この話題に共感したら、メンバーと話してみませんか?