Skip to content

Instantly share code, notes, and snippets.

@ronag
Created October 12, 2016 06:52
Show Gist options
  • Select an option

  • Save ronag/ce58d79eb2afa58fa9d06d751a6a56b8 to your computer and use it in GitHub Desktop.

Select an option

Save ronag/ce58d79eb2afa58fa9d06d751a6a56b8 to your computer and use it in GitHub Desktop.

Revisions

  1. ronag created this gist Oct 12, 2016.
    87 changes: 87 additions & 0 deletions couchdb-connector.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,87 @@
    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))
    }

    }