all files / src/connectors/ MemoryConnector.js

17.39% Statements 4/23
0% Branches 0/6
0% Functions 0/10
17.39% Lines 4/23
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                                                                                                     
'use strict';
const blow_collection_1 = require('blow-collection');
const DataConnector_1 = require('./DataConnector');
function copyObject(obj) {
    return Object.assign({}, obj);
}
class MemoryConnector extends DataConnector_1.DataConnector {
    constructor(settings) {
        super(settings);
        this._db = new Map();
    }
    _collection(collectionName) {
        if (!this._db.has(collectionName)) {
            this._db.set(collectionName, new blow_collection_1.Collection({ idKey: '_id' }));
        }
        return this._db.get(collectionName);
    }
    find(collectionName, query) {
        return this._collection(collectionName)
            .find(this._prepareQuery(query)).map(copyObject);
    }
    count(collectionName, query) {
        return this._collection(collectionName)
            .count(this._prepareQuery(query).where);
    }
    delete(collectionName, query) {
        return this._collection(collectionName)
            .destroy(this._prepareQuery(query).where);
    }
    deleteById(collectionName, id) {
        return this._collection(collectionName).destroyById(id);
    }
    get(collectionName, id) {
        return this._collection(collectionName).findById(id).map(copyObject);
    }
    save(collectionName, doc) {
        const hasId = Object.keys(doc).indexOf('_id') > -1 && doc['_id'];
        if (!hasId) {
            return this._collection(collectionName).create(doc).map(copyObject);
        }
        else {
            return this._collection(collectionName)
                .update(this._buildQueryWhereForId(doc['_id']), doc)
                .mapTo(doc);
        }
    }
    updateAttributes(collectionName, id, attributes) {
        delete attributes['_id'];
        return this.get(collectionName, id)
            .map(result => Object.assign(result, attributes))
            .mergeMap(doc => this.save(collectionName, doc));
    }
}
exports.MemoryConnector = MemoryConnector;