Skip to content

Instantly share code, notes, and snippets.

@jugyo
Last active Jul 19, 2019
Embed
What would you like to do?
Model class with PouchDB
export default class User extends Model {
static className = 'User'
}
await User._put({id: 1, name: 'Jugyo'})
await User.get(1) // {className: "User", id: 1, name: "Jugyo", _id: "User-1", _rev: "1-b2d6c93292974cd1b14a786f7576ec53"}
import { EventEmitter } from 'fbemitter'
import PouchDB from 'pouchdb'
import PouchdbAdapterMemory from 'pouchdb-adapter-memory'
import PouchdbFind from 'pouchdb-find'
PouchDB.plugin(PouchdbAdapterMemory);
PouchDB.plugin(PouchdbFind);
const db = new PouchDB('db', {adapter: 'memory'});
db.changes({
since: 'now',
live: true,
include_docs: true, // NOTE: For debug purpose
}).on('change', function (changes) {
console.log('changes', changes);
}).on('error', function (error) {
console.log('error', error);
});;
class Model {
static emitter = new EventEmitter()
static db = db
static get(id) {
return new Promise((resolve, reject) => {
db.get(this._genId(id)).then((doc) => {
resolve(doc)
}).catch(() => {
resolve(null)
})
})
}
static _put(newDoc) {
const id = this._genId(newDoc.id)
return db.get(id).catch(function (err) {
if (err.status !== 404) {
throw err;
}
return {};
}).then((oldDoc) => {
const doc = this._mergeDoc(oldDoc, newDoc)
return db.put(doc)
})
}
static _mergeDoc(oldDoc, newDoc) {
return {
_id: this._genId(newDoc.id), // NOTE: i.e. User-75 for a user id: 75
_rev: oldDoc._rev,
className: this.className,
...oldDoc,
...newDoc,
}
}
static _merge(docs) {
return Promise.all((docs || []).map((doc) => this._put(doc)))
}
static _update(id, diff) {
return this.get(id).then((doc) => {
return this._put({...diff, ...doc})
})
}
static _genId(id) {
return `${this.className}-${id}`
}
static subscribe(callback, event) {
return this.emitter.addListener(event || 'changed', callback);
}
static notify(event) {
this.emitter.emit(event || 'changed');
}
}
export default Model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment