次のページを参考にしました。
How to Build a REST API with KoaJS
ライブラリーをグローバルにインストールしたこと、データの題材を日本の文学作品にしたことが異なります。
ライブラリーのインストール
sudo npm install -g koa
sudo npm install -g koa-body
sudo npm install -g koa-router
フォルダー構造
$ tree
.
├── books.js
└── ex03.js
ex03.js
// ---------------------------------------------------------------
// ex03.js
//
// Dec/27/2020
// ---------------------------------------------------------------
const Koa = require('koa')
const koaBody = require('koa-body')
const app = new Koa()
console.error ("*** ex03 *** start ***")
// middleware functions
app.use(koaBody())
// Require the Router we defined in books.js
let books = require('./books.js')
// Use the Router on the sub route /books
app.use(books.routes())
// Bootstrap the server
app.listen(3000)
// ---------------------------------------------------------------
books.js
// ---------------------------------------------------------------
// books.js
//
// Dec/27/2020
// ---------------------------------------------------------------
const Router = require('koa-router')
// Prefix all routes with /books
const router = new Router({
prefix: '/books'
})
let books = [
{ id: 101, name: '草枕', author: '夏目漱石' },
{ id: 102, name: '走れメロス', author: '太宰治' },
{ id: 103, name: '千曲川のスケッチ', author: '島崎藤村' },
{ id: 104, name: '高瀬舟', author: '森鴎外' }
]
// Routes will go here
router.get('/', (ctx, next) => {
ctx.body = {
status: 'success',
message: books
}
next()
})
router.get('/:id', (ctx, next) => {
let getCurrentBook = books.filter(function(book) {
if (book.id == ctx.params.id) {
return true
}
})
if (getCurrentBook.length) {
ctx.body = getCurrentBook[0]
} else {
ctx.response.status = 404
ctx.body = {
status: 'error!',
message: 'Book Not Found with that id!'
}
}
next()
})
router.post('/new', (ctx, next) => {
// Check if any of the data field not empty
if (
!ctx.request.body.id ||
!ctx.request.body.name ||
!ctx.request.body.author
) {
ctx.response.status = 400
ctx.body = {
status: 'error',
message: 'Please enter the data'
}
} else {
let newBook = books.push({
id: ctx.request.body.id,
name: ctx.request.body.name,
author: ctx.request.body.author
})
ctx.response.status = 201
ctx.body = {
status: 'success',
message: `New book added with id: ${ctx.request.body.id} & name: ${
ctx.request.body.name
}`
}
}
next()
})
module.exports = router
// ---------------------------------------------------------------
サーバーの実行
export NODE_PATH=/usr/lib/node_modules
node ex03.js
クライアントでアクセス
総てのデータの取得
curl http://localhost:3000/books | jq .
id を指定してのデータの取得
curl http://localhost:3000/books/101 | jq .
データの挿入
curl -X POST --data "id=105&name=トロッコ&author=芥川龍之介" http://localhost:3000/books/new
挿入されたことを確認
$ curl http://localhost:3000/books/105 | jq .
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 61 100 61 0 0 30500 0 --:--:-- --:--:-- --:--:-- 30500
{
"id": "105",
"name": "トロッコ",
"author": "芥川龍之介"
}