Redis の WebAPI (Express)


こちらで定めた仕様を満たすサーバーサイドのプログラムです。
Redis の WebAPI を作成

フォルダー構成

$ tree
.
├── app.js
└── routes
    └── index.js
app.js
//-------------------------------------------------------------------------
//  app.js
//
//                  Jan/21/2020
//-------------------------------------------------------------------------
var express = require('express')
var routes = require('./routes')
var bodyParser = require("body-parser")
var cfenv = require('cfenv')

var app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

app.use(express.static(__dirname + '/public'))

var appEnv = cfenv.getAppEnv()

app.post('/read',routes.read)
app.post('/list',routes.list)
app.post('/insert',routes.insert)

app.listen(appEnv.port, '0.0.0.0', function() {
  console.log("server starting on " + appEnv.url)
})

//-------------------------------------------------------------------------
routes/index.js
// -----------------------------------------------------------------------
/*
    routes/index.js

                        Jan/21/2020
*/
// -----------------------------------------------------------------------
const redis = require("redis")
const client = redis.createClient(6379,'localhost')

exports.read = function(req,res)
{
    console.error ("*** read *** start ***")

    if (req.body.key) {
        key = req.body.key
        }

    var dict_aa = {}

    client.get (key, function (err, reply)
    {
        dict_aa["key"] = reply

        var str_out = JSON.stringify(dict_aa)

        res.send(str_out)

        console.error ("*** read *** end ***")
    })
}

// -----------------------------------------------------------------------
exports.list = function(req,res)
{
    console.error ("*** list *** start ***")

    client.keys ('*',function (err, reply)
        {
        const keys = reply

        var str_out = JSON.stringify(keys)

        res.send(str_out)

        console.error ("*** list *** end ***")
        })
}

// -----------------------------------------------------------------------
exports.insert = function(req,res)
{
    console.error ("*** 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)

    res.send(value)

    console.error ("*** insert *** end ***")
}

// -----------------------------------------------------------------------

サーバーの起動

$ export NODE_PATH=/usr/lib/node_modules
$ node app.js 
server starting on http://localhost:3000

読み出し

curl -X POST -d key="t1855" http://localhost:3000/read

書き込み

curl -X POST -d key="t1855" \
  -d value="{"name": "宇都宮", "population": 41295, "date_mod": "2003-8-12"}" \
http://localhost:3000/insert

key の一覧

curl -X POST http://localhost:3000/list

次のバージョンで確認しました。

$ node --version
v14.14.0