-
Notifications
You must be signed in to change notification settings - Fork 3
/
db.js
40 lines (30 loc) · 854 Bytes
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const Redis = require('ioredis')
const env = require('./env')
let redis
function initDB() {
if (!redis)
redis = new Redis({
port: env.REDIS_PORT,
host: env.REDIS_HOST,
password: env.REDIS_PASSWORD
})
}
async function getKeys(keys) {
const res = await redis.mget(keys.map(sanitizedKey))
return Object.fromEntries(res.map((value, i) => [keys[i], JSON.parse(value)]))
}
async function setKey(address, key, value) {
if (isNaN(+value)) {
console.info('Invalid value for key', address, key, value)
return;
}
address = sanitizedKey(address)
// get the current data
let data = JSON.parse(await redis.get(address)) ?? {}
data[key] = value
return redis.set(address, JSON.stringify(data))
}
function sanitizedKey(key) {
return key.toLowerCase().trim()
}
module.exports = { initDB, getKeys, setKey, }