解説はこちら
How to configure NestJS TypeORM Integration with MySQL?
ここに示されているコードを実行してみます。
コードの取得
git clone https://github.com/dashsaurabh/nestjs-typeorm-mysql-sample
ライブラリーのインストール
cd nestjs-typeorm-mysql-sample
npm install
MariaDB で ユーザー、データベースを用意
user: scott
password: tiger123
database: library
コードの修正
src/app.module.ts
(省略)
username: 'scott',
password: 'tiger123',
(省略)
サーバーの起動
npm run start:dev
library.book というテーブルが作成されます。
データの取得
$ http http://localhost:3000/books
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 12
Content-Type: application/json; charset=utf-8
Date: Wed, 12 Jan 2022 05:50:19 GMT
ETag: W/"c-1Dc+a0VevR0VqaVW3eOP9bDxCm8"
Keep-Alive: timeout=5
X-Powered-By: Express
{
"books": []
}
MariaDB にデータを挿入#
insert.sql
insert into book set id=101, bookName='草枕', authorName='夏目漱石', publishYear=1906;
insert into book set id=102, bookName='走れメロス', authorName='太宰治', publishYear=1940;
insert into book set id=103, bookName='千曲川のスケッチ', authorName='島崎藤村', publishYear=1911;
insert into book set id=104, bookName='高瀬舟', authorName='森鴎外', publishYear=1916;
go_insert.sh
mysql -uscott -ptiger123 library < insert.sql
データの取得
全件の取得
$ http http://localhost:3000/books
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 423
Content-Type: application/json; charset=utf-8
Date: Wed, 12 Jan 2022 05:52:11 GMT
ETag: W/"1a7-kynuTWrG1D0v8DOJukDYwZQqSNc"
Keep-Alive: timeout=5
X-Powered-By: Express
{
"books": [
{
"authorName": "夏目漱石",
"bookName": "草枕",
"id": 101,
"isAvailable": true,
"publishYear": 1906
},
{
"authorName": "太宰治",
"bookName": "走れメロス",
"id": 102,
"isAvailable": true,
"publishYear": 1940
},
{
"authorName": "島崎藤村",
"bookName": "千曲川のスケッチ",
"id": 103,
"isAvailable": true,
"publishYear": 1911
},
{
"authorName": "森鴎外",
"bookName": "高瀬舟",
"id": 104,
"isAvailable": true,
"publishYear": 1916
}
]
}
ID を指定して取得
$ http http://localhost:3000/books/104
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 105
Content-Type: application/json; charset=utf-8
Date: Wed, 12 Jan 2022 05:52:51 GMT
ETag: W/"69-mZZT1OIqB1kh8vJ3CS4cNKclNbY"
Keep-Alive: timeout=5
X-Powered-By: Express
{
"book": {
"authorName": "森鴎外",
"bookName": "高瀬舟",
"id": 104,
"isAvailable": true,
"publishYear": 1916
}
}