UNPKG

access-db

Version:

[统一数据库的连接]Unified access to all kinds of databases

79 lines (78 loc) 2.95 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const pathTo_1 = require("../utils/pathTo"); const constants_1 = require("../constants/constants"); const error_1 = require("../constants/error"); const findTrans_1 = __importDefault(require("../utils/findTrans")); const utils_1 = require("../utils/utils"); const fs = require('fs'); const POSITION_STEP = 9; function fetchFind(table, params = {}) { const filePath = (0, pathTo_1.pathTo)(table); let oldBuf, result = [], newarr = []; if (!fs.existsSync(filePath)) { return { data: { objects: result } }; // throw new Error(FASTDB_FILE_ERROR) } oldBuf = fs.readFileSync(filePath); let limit = (params.limit || 20); let all = limit * (params.page || 1); let t_positon = POSITION_STEP, t_json, n = 0; if (params.orderBy) { if (!(0, utils_1.isArray)(params.orderBy)) throw new Error(error_1.ORDER_BY_NOT_ARRAY); let all_json = JSON.parse(oldBuf.toString()); if (params.orderBy[0][0] === '-') { newarr = (0, utils_1.fastdbSort)(all_json, params.orderBy[0].substr(1), 0); } else { newarr = (0, utils_1.fastdbSort)(all_json, params.orderBy[0], 1); } let index = 0; while (result.length < all && index < newarr.length) { t_json = newarr[index]; let isOk = (0, findTrans_1.default)(params, 1, t_json, constants_1.PLATFORM_NAME.FASTDB); if (isOk) { result.push(t_json); } index++; } result = result.slice(all - limit, all); } else { while (result.length < all && t_positon < oldBuf.length) { let start = oldBuf.lastIndexOf(`{"id":`, t_positon); let end = oldBuf.indexOf(`,{"id"`, t_positon); if (end === -1) { end = oldBuf.length - 1; } if (start > -1) { t_json = JSON.parse(oldBuf.slice(start, end).toString()); } let isOk = (0, findTrans_1.default)(params, 1, t_json, constants_1.PLATFORM_NAME.FASTDB); if (isOk) { result.push(t_json); } t_positon = end + POSITION_STEP; } result = result.slice(all - limit, all); } // let tempAdd: any[] = [] // if(params.select){ // for(let i = 0; i < result.length; i++){ // let o = {} // for(let j = 0; j < params.select.length; j++){ // if(params.select[j][0] === '-'){ // delete result[i][params.select[j].substr(1)] // }else{ // o[result[i][params.select[j]]] // } // } // } // } return { data: { objects: result } }; } exports.default = fetchFind;