add usave of lokijs for storage

Signed-off-by: Jakub Sokołowski <jakub@status.im>
This commit is contained in:
Jakub Sokołowski 2018-12-12 22:14:43 +01:00
parent 16069158a7
commit 8c81e20027
No known key found for this signature in database
GPG Key ID: 4EF064D0E6D63020
3 changed files with 37 additions and 12 deletions

View File

@ -10,7 +10,8 @@
"koa-bodyparser": "^4.2.1",
"koa-json": "^2.0.2",
"koa-logger": "^3.2.0",
"koa-router": "^7.4.0"
"koa-router": "^7.4.0",
"lokijs": "^1.5.5"
},
"devDependencies": {
"@babel/cli": "^7.1.2",

View File

@ -1,12 +1,36 @@
import Loki from 'lokijs'
class Builds {
constructor(db) {
this.db = db
this.builds = db.addCollection('builds', {unique:['id']})
this.comments = db.addCollection('comments', {unique: ['pr']})
constructor(path, interval) {
this.db = new Loki(path, {
autoload: true,
autosave: true,
autosaveInterval: interval,
autoloadCallback: this.initDB.bind(this),
})
}
initDB() {
this.builds = this.db.getCollection('builds')
if (!this.builds) {
this.builds = this.db.addCollection('builds')
}
this.comments = this.db.getCollection('comments')
if (!this.comments) {
this.comments = this.db.addCollection('comments')
}
/* just to make sure we save on close */
this.db.on('close', () => this.save())
}
async save () {
this.db.saveDatabase((err) => {
console.log(err?"error saving":"saved");
})
}
async getBuilds (pr) {
const builds = this.builds.find({pr})
const builds = await this.builds.find({pr})
/* strip the $loki attribute */
return builds.map((b) => {
const {$loki, ...build} = b
@ -15,7 +39,7 @@ class Builds {
}
async addBuild (pr, build) {
return this.builds.insert({pr, ...build})
return await this.builds.insert({pr, ...build})
}
async addComment (pr, comment_id) {
@ -23,7 +47,7 @@ class Builds {
}
async getCommentID (pr) {
const rval = this.comments.findOne({pr: pr})
const rval = await this.comments.findOne({pr: pr})
return rval ? rval.comment_id : null
}
}

View File

@ -1,7 +1,6 @@
import Logger from 'koa-logger'
import App from './app'
import Loki from 'lokijs'
import Octokit from '@octokit/rest'
import Builds from './builds'
import Comments from './comments'
@ -11,15 +10,16 @@ const LISTEN_PORT = process.env.LISTEN_PORT || 3000
const GH_TOKEN = process.env.GH_TOKEN || null
const GH_REPO_OWNER = 'status-im'
const GH_REPO_NAME = 'status-react'
const DB_PATH = '/tmp/db.json'
const DB_PATH = '/tmp/ghcomments.db'
const DB_SAVE_INTERVAL = 1000
/* to store current builds bound to a PR */
const db = new Loki(DB_PATH, {autosave:true})
const builds = new Builds(DB_PATH, DB_SAVE_INTERVAL)
/* necessary to post and update comments */
const gh = new Octokit()
gh.authenticate({type: 'token', token: GH_TOKEN})
const builds = new Builds(db)
const ghc = new Comments(gh, GH_REPO_OWNER, GH_REPO_NAME, builds)
const app = App(ghc, builds)