UNPKG

blow-collection

Version:

Simple in memory collection with Rx / Observable interface.

103 lines (102 loc) 3.02 kB
'use strict'; const rxjs_1 = require('rxjs'); const uuid = require('node-uuid'); const _ = require('./helpers'); class Collection { constructor(options) { options = options || {}; this._idKey = options.idKey || '_id'; this._idGenerator = options.idGenerator || (() => uuid.v4()); this._data = []; } get size() { return this._data.length; } get _data$() { return rxjs_1.Observable.from(this._data); } _getId(data) { return _.get(data, this._idKey); } _setId(data, id) { return _.set(data, this._idKey, id || this._idGenerator()); } _hasId(data) { return _.has(data, this._idKey); } create(data) { data = _.dropReference(data); if (!this._hasId(data)) { data = this._setId(data); } this._data.push(data); return rxjs_1.Observable.of(_.dropReference(data)); } update(where, data) { return _.where(this._data$, where) .map(row => Object.assign(row, data)) .count(); } updateOrCreate(data) { if (this._hasId(data)) { return this.findById(this._getId(data)) .defaultIfEmpty() .mergeMap(current => { if (!current) { return this.create(data); } else { Object.assign(current, data); return rxjs_1.Observable.of(_.dropReference(current)); } }); } else { return this.create(data); } } count(where) { where = where || {}; return _.where(this._data$, where).count(); } destroy(where) { where = where || {}; return _.where(this._data$, where, true) .toArray() .map(rows => { const count = this._data.length - rows.length; this._data = rows; return count; }); } destroyById(id) { const where = this._setId({}, id); return this.destroy(where).map(num => !!num); } find(query) { query = _.prepareQuery(query); return _.filter(this._data$, query).map(row => Object.assign({}, row)); } findOne(query) { query = _.prepareQuery(query); return this.find(Object.assign(query, { limit: 1 })); } findById(id) { const where = this._setId({}, id); return _.filter(this._data$, { where: where }).map(row => Object.assign({}, row)); } findOrCreate(where, data) { return this.findOne({ where: where }).defaultIfEmpty().mergeMap(current => { if (!current) { return this.create(data); } else { return rxjs_1.Observable.of(_.dropReference(current)); } }); } exists(id) { return this.findById(id).map(row => !!row).defaultIfEmpty(false); } } exports.Collection = Collection;