Created
October 12, 2016 06:51
-
-
Save ronag/24022ab7e097f9af3ee6b5a7545603d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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