From 84b0a5a912a9f2ab809158968da339c29ae32cd2 Mon Sep 17 00:00:00 2001 From: Jannis R Date: Wed, 7 Mar 2018 16:53:33 +0100 Subject: [PATCH] storage interface --- .gitignore | 2 ++ lib/storage.js | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 2 ++ 3 files changed, 66 insertions(+) create mode 100644 lib/storage.js diff --git a/.gitignore b/.gitignore index 808662f..45d061e 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ pnpm-debug.log package-lock.json shrinkwrap.yaml + +vbb-telegram.ldb diff --git a/lib/storage.js b/lib/storage.js new file mode 100644 index 0000000..89fc5a5 --- /dev/null +++ b/lib/storage.js @@ -0,0 +1,62 @@ +'use strict' + +const level = require('level') +const path = require('path') +const hifo = require('hifo') + +const last = '\xff' + +const db = level(path.join(__dirname, '..', 'vbb-telegram.ldb'), { + valueEncoding: 'json' +}) + +const getCommand = (user) => { + return db.get(user + ':cmd') + .catch((err) => { + if (err.notFound) return null + else throw err + }) +} + +const putCommand = (user, cmd) => { + return db.put(user + ':cmd', cmd) +} + +// todo: sth more efficient +const getTopLocations = (user) => { + const ns = user + ':locations:' + const top = hifo(hifo.highest('count'), 3) + + const onItem = ({key, value}) => { + const id = key.slice(ns.length) + top.add({id, count: value}) + } + + const items = db.createReadStream({gt: ns, lt: ns + last}) + return new Promise((resolve, reject) => { + items.once('error', (err) => { + reject(err) + items.destroy() + }) + items.once('end', () => { + resolve(top.data) + }) + items.on('data', onItem) + }) +} + +const incLocation = async (user, id) => { + const key = user + ':locations:' + id + try { + const count = await db.get(key) + await db.put(key, count + 1) + } catch (err) { + if (err.notFound) await db.put(key, 1) + else throw err + } +} + +module.exports = { + getCommand, putCommand, + getTopLocations, incLocation +} diff --git a/package.json b/package.json index 1b1f338..1be7b94 100644 --- a/package.json +++ b/package.json @@ -21,5 +21,7 @@ "node": ">=8" }, "dependencies": { + "hifo": "^1.0.0", + "level": "^3.0.0" } }