tspace-mysql
Version:
Tspace MySQL is a promise-based ORM for Node.js, designed with modern TypeScript and providing type safety for schema databases.
175 lines • 7.41 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DBCache = void 0;
const __1 = require("..");
const utils_1 = __importDefault(require("../../utils"));
const constants_1 = __importDefault(require("../../constants"));
class DBCache {
constructor() {
this._cacheTable = '$cache';
this._v0x = 'v0x';
this._maxAddress = 10;
this._maxLength = 100;
this._db = () => new __1.DB(this._cacheTable);
}
provider() {
return 'db';
}
all() {
return __awaiter(this, void 0, void 0, function* () {
const cacheds = yield this._db().get();
const values = [];
for (const cached of cacheds) {
for (let i = 0; i < this._maxAddress; i++) {
const find = cached[this._addressNumber(i)];
if (find == null || find === '')
break;
if (Number.isNaN(+cached.expiredAt) ||
new Date() > new Date(+cached.expiredAt)) {
yield this._db()
.where('key', cached.key)
.delete();
continue;
}
const maybeArray = this._safetyJsonParse(find);
if (Array.isArray(maybeArray)) {
values.push(...this._safetyJsonParse(find));
continue;
}
values.push(this._safetyJsonParse(find));
}
}
return values;
});
}
exists(key) {
return __awaiter(this, void 0, void 0, function* () {
const cached = yield this._db().where('key', key).exists();
return cached;
});
}
get(key) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
try {
const cached = yield this._db().where('key', key).findOne();
if (!cached)
return null;
if (Number.isNaN(+cached.expiredAt) ||
new Date() > new Date(+cached.expiredAt)) {
yield this._db()
.where('key', key)
.delete();
return null;
}
const value = this._safetyJsonParse(cached[this._addressNumber(0)]);
if (!Array.isArray(value))
return value;
const values = [];
for (let i = 0; i < this._maxAddress; i++) {
const find = cached[this._addressNumber(i)];
if (find == null || find === '')
break;
const maybeArray = this._safetyJsonParse(find);
if (Array.isArray(maybeArray)) {
values.push(...this._safetyJsonParse(find));
continue;
}
values.push(this._safetyJsonParse(find));
}
return values;
}
catch (err) {
const message = String((_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : '');
if (message.toLocaleLowerCase().includes("doesn't exist")) {
yield this._checkTableCacheExists();
return yield this.get(key);
}
throw err;
}
});
}
set(key, value, ms) {
return __awaiter(this, void 0, void 0, function* () {
const expiredAt = Date.now() + ms;
if (!Array.isArray(value)) {
yield this._db().create({
key,
[this._addressNumber(0)]: JSON.stringify(value),
expiredAt,
createdAt: utils_1.default.timestamp(),
updatedAt: utils_1.default.timestamp()
})
.void()
.save();
return;
}
const avg = value.length / this._maxAddress;
const chunked = utils_1.default.chunkArray(value, avg > this._maxLength ? avg : this._maxLength);
const cache = {};
for (const [index, value] of chunked.entries()) {
cache[this._addressNumber(index)] = JSON.stringify(value);
}
yield this._db().create(Object.assign(Object.assign({ key }, cache), { expiredAt, createdAt: utils_1.default.timestamp(), updatedAt: utils_1.default.timestamp() }))
.void()
.save();
return;
});
}
clear() {
return __awaiter(this, void 0, void 0, function* () {
yield this._db().truncate({ force: true });
return;
});
}
delete(key) {
return __awaiter(this, void 0, void 0, function* () {
yield this._db().where('key', key).delete();
return;
});
}
_addressNumber(number) {
const index = `0${number}`.slice(-2);
return `${this._v0x}${index}`;
}
_checkTableCacheExists() {
return __awaiter(this, void 0, void 0, function* () {
const table = this._cacheTable;
const checkTables = yield new __1.DB().rawQuery(`${constants_1.default.SHOW_TABLES} ${constants_1.default.LIKE} '${table}'`);
const existsTables = checkTables.map((c) => Object.values(c)[0])[0];
if (existsTables != null)
return;
let address = {};
for (let i = 0; i < this._maxAddress; i++) {
address[this._addressNumber(i)] = new __1.Blueprint().longText().null();
}
const schemaLogger = Object.assign(Object.assign({ id: new __1.Blueprint().int().notNull().primary().autoIncrement(), key: new __1.Blueprint().longText().notNull() }, address), { expiredAt: new __1.Blueprint().varchar(100).null(), createdAt: new __1.Blueprint().timestamp().null(), updatedAt: new __1.Blueprint().timestamp().null() });
const sql = new __1.Schema().createTable(`\`${table}\``, schemaLogger);
yield new __1.DB().rawQuery(sql);
return;
});
}
_safetyJsonParse(value) {
try {
return JSON.parse(value);
}
catch (e) {
return value;
}
}
}
exports.DBCache = DBCache;
exports.default = DBCache;
//# sourceMappingURL=DBCache.js.map