こちらで定めた仕様を満たすサーバーサイドのプログラムです。
Redis の WebAPI を作成
こちらのプログラムを改造しました。
Nuxt.js で簡単な WebAPI を作成
api/index.js
// ---------------------------------------------------------------
// api/index.js
//
// Dec/26/2020
// ---------------------------------------------------------------
const express = require("express")
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const redis = require("redis")
const client = redis.createClient(6379,'localhost')
// ---------------------------------------------------------------
app.get("/", function(req, res) {
const json_str = '{"en": "Hello World","ja": "こんにちは","fr": "Bonjour"}'
res.send(json_str)
})
// ---------------------------------------------------------------
app.post('/read', function(req, res) {
const key = req.body.key
client.get (key, async function (err, reply)
{
console.log ("*** read *** start ***")
var dict_aa = {}
dict_aa[key] = reply
const str_out = JSON.stringify(dict_aa)
await res.send(str_out)
console.log ("*** read *** end ***")
})
})
// ---------------------------------------------------------------
app.post('/list', function(req, res) {
client.keys ('*', async function (err, reply)
{
console.log ("*** list *** start ***")
const keys = reply
const str_out = JSON.stringify(keys)
await res.send(str_out)
console.log ("*** list *** end ***")
})
})
// ---------------------------------------------------------------
app.post('/insert', function(req, res) {
client.keys ('*', async function (err, reply)
{
console.log ("*** insert *** start ***")
var key = ""
var value = ""
if (req.body.key) {
key = req.body.key
}
if (req.body.value) {
value = req.body.value
}
client.set(key, value, redis.print)
await res.send(value)
console.log ("*** insert *** end ***")
})
})
// ---------------------------------------------------------------
module.exports = {
path: "/api/",
handler: app
}
// ---------------------------------------------------------------
サーバーの実行
yarn dev
curl によるテストスクリプト
go_read.sh
#
curl -X POST http://localhost:3000/api/read -d key="t1851"
echo
#
curl -X POST http://localhost:3000/api/read -d key="t1852"
echo
#
curl -X POST http://localhost:3000/api/read -d key="t1853"
echo
#
curl -X POST http://localhost:3000/api/read -d key="t1854"
echo
#
go_list.sh
curl -X POST http://localhost:3000/api/list
echo
#
go_insert.sh
curl -X POST http://localhost:3000/api/insert \
-d key="t1851" \
-d value="{"name": "宇都宮", "population": 49236, "date_mod": "2003-5-22"}"
echo
#