Skip to content

Commit

Permalink
storage interface
Browse files Browse the repository at this point in the history
  • Loading branch information
derhuerst committed Mar 7, 2018
1 parent f4908a2 commit 84b0a5a
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ pnpm-debug.log

package-lock.json
shrinkwrap.yaml

vbb-telegram.ldb
62 changes: 62 additions & 0 deletions lib/storage.js
Original file line number Diff line number Diff line change
@@ -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
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,7 @@
"node": ">=8"
},
"dependencies": {
"hifo": "^1.0.0",
"level": "^3.0.0"
}
}

0 comments on commit 84b0a5a

Please sign in to comment.