UNPKG

tedb

Version:

TypeScript Embedded Database

127 lines 4.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("./utils"); const tedb_utils_1 = require("tedb-utils"); /** * Database Cursor */ class Cursor { /** * Constructor * @param datastore - Datastore reference * @param query - query for search * @param count - is this a count operation? Default: false */ constructor(datastore, query = {}, count) { this.datastore = datastore; this.query = query; this.count = count || false; this.options = {}; } /** * Sort order for fields * @param sort - sort object `{fieldName: 1 | -1}` */ sort(sort) { this.options.sort = sort; return this; } /** * Set how many results to skip * @param skip - how many results to skip */ skip(skip) { this.options.skip = skip; return this; } /** * Limit result size * @param limit - how many results */ limit(limit) { this.options.limit = limit; return this; } /** * Execute the Cursor */ exec() { return new Promise((resolve, reject) => { const promisesGetIds = []; if (tedb_utils_1.isEmpty(this.query)) { promisesGetIds.push(this.datastore.search()); } else { const searchKeys = Object.keys(this.query); if (searchKeys.indexOf("$or") !== -1 || searchKeys.indexOf("$and") !== -1) { for (const field in this.query) { if (this.query.hasOwnProperty(field)) { promisesGetIds.push(this.datastore.search(field, this.query[field])); } } } else { const searchValues = Object.values(this.query); const newQuery = { $and: [] }; searchKeys.forEach((v, i) => { const obj = {}; obj[v] = searchValues[i]; newQuery.$and.push(obj); }); promisesGetIds.push(this.datastore.search("$and", newQuery.$and)); } } const joined = Promise.all(promisesGetIds); // confusing type issues* joined .then((idsArr) => { idsArr = tedb_utils_1.flattenArr(idsArr); const ids = tedb_utils_1.rmArrDups(idsArr); if (this.count) { return ids.length; } else { return this.datastore.getDocs(this.options, ids); } }) .then((res) => { if (this.options.sort) { try { const sortKey = Object.keys(this.options.sort)[0]; // at created at field for querying if (sortKey === "$created_at") { res.forEach((doc) => { doc.$created_at = this.datastore.getIdDate(doc._id); }); } const sortValue = this.options.sort[sortKey]; const sortType = utils_1.getSortType(res, sortKey); if (sortType === "") { // can't sort null or undefined return res; } else { if (sortKey === "$created_at") { const removeCreatedAtField = utils_1.mergeSort(res, sortKey, sortValue, sortType); removeCreatedAtField.forEach((doc) => delete doc.$created_at); return removeCreatedAtField; } else { return utils_1.mergeSort(res, sortKey, sortValue, sortType); } } } catch (e) { return reject(e); } } else { return res; } }) .then(resolve) .catch(reject); }); } } exports.default = Cursor; //# sourceMappingURL=cursor.js.map