Skip to content

Instantly share code, notes, and snippets.

@ronag
Created October 12, 2016 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronag/24022ab7e097f9af3ee6b5a7545603d0 to your computer and use it in GitHub Desktop.
Save ronag/24022ab7e097f9af3ee6b5a7545603d0 to your computer and use it in GitHub Desktop.
import * as events from 'events'
import * as pckg from '../package.json'
import PouchDB from 'pouchdb'
import PouchDBUpsert from 'pouchdb-upsert'
PouchDB.plugin(PouchDBUpsert)
function transformValueForStorage (value) {
value = JSON.parse(JSON.stringify(value))
let data = value._d
delete value._d
if (data instanceof Array) {
data = {
$dsList: data,
$ds: value
}
} else {
data.$ds = value
}
return data
}
function transformValueFromStorage (value) {
value = JSON.parse(JSON.stringify(value))
var data = value.$ds
delete value.$ds
if (value.$dsList instanceof Array) {
data._d = value.$dsList
} else {
data._d = value
}
return data
}
export default class Connector extends events.EventEmitter {
constructor (options) {
super()
this.isReady = false
this.name = pckg.name
this.version = pckg.version
this.db = new PouchDB(options)
this.db
.info()
.then(() => {
this.isReady = true
this.emit('ready')
})
.catch(err => {
this.emit('error', err.message)
})
}
set (key, value, callback) {
this.db
.upsert(key, doc => transformValueForStorage(value))
.then(res => callback(null))
.catch(err => callback(err.message))
}
get (key, callback) {
this.db
.get(key)
.then(val => callback(null, transformValueFromStorage(val)))
.catch(err => {
if (err.status === 404) {
callback(null, null)
} else {
callback(err.message)
}
})
}
delete (key, callback) {
this.db
.delete(key)
.then(() => callback(null))
.catch(err => callback(err.message))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment