access-db
Version:
[统一数据库的连接]Unified access to all kinds of databases
41 lines (40 loc) • 1.61 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const pathTo_1 = require("../utils/pathTo");
const timeHash_1 = require("../utils/timeHash");
const error_1 = require("../constants/error");
const utils_1 = require("../utils/utils");
const fs = require('fs');
function fetchSet(table, params = {}) {
const filePath = (0, pathTo_1.pathTo)(table);
let oldBuf, tempParams = Object.assign({}, params);
if (!fs.existsSync(filePath)) {
(0, pathTo_1.mkdir)(filePath, '[]');
}
if (!tempParams.id) {
tempParams = Object.assign({ id: (0, timeHash_1.strHash)() }, tempParams);
}
else {
const tempid = tempParams.id;
delete tempParams.id;
tempParams = Object.assign({ id: tempid }, tempParams);
}
oldBuf = fs.readFileSync(filePath);
if ((0, utils_1.isNumber)(tempParams.id)) {
if (oldBuf.includes(`"id":${tempParams.id}`)) {
throw new Error(error_1.FASTDB_HAVE_ID_ERROR + ': ' + tempParams.id);
}
}
else {
if (oldBuf.includes(`"id":"${tempParams.id}"`)) {
throw new Error(error_1.FASTDB_HAVE_ID_ERROR + ': ' + tempParams.id);
}
}
let offset = oldBuf.length - 1;
let nowBuf = Buffer.from((oldBuf.length === 2 ? '' : ',') + JSON.stringify((0, utils_1.changeSetParams)(tempParams)) + ']');
let tempBuf = Buffer.concat([oldBuf, Buffer.allocUnsafe(nowBuf.length - 1)]);
let addBuf = tempBuf.fill(nowBuf, offset);
fs.writeFileSync(filePath, addBuf);
return { data: { insertId: tempParams.id } };
}
exports.default = fetchSet;