Last active
July 19, 2019 18:57
-
-
Save jugyo/7a94f36dcd414d0843f0e6686db46cc0 to your computer and use it in GitHub Desktop.
Model class with PouchDB
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
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"} |
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 { 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