Redis 的 WebAPI(Express,TypeScript)

这是一个符合我们在这里规定的规格的服务器端程序。
我们创建了一个 Redis WebAPI。
将以下程序更改为 TypeScript。
Redis WebAPI(Express)

服务器程序

文件夹结构

$ tree
.
├── app.ts
└── routes
    └── index.ts
//-------------------------------------------------------------------------
//	app.ts
//
//					May/30/2021
//-------------------------------------------------------------------------
var express = require('express')
var routes = require('./routes')
var cfenv = require('cfenv')

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

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

const 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.ts

						May/30/2023
*/
// -----------------------------------------------------------------------
const redis = require("redis")
const client = redis.createClient()

exports.read = async function(req: any,res: any)
{
	console.error ("*** read *** start ***")
	await client.connect()

	var key:string = "" 

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

	var dict_aa: {[key: string]: any} = {}

	const value = await client.get(key)
	dict_aa["key"] = value

	const str_out = JSON.stringify(dict_aa)

	res.send(str_out)

	await client.disconnect()
	console.error ("*** read *** end ***")
}

// -----------------------------------------------------------------------
exports.list = async function(req:any ,res:any)
{
	console.error ("*** list *** start ***")
	await client.connect()

	const keys = await client.keys('*')

	const str_out = JSON.stringify(keys)
	res.send(str_out)
	await client.disconnect()
	console.error ("*** list *** end ***")
}

// -----------------------------------------------------------------------
exports.insert = async function(req:any ,res:any)
{
	console.error ("*** insert *** start ***")
	await client.connect()

	var key:string = ""
	var value:string = ""

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

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

	await client.set(key, value, redis.print)

	res.send(value)

	await client.disconnect()
	console.error ("*** insert *** end ***")
}

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

服务器的启动

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

确认的版本

$ node -v
v20.2.0

$ tsc -v
Version 4.8.4