zetabasejs
Version:
A NoSQL database for quick deployment.
45 lines (38 loc) • 1.65 kB
JavaScript
var DBCONN = null
class Model {
static setDBCONN(db) {
DBCONN = db
}
constructor() {
if (!DBCONN) throw "Error: ORM module is not enabled on ZetabaseJS"
this.__ctime__ = null
this.__mtime__ = null
this.__key__ = null
}
put() {
this.__key__ = this.__key__ ? this.__key__ : DBCONN._key()
if (!this.__ctime__) this.__ctime__ = this.__mtime__ = new Date().getTime() * 1000
else this.__mtime__ = new Date().getTime() * 1000
DBCONN.write(`/${this.constructor.name}/${this.__key__}`, this)
return this
}
static get(key) {
if (!DBCONN) throw "Error: Please initialize an ZetabaseJS instance with option { orm: true }."
return Object.assign(new this(), DBCONN.read(`/${this.name}/${key}`))
}
static query(options) {
if (!DBCONN) throw "Error: Please initialize an ZetabaseJS instance with option { orm: true }."
if (!DBCONN.containsKey(new this().constructor.name)) return null;
options = this._defaultOptions(options || {})
let results = DBCONN.query(`/${this.name}/:key/@${options.fields}`, options.filters)
return results && options.get ? results.map(res => this.get(res.__key__)) : results
}
static _defaultOptions(options) {
if (!options.fields) options.fields = "{}"
if (isNaN(options.get)) options.get = true
if (options.get && options.fields.indexOf('__key__') < 0) options.fields = options.fields.replace('}', ', __key__ }')
if (!options.filters) options.filters = val => true
return options
}
}
module.exports = Model;