ts-redis-orm
Advanced tools
Comparing version 0.1.3 to 0.1.4
@@ -141,2 +141,10 @@ import { | ||
// events | ||
const events = MyEntity.getEventEmitter(); | ||
events.on("create", (entity) => { /* */ }); | ||
events.on("update", (entity) => { /* */ }); | ||
events.on("delete", (entity) => { /* */ }); | ||
events.on("forceDelete", (entity) => { /* */ }); | ||
events.on("restore", (entity) => { /* */ }); | ||
// errors | ||
@@ -143,0 +151,0 @@ try { |
/// <reference types="ioredis" /> | ||
import { Query } from "./Query"; | ||
import { IArgValues, IIdObject, IInstanceValues } from "./types"; | ||
import { IArgValues, IEvent, IIdObject, IInstanceValues } from "./types"; | ||
export declare class BaseEntity { | ||
@@ -18,6 +18,7 @@ static connect(): Promise<import("ioredis").Redis>; | ||
static truncate(className: string): Promise<void>; | ||
static getEventEmitter<T extends typeof BaseEntity>(this: T): IEvent<InstanceType<T>>; | ||
static export(file: string): Promise<void>; | ||
static exportEntities<T extends BaseEntity>(entities: T[], file: string): Promise<void>; | ||
static getImportFileMeta(): void; | ||
static import(file: string): Promise<void>; | ||
static import(file: string, skipSchemasCheck?: boolean): Promise<void>; | ||
private _isNew; | ||
@@ -37,7 +38,8 @@ private _values; | ||
set<T extends BaseEntity>(this: T, values: IArgValues<T>): T; | ||
save(): Promise<void>; | ||
delete(): Promise<void>; | ||
forceDelete(): Promise<void>; | ||
restore(): Promise<void>; | ||
save(): Promise<this>; | ||
delete(): Promise<this>; | ||
forceDelete(): Promise<this>; | ||
restore(): Promise<this>; | ||
clone(): this; | ||
toJSON(): IInstanceValues<this>; | ||
protected assignStorageStrings(storageStrings: { | ||
@@ -44,0 +46,0 @@ [key: string]: string; |
"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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
@@ -37,2 +38,9 @@ }); | ||
}; | ||
var __spreadArrays = (this && this.__spreadArrays) || function () { | ||
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; | ||
for (var r = Array(s), k = 0, i = 0; i < il; i++) | ||
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) | ||
r[k] = a[j]; | ||
return r; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -42,5 +50,6 @@ var entityExporter_1 = require("./entityExporter"); | ||
var RedisOrmSchemaError_1 = require("./errors/RedisOrmSchemaError"); | ||
var metaInstance_1 = require("./metaInstance"); | ||
var eventEmitters_1 = require("./eventEmitters"); | ||
var parser_1 = require("./parser"); | ||
var Query_1 = require("./Query"); | ||
var serviceInstance_1 = require("./serviceInstance"); | ||
var BaseEntity = /** @class */ (function () { | ||
@@ -65,8 +74,15 @@ function BaseEntity() { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var redis, schemaErrors; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, metaInstance_1.metaInstance.getRedis(this)]; | ||
case 1: | ||
// this will init connection | ||
return [2 /*return*/, _a.sent()]; | ||
case 0: return [4 /*yield*/, serviceInstance_1.serviceInstance.getRedis(this)]; | ||
case 1: | ||
redis = _a.sent(); | ||
return [4 /*yield*/, serviceInstance_1.serviceInstance.compareSchemas(this)]; | ||
case 2: | ||
schemaErrors = _a.sent(); | ||
if (schemaErrors.length) { | ||
throw new RedisOrmSchemaError_1.RedisOrmSchemaError("(" + this.name + ") Invalid Schemas", schemaErrors); | ||
} | ||
return [2 /*return*/, redis]; | ||
} | ||
@@ -132,3 +148,3 @@ }); | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, metaInstance_1.metaInstance.getRedis(this, false)]; | ||
case 0: return [4 /*yield*/, serviceInstance_1.serviceInstance.getRedis(this, false)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
@@ -144,13 +160,13 @@ } | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, metaInstance_1.metaInstance.getRedis(this)]; | ||
case 0: return [4 /*yield*/, serviceInstance_1.serviceInstance.getRedis(this)]; | ||
case 1: | ||
redis = _a.sent(); | ||
return [4 /*yield*/, metaInstance_1.metaInstance.getRemoteSchemas(this, redis)]; | ||
return [4 /*yield*/, serviceInstance_1.serviceInstance.getRemoteSchemas(this, redis)]; | ||
case 2: | ||
remoteSchemas = _a.sent(); | ||
if (!remoteSchemas) return [3 /*break*/, 4]; | ||
tableName = metaInstance_1.metaInstance.getTable(this); | ||
tableName = serviceInstance_1.serviceInstance.getTable(this); | ||
keys = []; | ||
params = [ | ||
metaInstance_1.metaInstance.getSchemasJson(this), | ||
serviceInstance_1.serviceInstance.getSchemasJson(this), | ||
tableName, | ||
@@ -163,3 +179,3 @@ ]; | ||
if (saveResult.error) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError(saveResult.error); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.name + ") " + saveResult.error); | ||
} | ||
@@ -179,12 +195,12 @@ _a.label = 4; | ||
if (className !== this.name) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("You need to provide the class name for truncate"); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.name + ") You need to provide the class name for truncate"); | ||
} | ||
return [4 /*yield*/, metaInstance_1.metaInstance.getRedis(this)]; | ||
return [4 /*yield*/, serviceInstance_1.serviceInstance.getRedis(this)]; | ||
case 1: | ||
redis = _a.sent(); | ||
return [4 /*yield*/, metaInstance_1.metaInstance.getRemoteSchemas(this, redis)]; | ||
return [4 /*yield*/, serviceInstance_1.serviceInstance.getRemoteSchemas(this, redis)]; | ||
case 2: | ||
remoteSchemas = _a.sent(); | ||
if (!remoteSchemas) return [3 /*break*/, 4]; | ||
tableName = metaInstance_1.metaInstance.getTable(this); | ||
tableName = serviceInstance_1.serviceInstance.getTable(this); | ||
keys = []; | ||
@@ -205,2 +221,5 @@ params = [ | ||
}; | ||
BaseEntity.getEventEmitter = function () { | ||
return eventEmitters_1.eventEmitters.getEventEmitter(this); | ||
}; | ||
// endregion | ||
@@ -219,3 +238,3 @@ // region static method: import/export | ||
allDeleted = _a.sent(); | ||
return [4 /*yield*/, this.exportEntities(all.concat(allDeleted), file)]; | ||
return [4 /*yield*/, this.exportEntities(__spreadArrays(all, allDeleted), file)]; | ||
case 3: | ||
@@ -243,7 +262,8 @@ _a.sent(); | ||
}; | ||
BaseEntity.import = function (file) { | ||
BaseEntity.import = function (file, skipSchemasCheck) { | ||
if (skipSchemasCheck === void 0) { skipSchemasCheck = false; } | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, entityExporter_1.entityExporter.import(this, file)]; | ||
case 0: return [4 /*yield*/, entityExporter_1.entityExporter.import(this, file, skipSchemasCheck)]; | ||
case 1: | ||
@@ -307,3 +327,3 @@ _a.sent(); | ||
BaseEntity.prototype.getEntityId = function () { | ||
var primaryKeys = metaInstance_1.metaInstance.getPrimaryKeys(this.constructor).sort(); | ||
var primaryKeys = serviceInstance_1.serviceInstance.getPrimaryKeys(this.constructor).sort(); | ||
var values = []; | ||
@@ -318,3 +338,3 @@ for (var _i = 0, primaryKeys_1 = primaryKeys; _i < primaryKeys_1.length; _i++) { | ||
else { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("Invalid number value: " + value + " for primary key: " + column); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") Invalid number value: " + value + " for primary key: " + column); | ||
} | ||
@@ -327,7 +347,7 @@ } | ||
else { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("Invalid string value: '" + value + "' for primary key: " + column); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") Invalid string value: '" + value + "' for primary key: " + column); | ||
} | ||
} | ||
else { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("Invalid value: " + value + " for primary key: " + column); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") Invalid value: " + value + " for primary key: " + column); | ||
} | ||
@@ -339,3 +359,3 @@ } | ||
var values = {}; | ||
var columns = metaInstance_1.metaInstance.getColumns(this.constructor); | ||
var columns = serviceInstance_1.serviceInstance.getColumns(this.constructor); | ||
for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) { | ||
@@ -350,15 +370,15 @@ var column = columns_1[_i]; | ||
if (this.isNew) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("You cannot increment a new entity"); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") You cannot increment a new entity"); | ||
} | ||
if (metaInstance_1.metaInstance.isPrimaryKey(this.constructor, column)) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("You cannot increment primary key"); | ||
if (serviceInstance_1.serviceInstance.isPrimaryKey(this.constructor, column)) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") You cannot increment primary key"); | ||
} | ||
if (metaInstance_1.metaInstance.isUniqueKey(this.constructor, column)) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("You cannot increment unique key"); | ||
if (serviceInstance_1.serviceInstance.isUniqueKey(this.constructor, column)) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") You cannot increment unique key"); | ||
} | ||
if (!metaInstance_1.metaInstance.isNumberColumn(this.constructor, column)) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("Column need to be in the type of Number"); | ||
if (!serviceInstance_1.serviceInstance.isNumberColumn(this.constructor, column)) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") Column need to be in the type of Number"); | ||
} | ||
if (!Number.isInteger(value)) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("Increment value need to be an integer"); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") Increment value need to be an integer"); | ||
} | ||
@@ -377,5 +397,3 @@ this._increments[column] = value; | ||
case 0: return [4 /*yield*/, this._saveInternal()]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
@@ -390,5 +408,3 @@ }); | ||
case 0: return [4 /*yield*/, this._deleteInternal({ forceDelete: false })]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
@@ -403,5 +419,3 @@ }); | ||
case 0: return [4 /*yield*/, this._deleteInternal({ forceDelete: true })]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
@@ -416,5 +430,3 @@ }); | ||
case 0: return [4 /*yield*/, this._saveInternal({ isRestore: true })]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
@@ -429,2 +441,5 @@ }); | ||
}; | ||
BaseEntity.prototype.toJSON = function () { | ||
return this.getValues(); | ||
}; | ||
// endregion | ||
@@ -445,3 +460,3 @@ // region protected methods | ||
if (!(column in this._values)) { | ||
var schema = metaInstance_1.metaInstance.getSchema(this.constructor, column); | ||
var schema = serviceInstance_1.serviceInstance.getSchema(this.constructor, column); | ||
this._values[column] = parser_1.parser.parseStorageStringToValue(schema.type, this._storageStrings[column]); | ||
@@ -453,3 +468,3 @@ } | ||
if (updateStorageString === void 0) { updateStorageString = false; } | ||
var schema = metaInstance_1.metaInstance.getSchema(this.constructor, column); | ||
var schema = serviceInstance_1.serviceInstance.getSchema(this.constructor, column); | ||
var storageString = parser_1.parser.parseValueToStorageString(schema.type, value); | ||
@@ -466,3 +481,3 @@ this._values[column] = parser_1.parser.parseStorageStringToValue(schema.type, storageString); | ||
return __awaiter(this, void 0, void 0, function () { | ||
var changes, tableName, indexKeys, uniqueKeys, autoIncrementKey, entityId, params, redis, commandResult, saveResult, schemaErrors, _i, _c, _d, column, value; | ||
var changes, tableName, indexKeys, uniqueKeys, autoIncrementKey, entityId, params, redis, commandResult, saveResult, schemaErrors, _i, _c, _d, column, value, isNew; | ||
return __generator(this, function (_e) { | ||
@@ -472,3 +487,3 @@ switch (_e.label) { | ||
if (this.isDeleted && !isRestore) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("You cannot update a deleted entity"); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") You cannot update a deleted entity"); | ||
} | ||
@@ -479,3 +494,3 @@ changes = this._getChanges(); | ||
if (!isRestore && Object.keys(this._increments).length === 0) { | ||
return [2 /*return*/]; | ||
return [2 /*return*/, this]; | ||
} | ||
@@ -489,8 +504,8 @@ } | ||
changes.deletedAt = parser_1.parser.parseValueToStorageString(Date, new Date(Number.NaN)); | ||
tableName = metaInstance_1.metaInstance.getTable(this.constructor); | ||
indexKeys = metaInstance_1.metaInstance.getIndexKeys(this.constructor); | ||
uniqueKeys = metaInstance_1.metaInstance.getUniqueKeys(this.constructor); | ||
autoIncrementKey = metaInstance_1.metaInstance.getAutoIncrementKey(this.constructor); | ||
tableName = serviceInstance_1.serviceInstance.getTable(this.constructor); | ||
indexKeys = serviceInstance_1.serviceInstance.getIndexKeys(this.constructor); | ||
uniqueKeys = serviceInstance_1.serviceInstance.getUniqueKeys(this.constructor); | ||
autoIncrementKey = serviceInstance_1.serviceInstance.getAutoIncrementKey(this.constructor); | ||
entityId = ""; | ||
// we must for a new entity for the case | ||
// we must assign an entity id for the following case | ||
// - if it's not new | ||
@@ -503,3 +518,3 @@ // - if it's not auto increment | ||
params = [ | ||
metaInstance_1.metaInstance.getSchemasJson(this.constructor), | ||
serviceInstance_1.serviceInstance.getSchemasJson(this.constructor), | ||
entityId, | ||
@@ -515,3 +530,3 @@ this.isNew, | ||
]; | ||
return [4 /*yield*/, metaInstance_1.metaInstance.getRedis(this.constructor)]; | ||
return [4 /*yield*/, serviceInstance_1.serviceInstance.getRedis(this.constructor)]; | ||
case 1: | ||
@@ -525,7 +540,7 @@ redis = _e.sent(); | ||
if (!(saveResult.error === "Invalid Schemas")) return [3 /*break*/, 4]; | ||
return [4 /*yield*/, metaInstance_1.metaInstance.compareSchemas(this.constructor)]; | ||
return [4 /*yield*/, serviceInstance_1.serviceInstance.compareSchemas(this.constructor)]; | ||
case 3: | ||
schemaErrors = _e.sent(); | ||
throw new RedisOrmSchemaError_1.RedisOrmSchemaError(saveResult.error, schemaErrors); | ||
case 4: throw new RedisOrmEntityError_1.RedisOrmEntityError(saveResult.error); | ||
throw new RedisOrmSchemaError_1.RedisOrmSchemaError("(" + this.constructor.name + ") " + saveResult.error, schemaErrors); | ||
case 4: throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") " + saveResult.error); | ||
case 5: | ||
@@ -548,5 +563,17 @@ // update storage strings | ||
this._values = {}; | ||
// update the flags | ||
isNew = this._isNew; | ||
this._isNew = false; | ||
return [2 /*return*/]; | ||
// fire event | ||
if (isRestore) { | ||
eventEmitters_1.eventEmitters.getEventEmitter(this.constructor).emit("restore", this); | ||
} | ||
else { | ||
if (isNew) { | ||
eventEmitters_1.eventEmitters.getEventEmitter(this.constructor).emit("create", this); | ||
} | ||
else { | ||
eventEmitters_1.eventEmitters.getEventEmitter(this.constructor).emit("update", this); | ||
} | ||
} | ||
return [2 /*return*/, this]; | ||
} | ||
@@ -565,7 +592,7 @@ }); | ||
if (this.isNew) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("You cannot delete a new entity"); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") You cannot delete a new entity"); | ||
} | ||
entityMeta = metaInstance_1.metaInstance.getEntityMeta(this.constructor); | ||
entityMeta = serviceInstance_1.serviceInstance.getEntityMeta(this.constructor); | ||
if (!forceDelete && this.isDeleted) { | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("You cannot delete a deleted entity"); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") You cannot delete a deleted entity"); | ||
} | ||
@@ -577,7 +604,8 @@ deletedAt = this.deletedAt; | ||
entityId = this.getEntityId(); | ||
tableName = metaInstance_1.metaInstance.getTable(this.constructor); | ||
indexKeys = metaInstance_1.metaInstance.getIndexKeys(this.constructor); | ||
uniqueKeys = metaInstance_1.metaInstance.getUniqueKeys(this.constructor); | ||
tableName = serviceInstance_1.serviceInstance.getTable(this.constructor); | ||
indexKeys = serviceInstance_1.serviceInstance.getIndexKeys(this.constructor); | ||
uniqueKeys = serviceInstance_1.serviceInstance.getUniqueKeys(this.constructor); | ||
keys = []; | ||
params = [ | ||
serviceInstance_1.serviceInstance.getSchemasJson(this.constructor), | ||
entityId, | ||
@@ -590,3 +618,3 @@ !forceDelete, | ||
]; | ||
return [4 /*yield*/, metaInstance_1.metaInstance.getRedis(this.constructor)]; | ||
return [4 /*yield*/, serviceInstance_1.serviceInstance.getRedis(this.constructor)]; | ||
case 1: | ||
@@ -600,7 +628,14 @@ redis = _c.sent(); | ||
if (saveResult.error) { | ||
throw new Error(saveResult.error); | ||
throw new RedisOrmEntityError_1.RedisOrmEntityError("(" + this.constructor.name + ") " + saveResult.error); | ||
} | ||
// update deleted At | ||
this._set("deletedAt", deletedAt, true); | ||
return [2 /*return*/]; | ||
// fire event | ||
if (forceDelete) { | ||
eventEmitters_1.eventEmitters.getEventEmitter(this.constructor).emit("forceDelete", this); | ||
} | ||
else { | ||
eventEmitters_1.eventEmitters.getEventEmitter(this.constructor).emit("delete", this); | ||
} | ||
return [2 /*return*/, this]; | ||
} | ||
@@ -613,3 +648,3 @@ }); | ||
var changes = {}; | ||
var schemas = metaInstance_1.metaInstance.getSchemas(this.constructor); | ||
var schemas = serviceInstance_1.serviceInstance.getSchemas(this.constructor); | ||
for (var _i = 0, _a = Object.entries(schemas); _i < _a.length; _i++) { | ||
@@ -616,0 +651,0 @@ var _b = _a[_i], column = _b[0], schema = _b[1]; |
@@ -16,7 +16,10 @@ "use strict"; | ||
ConfigLoader.prototype.getConfigFile = function () { | ||
var name = process.env.node_env || "default"; | ||
var name = process.env.NODE_ENV || "default"; | ||
var configFiles = ["redisorm.default.json"]; | ||
if (process.env.node_env) { | ||
if (process.env.NODE_ENV) { | ||
configFiles.push("redisorm." + name + ".json"); | ||
} | ||
if (process.env.REDISORM_CONFIG_PATH) { | ||
configFiles = [process.env.REDISORM_CONFIG_PATH]; | ||
} | ||
for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { | ||
@@ -23,0 +26,0 @@ var configFile = configFiles_1[_i]; |
@@ -5,20 +5,20 @@ "use strict"; | ||
var __1 = require(".."); | ||
var metaInstance_1 = require("../metaInstance"); | ||
var serviceInstance_1 = require("../serviceInstance"); | ||
function validSchema(target, schema) { | ||
// only one schema | ||
var autoIncrementKey = metaInstance_1.metaInstance.getAutoIncrementKey(target); | ||
var autoIncrementKey = serviceInstance_1.serviceInstance.getAutoIncrementKey(target); | ||
if (autoIncrementKey) { | ||
if (schema.autoIncrement) { | ||
throw new __1.RedisOrmDecoratorError("AutoIncrement already exist for column: " + autoIncrementKey); | ||
throw new __1.RedisOrmDecoratorError("(" + target.name + ") AutoIncrement already exist for column: " + autoIncrementKey); | ||
} | ||
if (schema.primary) { | ||
throw new __1.RedisOrmDecoratorError("AutoIncrement can only work with one primary key"); | ||
throw new __1.RedisOrmDecoratorError("(" + target.name + ") AutoIncrement can only work with one primary key"); | ||
} | ||
} | ||
if (schema.autoIncrement && !schema.primary) { | ||
throw new __1.RedisOrmDecoratorError("AutoIncrement needs pair up with primary key"); | ||
throw new __1.RedisOrmDecoratorError("(" + target.name + ") AutoIncrement needs pair up with primary key"); | ||
} | ||
if (schema.primary) { | ||
if (schema.type !== String && schema.type !== Number) { | ||
throw new __1.RedisOrmDecoratorError("Primary key only supports String or Number"); | ||
throw new __1.RedisOrmDecoratorError("(" + target.name + ") Primary key only supports String or Number"); | ||
} | ||
@@ -28,3 +28,3 @@ } | ||
if (schema.type !== Number && schema.type !== Boolean && schema.type !== Date) { | ||
throw new __1.RedisOrmDecoratorError("Index only supports Number, Boolean or Date"); | ||
throw new __1.RedisOrmDecoratorError("(" + target.name + ") Index only supports Number, Boolean or Date"); | ||
} | ||
@@ -34,3 +34,3 @@ } | ||
if (schema.type !== String && schema.type !== Number) { | ||
throw new __1.RedisOrmDecoratorError("Unique only supports String or Number"); | ||
throw new __1.RedisOrmDecoratorError("(" + target.name + ") Unique only supports String or Number"); | ||
} | ||
@@ -55,3 +55,3 @@ } | ||
// everything ok , add the schema | ||
metaInstance_1.metaInstance.addColumn(target.constructor, propertyKey, newSchema); | ||
serviceInstance_1.serviceInstance.addColumn(target.constructor, propertyKey, newSchema); | ||
// define getter / setter | ||
@@ -58,0 +58,0 @@ if (!Object.getOwnPropertyDescriptor(target.constructor.prototype, propertyKey)) { |
@@ -15,3 +15,3 @@ "use strict"; | ||
var __1 = require(".."); | ||
var metaInstance_1 = require("../metaInstance"); | ||
var serviceInstance_1 = require("../serviceInstance"); | ||
function Entity(entityMeta) { | ||
@@ -28,3 +28,3 @@ if (entityMeta === void 0) { entityMeta = {}; } | ||
newEntityMeta = Object.assign(newEntityMeta, entityMeta); | ||
metaInstance_1.metaInstance.addEntity(target, newEntityMeta); | ||
serviceInstance_1.serviceInstance.addEntity(target, newEntityMeta); | ||
// add createdAt, updatedAt and deletedAt | ||
@@ -38,9 +38,9 @@ var schema = { | ||
}; | ||
metaInstance_1.metaInstance.addColumn(target, "createdAt", schema); | ||
metaInstance_1.metaInstance.addColumn(target, "updatedAt", __assign({}, schema, { index: newEntityMeta.indexUpdatedAt })); | ||
metaInstance_1.metaInstance.addColumn(target, "deletedAt", schema); | ||
serviceInstance_1.serviceInstance.addColumn(target, "createdAt", schema); | ||
serviceInstance_1.serviceInstance.addColumn(target, "updatedAt", __assign(__assign({}, schema), { index: newEntityMeta.indexUpdatedAt })); | ||
serviceInstance_1.serviceInstance.addColumn(target, "deletedAt", schema); | ||
// validate from entity | ||
var primaryKeys = metaInstance_1.metaInstance.getPrimaryKeys(target); | ||
var primaryKeys = serviceInstance_1.serviceInstance.getPrimaryKeys(target); | ||
if (primaryKeys.length === 0) { | ||
throw new __1.RedisOrmDecoratorError("No primary keys exist for this entity"); | ||
throw new __1.RedisOrmDecoratorError("(" + target.name + ") No primary keys exist for this entity"); | ||
} | ||
@@ -47,0 +47,0 @@ }; |
import { BaseEntity } from "./BaseEntity"; | ||
declare class EntityExporter { | ||
exportEntities<T extends BaseEntity>(entityType: object, entities: T[], file: string): Promise<unknown>; | ||
import(entityType: object, file: string): Promise<unknown>; | ||
import(entityType: object, file: string, skipSchemasCheck?: boolean): Promise<unknown>; | ||
} | ||
export declare const entityExporter: EntityExporter; | ||
export {}; |
"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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
@@ -50,3 +51,3 @@ }); | ||
var readline = __importStar(require("readline")); | ||
var metaInstance_1 = require("./metaInstance"); | ||
var serviceInstance_1 = require("./serviceInstance"); | ||
var EntityExporter = /** @class */ (function () { | ||
@@ -62,7 +63,7 @@ function EntityExporter() { | ||
class: entityType.name, | ||
table: metaInstance_1.metaInstance.getTable(entityType), | ||
schemas: metaInstance_1.metaInstance.getSchemas(entityType), | ||
table: serviceInstance_1.serviceInstance.getTable(entityType), | ||
schemas: serviceInstance_1.serviceInstance.getSchemasJson(entityType), | ||
total: entities.length, | ||
}; | ||
writeStream.write(JSON.stringify(meta, metaInstance_1.schemaJsonReplacer) + "\r\n"); | ||
writeStream.write(JSON.stringify(meta, serviceInstance_1.schemaJsonReplacer) + "\r\n"); | ||
// write all the models | ||
@@ -82,3 +83,4 @@ for (var _i = 0, entities_1 = entities; _i < entities_1.length; _i++) { | ||
}; | ||
EntityExporter.prototype.import = function (entityType, file) { | ||
EntityExporter.prototype.import = function (entityType, file, skipSchemasCheck) { | ||
if (skipSchemasCheck === void 0) { skipSchemasCheck = false; } | ||
return __awaiter(this, void 0, void 0, function () { | ||
@@ -179,2 +181,18 @@ var readStream, r1; | ||
} | ||
if (!skipSchemasCheck) { | ||
var className = entityType.name; | ||
var clientSchemas = serviceInstance_1.serviceInstance.getSchemasJson(entityType); | ||
if (meta.class !== className) { | ||
var err = new Error(); | ||
err.message = "Class name: " + className + " does not match with the import file: " + meta.class; | ||
currentError = err; | ||
checkError(); | ||
} | ||
else if (meta.schemas !== clientSchemas) { | ||
var err = new Error(); | ||
err.message = "Current Schemas: " + clientSchemas + " does not match with the import file: " + meta.schemas; | ||
currentError = err; | ||
checkError(); | ||
} | ||
} | ||
} | ||
@@ -181,0 +199,0 @@ else { |
import { BaseEntity } from "./BaseEntity"; | ||
import { IAggregateObject, IArgColumn, IIndexOperator, IIdObject, IOrder, IStringOperator, IUniqueValueType, IValueType } from "./types"; | ||
import { IAggregateObject, IArgColumn, IIdObject, IIndexOperator, IOrder, IStringOperator, IUniqueValueType, IValueType } from "./types"; | ||
export declare class Query<T extends typeof BaseEntity> { | ||
@@ -4,0 +4,0 @@ private readonly _entityType; |
"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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
@@ -37,6 +38,13 @@ }); | ||
}; | ||
var __spreadArrays = (this && this.__spreadArrays) || function () { | ||
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; | ||
for (var r = Array(s), k = 0, i = 0; i < il; i++) | ||
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) | ||
r[k] = a[j]; | ||
return r; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var RedisOrmQueryError_1 = require("./errors/RedisOrmQueryError"); | ||
var metaInstance_1 = require("./metaInstance"); | ||
var parser_1 = require("./parser"); | ||
var serviceInstance_1 = require("./serviceInstance"); | ||
var Query = /** @class */ (function () { | ||
@@ -57,15 +65,16 @@ function Query(_entityType) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var redis, entityId, primaryKeys, entityStorageKey, storageStrings_1; | ||
var entityId, primaryKeys, entityStorageKey, redis, storageStrings_1; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this._getRedis()]; | ||
case 1: | ||
redis = _a.sent(); | ||
entityId = metaInstance_1.metaInstance.convertAsEntityId(this._entityType, idObject); | ||
primaryKeys = metaInstance_1.metaInstance.getPrimaryKeys(this._entityType); | ||
case 0: | ||
entityId = serviceInstance_1.serviceInstance.convertAsEntityId(this._entityType, idObject); | ||
primaryKeys = serviceInstance_1.serviceInstance.getPrimaryKeys(this._entityType); | ||
if (!entityId) return [3 /*break*/, 3]; | ||
entityStorageKey = metaInstance_1.metaInstance.getEntityStorageKey(this._entityType, entityId); | ||
entityStorageKey = serviceInstance_1.serviceInstance.getEntityStorageKey(this._entityType, entityId); | ||
if (!entityStorageKey) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("Invalid id " + JSON.stringify(idObject)); | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") Invalid id " + JSON.stringify(idObject)); | ||
} | ||
return [4 /*yield*/, this._getRedis()]; | ||
case 1: | ||
redis = _a.sent(); | ||
return [4 /*yield*/, redis.hgetall(entityStorageKey)]; | ||
@@ -110,4 +119,4 @@ case 2: | ||
case 0: | ||
if (!metaInstance_1.metaInstance.isUniqueKey(this._entityType, column)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("Invalid unique column: " + column); | ||
if (!serviceInstance_1.serviceInstance.isUniqueKey(this._entityType, column)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") Invalid unique column: " + column); | ||
} | ||
@@ -117,3 +126,3 @@ return [4 /*yield*/, this._getRedis()]; | ||
redis = _a.sent(); | ||
return [4 /*yield*/, redis.hget(metaInstance_1.metaInstance.getUniqueStorageKey(this._entityType, column), value.toString())]; | ||
return [4 /*yield*/, redis.hget(serviceInstance_1.serviceInstance.getUniqueStorageKey(this._entityType, column), value.toString())]; | ||
case 2: | ||
@@ -175,12 +184,12 @@ id = _a.sent(); | ||
var columnString = column; | ||
if (metaInstance_1.metaInstance.isIndexKey(this._entityType, columnString)) { | ||
if (serviceInstance_1.serviceInstance.isIndexKey(this._entityType, columnString)) { | ||
if (this._onlyDeleted) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("You cannot apply extra where indexing clause for only deleted query"); | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") You cannot apply extra where indexing clause for only deleted query"); | ||
} | ||
if (!metaInstance_1.metaInstance.isIndexKey(this._entityType, columnString)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("Invalid index column: " + column); | ||
if (!serviceInstance_1.serviceInstance.isIndexKey(this._entityType, columnString)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") Invalid index column: " + column); | ||
} | ||
// convert value into string value | ||
if (value !== "-inf" && value !== "+inf") { | ||
var schema = metaInstance_1.metaInstance.getSchema(this._entityType, columnString); | ||
var schema = serviceInstance_1.serviceInstance.getSchema(this._entityType, columnString); | ||
value = parser_1.parser.parseValueToStorageString(schema.type, value); | ||
@@ -210,12 +219,12 @@ } | ||
default: | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("Invalid operator (" + operator + ") for index column: " + column); | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") Invalid operator (" + operator + ") for index column: " + column); | ||
} | ||
this._whereIndexes[columnString] = whereIndexType; | ||
} | ||
else if (metaInstance_1.metaInstance.isSearchableColumn(this._entityType, columnString)) { | ||
else if (serviceInstance_1.serviceInstance.isSearchableColumn(this._entityType, columnString)) { | ||
if (!["=", "!=", "like"].includes(operator)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("Invalid operator (" + operator + ") for non index column: " + column); | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") Invalid operator (" + operator + ") for non index column: " + column); | ||
} | ||
// convert value into string value | ||
var schema = metaInstance_1.metaInstance.getSchema(this._entityType, columnString); | ||
var schema = serviceInstance_1.serviceInstance.getSchema(this._entityType, columnString); | ||
value = parser_1.parser.parseValueToStorageString(schema.type, value); | ||
@@ -225,3 +234,3 @@ this._whereSearches[columnString] = { operator: operator, value: value }; | ||
else { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("Invalid search column: " + column); | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") Invalid search column: " + column); | ||
} | ||
@@ -232,3 +241,3 @@ return this; | ||
if (Object.keys(this._whereIndexes).length > 0) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("You cannot apply extra where indexing clause for only deleted query"); | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") You cannot apply extra where indexing clause for only deleted query"); | ||
} | ||
@@ -242,6 +251,6 @@ this.where("deletedAt", "<=", "+inf"); | ||
if (this._sortBy !== null) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("You can only order by 1 column"); | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") You can only order by 1 column"); | ||
} | ||
if (!metaInstance_1.metaInstance.isSortableColumn(this._entityType, column)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("Not sortable Column: " + column + ". You can only sort column type of Number, Boolean or Date"); | ||
if (!serviceInstance_1.serviceInstance.isSortableColumn(this._entityType, column)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") Not sortable Column: " + column + ". You can only sort column type of Number, Boolean or Date"); | ||
} | ||
@@ -266,6 +275,6 @@ this._sortBy = { column: column, order: order }; | ||
if (this._groupByColumn !== null) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("You can only group by 1 column"); | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") You can only group by 1 column"); | ||
} | ||
if (!metaInstance_1.metaInstance.isValidColumn(this._entityType, column)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("Invalid column: " + column); | ||
if (!serviceInstance_1.serviceInstance.isValidColumn(this._entityType, column)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") Invalid column: " + column); | ||
} | ||
@@ -336,7 +345,7 @@ this._groupByColumn = column; | ||
case 0: | ||
if (!metaInstance_1.metaInstance.isIndexKey(this._entityType, column)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("Invalid index column: " + column); | ||
if (!serviceInstance_1.serviceInstance.isIndexKey(this._entityType, column)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") Invalid index column: " + column); | ||
} | ||
indexStorageKey = metaInstance_1.metaInstance.getIndexStorageKey(this._entityType, column); | ||
entityId = metaInstance_1.metaInstance.convertAsEntityId(this._entityType, idObject); | ||
indexStorageKey = serviceInstance_1.serviceInstance.getIndexStorageKey(this._entityType, column); | ||
entityId = serviceInstance_1.serviceInstance.convertAsEntityId(this._entityType, idObject); | ||
if (!entityId) return [3 /*break*/, 6]; | ||
@@ -391,3 +400,3 @@ return [4 /*yield*/, this._getRedis()]; | ||
this._limit, | ||
metaInstance_1.metaInstance.getTable(this._entityType), | ||
serviceInstance_1.serviceInstance.getTable(this._entityType), | ||
"", | ||
@@ -438,3 +447,3 @@ "", | ||
order = this._sortBy ? this._sortBy.order : "asc"; | ||
indexStorageKey = metaInstance_1.metaInstance.getIndexStorageKey(this._entityType, column); | ||
indexStorageKey = serviceInstance_1.serviceInstance.getIndexStorageKey(this._entityType, column); | ||
extraParams = ["LIMIT", this._offset.toString(), this._limit.toString()]; | ||
@@ -446,3 +455,3 @@ return [4 /*yield*/, this._getRedis()]; | ||
if (!(order === "asc")) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, redis.zrangebyscore.apply(redis, [indexStorageKey, min, max].concat(extraParams))]; | ||
return [4 /*yield*/, redis.zrangebyscore.apply(redis, __spreadArrays([indexStorageKey, min, max], extraParams))]; | ||
case 2: | ||
@@ -453,3 +462,3 @@ ids = _a.sent(); | ||
if (!(order === "desc")) return [3 /*break*/, 5]; | ||
return [4 /*yield*/, redis.zrevrangebyscore.apply(redis, [indexStorageKey, max, min].concat(extraParams))]; | ||
return [4 /*yield*/, redis.zrevrangebyscore.apply(redis, __spreadArrays([indexStorageKey, max, min], extraParams))]; | ||
case 4: | ||
@@ -471,4 +480,4 @@ ids = _a.sent(); | ||
if (aggregate !== "count") { | ||
if (!metaInstance_1.metaInstance.isNumberColumn(this._entityType, aggregateColumn)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("Column: " + aggregateColumn + " is not in the type of number"); | ||
if (!serviceInstance_1.serviceInstance.isNumberColumn(this._entityType, aggregateColumn)) { | ||
throw new RedisOrmQueryError_1.RedisOrmQueryError("(" + this._entityType.name + ") Column: " + aggregateColumn + " is not in the type of number"); | ||
} | ||
@@ -493,3 +502,3 @@ } | ||
this._offset, | ||
metaInstance_1.metaInstance.getTable(this._entityType), | ||
serviceInstance_1.serviceInstance.getTable(this._entityType), | ||
aggregate, | ||
@@ -546,7 +555,7 @@ aggregateColumn, | ||
if (!(max === "+inf" && min === "-inf")) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, redis.zcard(metaInstance_1.metaInstance.getIndexStorageKey(this._entityType, column))]; | ||
return [4 /*yield*/, redis.zcard(serviceInstance_1.serviceInstance.getIndexStorageKey(this._entityType, column))]; | ||
case 2: | ||
count = _a.sent(); | ||
return [3 /*break*/, 5]; | ||
case 3: return [4 /*yield*/, redis.zcount(metaInstance_1.metaInstance.getIndexStorageKey(this._entityType, column), min, max)]; | ||
case 3: return [4 /*yield*/, redis.zcount(serviceInstance_1.serviceInstance.getIndexStorageKey(this._entityType, column), min, max)]; | ||
case 4: | ||
@@ -564,3 +573,3 @@ count = _a.sent(); | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, metaInstance_1.metaInstance.getRedis(this._entityType)]; | ||
case 0: return [4 /*yield*/, serviceInstance_1.serviceInstance.getRedis(this._entityType)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
@@ -567,0 +576,0 @@ } |
@@ -69,1 +69,10 @@ import * as IORedis from "ioredis"; | ||
export declare type IIdObject<T> = IArgValues<T> | number | string; | ||
export declare type IEventType = "create" | "update" | "delete" | "forceDelete" | "restore"; | ||
export interface IEvent<T> { | ||
on(type: IEventType, callback: (entity: T) => void): any; | ||
addListener(type: IEventType, callback: (entity: T) => void): any; | ||
removeListener(type: IEventType, callback: (entity: T) => void): any; | ||
once(type: IEventType, callback: (entity: T) => void): any; | ||
off(type: IEventType, callback: (entity: T) => void): any; | ||
emit(type: IEventType, entity: T): any; | ||
} |
{ | ||
"name": "ts-redis-orm", | ||
"version": "0.1.3", | ||
"version": "0.1.4", | ||
"description": "A full functional Redis Orm library written in Typescript.", | ||
@@ -23,13 +23,13 @@ "main": "build/index.js", | ||
"ioredis": "^4.14.1", | ||
"@types/ioredis": "^4.0.18", | ||
"reflect-metadata": "^0.1.13" | ||
}, | ||
"devDependencies": { | ||
"@types/chai": "^4.2.3", | ||
"@types/ioredis": "^4.0.18", | ||
"@types/chai": "^4.2.4", | ||
"@types/mocha": "^5.2.7", | ||
"@types/node": "^12.7.8", | ||
"@types/node": "^12.11.7", | ||
"chai": "^4.2.0", | ||
"mocha": "^6.2.0", | ||
"mocha": "^6.2.2", | ||
"ts-node": "^8.4.1", | ||
"typescript": "^3.6.3" | ||
"typescript": "^3.6.4" | ||
}, | ||
@@ -36,0 +36,0 @@ "repository": { |
@@ -170,2 +170,11 @@ # Redis ORM (Typescript) | ||
// events | ||
const events = MyEntity.getEventEmitter(); | ||
events.on("create", (entity) => { /* */ }); | ||
events.on("update", (entity) => { /* */ }); | ||
events.on("delete", (entity) => { /* */ }); | ||
events.on("forceDelete", (entity) => { /* */ }); | ||
events.on("restore", (entity) => { /* */ }); | ||
// errors | ||
@@ -200,4 +209,6 @@ try { | ||
- Create redisorm.default.json in the project root folder. | ||
- If you wanted to manage multiple environment, you can create redisorm.${node_env}.json, where ${node_env} eqauls to the process.env.node_env environment variable. | ||
- If you wanted to manage multiple environment, you can create redisorm.${NODE_ENV}.json, where ${NODE_ENV} eqauls to the process.env.NODE_ENV environment variable. | ||
- The library will search for the environment specific json file first. If it does not exist, it will try to load the redisorm.default.json. | ||
- Export env variable REDIS_ORM_CONFIG=custom.json for your own config file path | ||
```json5 | ||
@@ -204,0 +215,0 @@ { |
import {entityExporter} from "./entityExporter"; | ||
import {RedisOrmEntityError} from "./errors/RedisOrmEntityError"; | ||
import {RedisOrmSchemaError} from "./errors/RedisOrmSchemaError"; | ||
import {metaInstance} from "./metaInstance"; | ||
import {eventEmitters} from "./eventEmitters"; | ||
import {parser} from "./parser"; | ||
import {Query} from "./Query"; | ||
import {IArgValues, IIdObject, IInstanceValues, ISaveResult} from "./types"; | ||
import {serviceInstance} from "./serviceInstance"; | ||
import {IArgValues, IEvent, IIdObject, IInstanceValues, ISaveResult} from "./types"; | ||
@@ -13,12 +14,9 @@ export class BaseEntity { | ||
public static async connect() { | ||
// this will init connection | ||
const redis = await metaInstance.getRedis(this); | ||
// validate the schema | ||
const schemaErrors = await metaInstance.compareSchemas(this); | ||
const schemaErrors = await serviceInstance.compareSchemas(this); | ||
if (schemaErrors.length) { | ||
throw new RedisOrmSchemaError("Invalid Schemas", schemaErrors); | ||
throw new RedisOrmSchemaError(`(${this.name}) Invalid Schemas`, schemaErrors); | ||
} | ||
return redis; | ||
return await serviceInstance.getRedis(this); | ||
} | ||
@@ -61,3 +59,3 @@ | ||
public static async getRedis() { | ||
return await metaInstance.getRedis(this, false); | ||
return await serviceInstance.getRedis(this, false); | ||
} | ||
@@ -67,4 +65,4 @@ | ||
// get redis, | ||
const redis = await metaInstance.getRedis(this); | ||
const remoteSchemas = await metaInstance.getRemoteSchemas(this, redis); | ||
const redis = await serviceInstance.getRedis(this); | ||
const remoteSchemas = await serviceInstance.getRemoteSchemas(this, redis); | ||
@@ -74,6 +72,6 @@ // we resync only if we found any schema exist | ||
// prepare arguments | ||
const tableName = metaInstance.getTable(this); | ||
const tableName = serviceInstance.getTable(this); | ||
const keys: [] = []; | ||
const params = [ | ||
metaInstance.getSchemasJson(this), | ||
serviceInstance.getSchemasJson(this), | ||
tableName, | ||
@@ -87,3 +85,3 @@ ]; | ||
if (saveResult.error) { | ||
throw new RedisOrmEntityError(saveResult.error); | ||
throw new RedisOrmEntityError(`(${this.name}) ${saveResult.error}`); | ||
} | ||
@@ -95,8 +93,8 @@ } | ||
if (className !== this.name) { | ||
throw new RedisOrmEntityError("You need to provide the class name for truncate"); | ||
throw new RedisOrmEntityError(`(${this.name}) You need to provide the class name for truncate`); | ||
} | ||
// get redis, | ||
const redis = await metaInstance.getRedis(this); | ||
const remoteSchemas = await metaInstance.getRemoteSchemas(this, redis); | ||
const redis = await serviceInstance.getRedis(this); | ||
const remoteSchemas = await serviceInstance.getRemoteSchemas(this, redis); | ||
@@ -106,3 +104,3 @@ // we truncate only if we found any schema exist | ||
// prepare arguments | ||
const tableName = metaInstance.getTable(this); | ||
const tableName = serviceInstance.getTable(this); | ||
const keys: [] = []; | ||
@@ -118,2 +116,6 @@ const params = [ | ||
public static getEventEmitter<T extends typeof BaseEntity>(this: T): IEvent<InstanceType<T>> { | ||
return eventEmitters.getEventEmitter(this); | ||
} | ||
// endregion | ||
@@ -208,3 +210,3 @@ | ||
public getEntityId(): string { | ||
const primaryKeys = metaInstance.getPrimaryKeys(this.constructor).sort(); | ||
const primaryKeys = serviceInstance.getPrimaryKeys(this.constructor).sort(); | ||
const values: string[] = []; | ||
@@ -218,3 +220,3 @@ | ||
} else { | ||
throw new RedisOrmEntityError(`Invalid number value: ${value} for primary key: ${column}`); | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) Invalid number value: ${value} for primary key: ${column}`); | ||
} | ||
@@ -226,6 +228,6 @@ | ||
} else { | ||
throw new RedisOrmEntityError(`Invalid string value: '${value}' for primary key: ${column}`); | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) Invalid string value: '${value}' for primary key: ${column}`); | ||
} | ||
} else { | ||
throw new RedisOrmEntityError(`Invalid value: ${value} for primary key: ${column}`); | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) Invalid value: ${value} for primary key: ${column}`); | ||
} | ||
@@ -239,3 +241,3 @@ } | ||
const values: any = {}; | ||
const columns = metaInstance.getColumns(this.constructor); | ||
const columns = serviceInstance.getColumns(this.constructor); | ||
for (const column of columns) { | ||
@@ -250,19 +252,19 @@ values[column] = this._get(column); | ||
if (this.isNew) { | ||
throw new RedisOrmEntityError("You cannot increment a new entity"); | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) You cannot increment a new entity`); | ||
} | ||
if (metaInstance.isPrimaryKey(this.constructor, column as string)) { | ||
throw new RedisOrmEntityError("You cannot increment primary key"); | ||
if (serviceInstance.isPrimaryKey(this.constructor, column as string)) { | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) You cannot increment primary key`); | ||
} | ||
if (metaInstance.isUniqueKey(this.constructor, column as string)) { | ||
throw new RedisOrmEntityError("You cannot increment unique key"); | ||
if (serviceInstance.isUniqueKey(this.constructor, column as string)) { | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) You cannot increment unique key`); | ||
} | ||
if (!metaInstance.isNumberColumn(this.constructor, column as string)) { | ||
throw new RedisOrmEntityError("Column need to be in the type of Number"); | ||
if (!serviceInstance.isNumberColumn(this.constructor, column as string)) { | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) Column need to be in the type of Number`); | ||
} | ||
if (!Number.isInteger(value)) { | ||
throw new RedisOrmEntityError("Increment value need to be an integer"); | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) Increment value need to be an integer`); | ||
} | ||
@@ -301,2 +303,6 @@ | ||
public toJSON() { | ||
return this.getValues(); | ||
} | ||
// endregion | ||
@@ -322,3 +328,3 @@ | ||
if (!(column in this._values)) { | ||
const schema = metaInstance.getSchema(this.constructor, column); | ||
const schema = serviceInstance.getSchema(this.constructor, column); | ||
this._values[column] = parser.parseStorageStringToValue(schema.type, this._storageStrings[column]); | ||
@@ -331,3 +337,3 @@ } | ||
private _set(column: string, value: any, updateStorageString = false) { | ||
const schema = metaInstance.getSchema(this.constructor, column); | ||
const schema = serviceInstance.getSchema(this.constructor, column); | ||
const storageString = parser.parseValueToStorageString(schema.type, value); | ||
@@ -347,3 +353,3 @@ this._values[column] = parser.parseStorageStringToValue(schema.type, storageString); | ||
if (this.isDeleted && !isRestore) { | ||
throw new RedisOrmEntityError("You cannot update a deleted entity"); | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) You cannot update a deleted entity`); | ||
} | ||
@@ -368,6 +374,6 @@ | ||
// prepare redis lua command parameters | ||
const tableName = metaInstance.getTable(this.constructor); | ||
const indexKeys = metaInstance.getIndexKeys(this.constructor); | ||
const uniqueKeys = metaInstance.getUniqueKeys(this.constructor); | ||
const autoIncrementKey = metaInstance.getAutoIncrementKey(this.constructor); | ||
const tableName = serviceInstance.getTable(this.constructor); | ||
const indexKeys = serviceInstance.getIndexKeys(this.constructor); | ||
const uniqueKeys = serviceInstance.getUniqueKeys(this.constructor); | ||
const autoIncrementKey = serviceInstance.getAutoIncrementKey(this.constructor); | ||
let entityId = ""; | ||
@@ -385,3 +391,3 @@ | ||
const params = [ | ||
metaInstance.getSchemasJson(this.constructor), | ||
serviceInstance.getSchemasJson(this.constructor), | ||
entityId, | ||
@@ -398,3 +404,3 @@ this.isNew, | ||
const redis = await metaInstance.getRedis(this.constructor); | ||
const redis = await serviceInstance.getRedis(this.constructor); | ||
const commandResult = await (redis as any).commandAtomicSave([], params); | ||
@@ -405,6 +411,6 @@ const saveResult = JSON.parse(commandResult) as ISaveResult; | ||
if (saveResult.error === "Invalid Schemas") { | ||
const schemaErrors = await metaInstance.compareSchemas(this.constructor); | ||
throw new RedisOrmSchemaError(saveResult.error, schemaErrors); | ||
const schemaErrors = await serviceInstance.compareSchemas(this.constructor); | ||
throw new RedisOrmSchemaError(`(${this.constructor.name}) ${saveResult.error}`, schemaErrors); | ||
} else { | ||
throw new RedisOrmEntityError(saveResult.error); | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) ${saveResult.error}`); | ||
} | ||
@@ -433,4 +439,17 @@ } | ||
// update the flags | ||
const isNew = this._isNew; | ||
this._isNew = false; | ||
// fire event | ||
if (isRestore) { | ||
eventEmitters.getEventEmitter(this.constructor as any).emit("restore", this); | ||
} else { | ||
if (isNew) { | ||
eventEmitters.getEventEmitter(this.constructor as any).emit("create", this); | ||
} else { | ||
eventEmitters.getEventEmitter(this.constructor as any).emit("update", this); | ||
} | ||
} | ||
return this; | ||
@@ -442,9 +461,9 @@ } | ||
if (this.isNew) { | ||
throw new RedisOrmEntityError("You cannot delete a new entity"); | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) You cannot delete a new entity`); | ||
} | ||
// if it's soft delete | ||
const entityMeta = metaInstance.getEntityMeta(this.constructor); | ||
const entityMeta = serviceInstance.getEntityMeta(this.constructor); | ||
if (!forceDelete && this.isDeleted) { | ||
throw new RedisOrmEntityError("You cannot delete a deleted entity"); | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) You cannot delete a deleted entity`); | ||
} | ||
@@ -460,9 +479,9 @@ | ||
const entityId = this.getEntityId(); | ||
const tableName = metaInstance.getTable(this.constructor); | ||
const indexKeys = metaInstance.getIndexKeys(this.constructor); | ||
const uniqueKeys = metaInstance.getUniqueKeys(this.constructor); | ||
const tableName = serviceInstance.getTable(this.constructor); | ||
const indexKeys = serviceInstance.getIndexKeys(this.constructor); | ||
const uniqueKeys = serviceInstance.getUniqueKeys(this.constructor); | ||
const keys: [] = []; | ||
const params = [ | ||
metaInstance.getSchemasJson(this.constructor), | ||
serviceInstance.getSchemasJson(this.constructor), | ||
entityId, | ||
@@ -476,3 +495,3 @@ !forceDelete, | ||
const redis = await metaInstance.getRedis(this.constructor); | ||
const redis = await serviceInstance.getRedis(this.constructor); | ||
const commandResult = await (redis as any).commandAtomicDelete(keys, params); | ||
@@ -483,3 +502,3 @@ const saveResult = JSON.parse(commandResult) as ISaveResult; | ||
if (saveResult.error) { | ||
throw new Error(saveResult.error); | ||
throw new RedisOrmEntityError(`(${this.constructor.name}) ${saveResult.error}`); | ||
} | ||
@@ -490,2 +509,9 @@ | ||
// fire event | ||
if (forceDelete) { | ||
eventEmitters.getEventEmitter(this.constructor as any).emit("forceDelete", this); | ||
} else { | ||
eventEmitters.getEventEmitter(this.constructor as any).emit("delete", this); | ||
} | ||
return this; | ||
@@ -497,3 +523,3 @@ } | ||
const changes: { [key: string]: string } = {}; | ||
const schemas = metaInstance.getSchemas(this.constructor); | ||
const schemas = serviceInstance.getSchemas(this.constructor); | ||
for (const [column, schema] of Object.entries(schemas)) { | ||
@@ -500,0 +526,0 @@ // if no such value before, it must be a changes |
@@ -6,8 +6,13 @@ import * as fs from "fs"; | ||
public getConfigFile(): string | null { | ||
const name = process.env.node_env || "default"; | ||
const configFiles = [`redisorm.default.json`]; | ||
if (process.env.node_env) { | ||
const name = process.env.NODE_ENV || "default"; | ||
let configFiles = [`redisorm.default.json`]; | ||
if (process.env.NODE_ENV) { | ||
configFiles.push(`redisorm.${name}.json`); | ||
} | ||
if (process.env.REDISORM_CONFIG_PATH) { | ||
configFiles = [process.env.REDISORM_CONFIG_PATH]; | ||
} | ||
for (const configFile of configFiles) { | ||
@@ -14,0 +19,0 @@ try { |
import "reflect-metadata"; | ||
import {RedisOrmDecoratorError} from ".."; | ||
import { metaInstance} from "../metaInstance"; | ||
import {serviceInstance} from "../serviceInstance"; | ||
import {ISchema, ISchemaBase} from "../types"; | ||
@@ -8,10 +8,10 @@ | ||
// only one schema | ||
const autoIncrementKey = metaInstance.getAutoIncrementKey(target); | ||
const autoIncrementKey = serviceInstance.getAutoIncrementKey(target); | ||
if (autoIncrementKey) { | ||
if (schema.autoIncrement) { | ||
throw new RedisOrmDecoratorError(`AutoIncrement already exist for column: ${autoIncrementKey}`); | ||
throw new RedisOrmDecoratorError(`(${(target as any).name}) AutoIncrement already exist for column: ${autoIncrementKey}`); | ||
} | ||
if (schema.primary) { | ||
throw new RedisOrmDecoratorError(`AutoIncrement can only work with one primary key`); | ||
throw new RedisOrmDecoratorError(`(${(target as any).name}) AutoIncrement can only work with one primary key`); | ||
} | ||
@@ -21,3 +21,3 @@ } | ||
if (schema.autoIncrement && !schema.primary) { | ||
throw new RedisOrmDecoratorError(`AutoIncrement needs pair up with primary key`); | ||
throw new RedisOrmDecoratorError(`(${(target as any).name}) AutoIncrement needs pair up with primary key`); | ||
} | ||
@@ -27,3 +27,3 @@ | ||
if (schema.type !== String && schema.type !== Number) { | ||
throw new RedisOrmDecoratorError(`Primary key only supports String or Number`); | ||
throw new RedisOrmDecoratorError(`(${(target as any).name}) Primary key only supports String or Number`); | ||
} | ||
@@ -34,3 +34,3 @@ } | ||
if (schema.type !== Number && schema.type !== Boolean && schema.type !== Date) { | ||
throw new RedisOrmDecoratorError(`Index only supports Number, Boolean or Date`); | ||
throw new RedisOrmDecoratorError(`(${(target as any).name}) Index only supports Number, Boolean or Date`); | ||
} | ||
@@ -41,3 +41,3 @@ } | ||
if (schema.type !== String && schema.type !== Number) { | ||
throw new RedisOrmDecoratorError(`Unique only supports String or Number`); | ||
throw new RedisOrmDecoratorError(`(${(target as any).name}) Unique only supports String or Number`); | ||
} | ||
@@ -64,3 +64,3 @@ } | ||
// everything ok , add the schema | ||
metaInstance.addColumn(target.constructor, propertyKey, newSchema); | ||
serviceInstance.addColumn(target.constructor, propertyKey, newSchema); | ||
@@ -67,0 +67,0 @@ // define getter / setter |
import {RedisOrmDecoratorError} from ".."; | ||
import {metaInstance} from "../metaInstance"; | ||
import {serviceInstance} from "../serviceInstance"; | ||
import {IEntityBaseMeta, IEntityMeta, ISchema} from "../types"; | ||
@@ -15,3 +15,3 @@ | ||
newEntityMeta = Object.assign(newEntityMeta, entityMeta); | ||
metaInstance.addEntity(target, newEntityMeta); | ||
serviceInstance.addEntity(target, newEntityMeta); | ||
@@ -26,10 +26,10 @@ // add createdAt, updatedAt and deletedAt | ||
}; | ||
metaInstance.addColumn(target, "createdAt", schema); | ||
metaInstance.addColumn(target, "updatedAt", {...schema, index: newEntityMeta.indexUpdatedAt}); | ||
metaInstance.addColumn(target, "deletedAt", schema); | ||
serviceInstance.addColumn(target, "createdAt", schema); | ||
serviceInstance.addColumn(target, "updatedAt", {...schema, index: newEntityMeta.indexUpdatedAt}); | ||
serviceInstance.addColumn(target, "deletedAt", schema); | ||
// validate from entity | ||
const primaryKeys = metaInstance.getPrimaryKeys(target); | ||
const primaryKeys = serviceInstance.getPrimaryKeys(target); | ||
if (primaryKeys.length === 0) { | ||
throw new RedisOrmDecoratorError(`No primary keys exist for this entity`); | ||
throw new RedisOrmDecoratorError(`(${(target as any).name}) No primary keys exist for this entity`); | ||
} | ||
@@ -36,0 +36,0 @@ |
import fs from "fs"; | ||
import * as readline from "readline"; | ||
import {BaseEntity} from "./BaseEntity"; | ||
import {metaInstance, schemaJsonReplacer} from "./metaInstance"; | ||
import {schemaJsonReplacer, serviceInstance} from "./serviceInstance"; | ||
@@ -15,4 +15,4 @@ class EntityExporter { | ||
class: (entityType as any).name, | ||
table: metaInstance.getTable(entityType), | ||
schemas: metaInstance.getSchemasJson(entityType), | ||
table: serviceInstance.getTable(entityType), | ||
schemas: serviceInstance.getSchemasJson(entityType), | ||
total: entities.length, | ||
@@ -130,3 +130,3 @@ }; | ||
const className = (entityType as any).name; | ||
const clientSchemas = metaInstance.getSchemasJson(entityType); | ||
const clientSchemas = serviceInstance.getSchemasJson(entityType); | ||
if (meta.class !== className) { | ||
@@ -133,0 +133,0 @@ const err = new Error(); |
import {BaseEntity} from "./BaseEntity"; | ||
import {RedisOrmQueryError} from "./errors/RedisOrmQueryError"; | ||
import {metaInstance} from "./metaInstance"; | ||
import {parser} from "./parser"; | ||
import {serviceInstance} from "./serviceInstance"; | ||
import { | ||
@@ -34,15 +35,15 @@ IAggregateObject, | ||
public async find(idObject: IIdObject<InstanceType<T>>): Promise<InstanceType<T> | undefined> { | ||
const redis = await this._getRedis(); | ||
const entityId = metaInstance.convertAsEntityId(this._entityType, idObject); | ||
const primaryKeys = metaInstance.getPrimaryKeys(this._entityType); | ||
const entityId = serviceInstance.convertAsEntityId(this._entityType, idObject); | ||
const primaryKeys = serviceInstance.getPrimaryKeys(this._entityType); | ||
// if we have a valid entity id | ||
if (entityId) { | ||
const entityStorageKey = metaInstance.getEntityStorageKey(this._entityType, entityId); | ||
const entityStorageKey = serviceInstance.getEntityStorageKey(this._entityType, entityId); | ||
if (!entityStorageKey) { | ||
throw new RedisOrmQueryError(`Invalid id ${JSON.stringify(idObject)}`); | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) Invalid id ${JSON.stringify(idObject)}`); | ||
} | ||
// we need to make sure if have all the keys exist in the storage strings | ||
const redis = await this._getRedis(); | ||
const storageStrings = await redis.hgetall(entityStorageKey); | ||
@@ -68,4 +69,4 @@ if (primaryKeys.every(primaryKey => primaryKey in storageStrings)) { | ||
public async findUnique(column: IArgColumn<T>, value: IUniqueValueType): Promise<InstanceType<T> | undefined> { | ||
if (!metaInstance.isUniqueKey(this._entityType, column as string)) { | ||
throw new RedisOrmQueryError(`Invalid unique column: ${column}`); | ||
if (!serviceInstance.isUniqueKey(this._entityType, column as string)) { | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) Invalid unique column: ${column}`); | ||
} | ||
@@ -75,3 +76,3 @@ | ||
const id = await redis.hget( | ||
metaInstance.getUniqueStorageKey(this._entityType, column as string), | ||
serviceInstance.getUniqueStorageKey(this._entityType, column as string), | ||
value.toString(), | ||
@@ -114,9 +115,9 @@ ); | ||
const columnString = column as string; | ||
if (metaInstance.isIndexKey(this._entityType, columnString)) { | ||
if (serviceInstance.isIndexKey(this._entityType, columnString)) { | ||
if (this._onlyDeleted) { | ||
throw new RedisOrmQueryError(`You cannot apply extra where indexing clause for only deleted query`); | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) You cannot apply extra where indexing clause for only deleted query`); | ||
} | ||
if (!metaInstance.isIndexKey(this._entityType, columnString)) { | ||
throw new RedisOrmQueryError(`Invalid index column: ${column}`); | ||
if (!serviceInstance.isIndexKey(this._entityType, columnString)) { | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) Invalid index column: ${column}`); | ||
} | ||
@@ -126,3 +127,3 @@ | ||
if (value !== "-inf" && value !== "+inf") { | ||
const schema = metaInstance.getSchema(this._entityType, columnString); | ||
const schema = serviceInstance.getSchema(this._entityType, columnString); | ||
value = parser.parseValueToStorageString(schema.type, value); | ||
@@ -159,3 +160,3 @@ } | ||
default: | ||
throw new RedisOrmQueryError(`Invalid operator (${operator}) for index column: ${column}`); | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) Invalid operator (${operator}) for index column: ${column}`); | ||
} | ||
@@ -165,9 +166,9 @@ | ||
} else if (metaInstance.isSearchableColumn(this._entityType, columnString)) { | ||
} else if (serviceInstance.isSearchableColumn(this._entityType, columnString)) { | ||
if (!["=", "!=", "like"].includes(operator)) { | ||
throw new RedisOrmQueryError(`Invalid operator (${operator}) for non index column: ${column}`); | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) Invalid operator (${operator}) for non index column: ${column}`); | ||
} | ||
// convert value into string value | ||
const schema = metaInstance.getSchema(this._entityType, columnString); | ||
const schema = serviceInstance.getSchema(this._entityType, columnString); | ||
value = parser.parseValueToStorageString(schema.type, value); | ||
@@ -177,3 +178,3 @@ this._whereSearches[columnString] = {operator: operator as IStringOperator, value}; | ||
} else { | ||
throw new RedisOrmQueryError(`Invalid search column: ${column}`); | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) Invalid search column: ${column}`); | ||
@@ -187,3 +188,3 @@ } | ||
if (Object.keys(this._whereIndexes).length > 0) { | ||
throw new RedisOrmQueryError(`You cannot apply extra where indexing clause for only deleted query`); | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) You cannot apply extra where indexing clause for only deleted query`); | ||
} | ||
@@ -199,8 +200,7 @@ | ||
if (this._sortBy !== null) { | ||
throw new RedisOrmQueryError("You can only order by 1 column"); | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) You can only order by 1 column`); | ||
} | ||
if (!metaInstance.isSortableColumn(this._entityType, column as string)) { | ||
throw new RedisOrmQueryError( | ||
`Not sortable Column: ${column}. You can only sort column type of Number, Boolean or Date`); | ||
if (!serviceInstance.isSortableColumn(this._entityType, column as string)) { | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) Not sortable Column: ${column}. You can only sort column type of Number, Boolean or Date`); | ||
} | ||
@@ -230,7 +230,7 @@ | ||
if (this._groupByColumn !== null) { | ||
throw new RedisOrmQueryError(`You can only group by 1 column`); | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) You can only group by 1 column`); | ||
} | ||
if (!metaInstance.isValidColumn(this._entityType, column as string)) { | ||
throw new RedisOrmQueryError(`Invalid column: ${column}`); | ||
if (!serviceInstance.isValidColumn(this._entityType, column as string)) { | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) Invalid column: ${column}`); | ||
} | ||
@@ -272,8 +272,8 @@ | ||
Promise<number> { | ||
if (!metaInstance.isIndexKey(this._entityType, column as string)) { | ||
throw new RedisOrmQueryError(`Invalid index column: ${column}`); | ||
if (!serviceInstance.isIndexKey(this._entityType, column as string)) { | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) Invalid index column: ${column}`); | ||
} | ||
const indexStorageKey = metaInstance.getIndexStorageKey(this._entityType, column as string); | ||
const entityId = metaInstance.convertAsEntityId(this._entityType, idObject); | ||
const indexStorageKey = serviceInstance.getIndexStorageKey(this._entityType, column as string); | ||
const entityId = serviceInstance.convertAsEntityId(this._entityType, idObject); | ||
@@ -323,3 +323,3 @@ if (entityId) { | ||
this._limit, | ||
metaInstance.getTable(this._entityType), | ||
serviceInstance.getTable(this._entityType), | ||
"", // aggregate | ||
@@ -362,3 +362,3 @@ "", // aggregate column | ||
// redis params | ||
const indexStorageKey = metaInstance.getIndexStorageKey(this._entityType, column); | ||
const indexStorageKey = serviceInstance.getIndexStorageKey(this._entityType, column); | ||
const extraParams = ["LIMIT", this._offset.toString(), this._limit.toString()]; | ||
@@ -381,4 +381,4 @@ | ||
if (aggregate !== "count") { | ||
if (!metaInstance.isNumberColumn(this._entityType, aggregateColumn)) { | ||
throw new RedisOrmQueryError(`Column: ${aggregateColumn} is not in the type of number`); | ||
if (!serviceInstance.isNumberColumn(this._entityType, aggregateColumn)) { | ||
throw new RedisOrmQueryError(`(${this._entityType.name}) Column: ${aggregateColumn} is not in the type of number`); | ||
} | ||
@@ -407,3 +407,3 @@ } | ||
this._offset, // not used | ||
metaInstance.getTable(this._entityType), | ||
serviceInstance.getTable(this._entityType), | ||
aggregate, | ||
@@ -452,5 +452,5 @@ aggregateColumn, | ||
if (max === "+inf" && min === "-inf") { | ||
count = await redis.zcard(metaInstance.getIndexStorageKey(this._entityType, column)); | ||
count = await redis.zcard(serviceInstance.getIndexStorageKey(this._entityType, column)); | ||
} else { | ||
count = await redis.zcount(metaInstance.getIndexStorageKey(this._entityType, column), min, max); | ||
count = await redis.zcount(serviceInstance.getIndexStorageKey(this._entityType, column), min, max); | ||
} | ||
@@ -462,3 +462,3 @@ | ||
private async _getRedis() { | ||
return await metaInstance.getRedis(this._entityType); | ||
return await serviceInstance.getRedis(this._entityType); | ||
} | ||
@@ -465,0 +465,0 @@ |
@@ -61,1 +61,13 @@ import * as IORedis from "ioredis"; | ||
export type IIdObject<T> = IArgValues<T> | number | string; | ||
// event | ||
export type IEventType = "create" | "update" | "delete" | "forceDelete" | "restore"; | ||
export interface IEvent<T> { | ||
on(type: IEventType, callback: (entity: T) => void): any; | ||
addListener(type: IEventType, callback: (entity: T) => void): any; | ||
removeListener(type: IEventType, callback: (entity: T) => void): any; | ||
once(type: IEventType, callback: (entity: T) => void): any; | ||
off(type: IEventType, callback: (entity: T) => void): any; | ||
emit(type: IEventType, entity: T): any; | ||
} |
@@ -14,3 +14,3 @@ import { assert, expect } from "chai"; | ||
} catch (err) { | ||
assert.equal(err.message, "AutoIncrement needs pair up with primary key"); | ||
assert.equal(err.message, "(TestingDecorator1) AutoIncrement needs pair up with primary key"); | ||
} | ||
@@ -31,3 +31,3 @@ }); | ||
} catch (err) { | ||
assert.equal(err.message, "AutoIncrement already exist for column: id1"); | ||
assert.equal(err.message, "(TestingDecorator2) AutoIncrement already exist for column: id1"); | ||
} | ||
@@ -48,3 +48,3 @@ }); | ||
} catch (err) { | ||
assert.equal(err.message, "AutoIncrement can only work with one primary key"); | ||
assert.equal(err.message, "(TestingDecorator3) AutoIncrement can only work with one primary key"); | ||
} | ||
@@ -62,3 +62,3 @@ }); | ||
} catch (err) { | ||
assert.equal(err.message, "Primary key only supports String or Number"); | ||
assert.equal(err.message, "(TestingDecorator4) Primary key only supports String or Number"); | ||
} | ||
@@ -79,3 +79,3 @@ }); | ||
} catch (err) { | ||
assert.equal(err.message, "Index only supports Number, Boolean or Date"); | ||
assert.equal(err.message, "(TestingDecorator5) Index only supports Number, Boolean or Date"); | ||
} | ||
@@ -96,3 +96,3 @@ }); | ||
} catch (err) { | ||
assert.equal(err.message, "Unique only supports String or Number"); | ||
assert.equal(err.message, "(TestingDecorator6) Unique only supports String or Number"); | ||
} | ||
@@ -110,5 +110,5 @@ }); | ||
} catch (err) { | ||
assert.equal(err.message, "No primary keys exist for this entity"); | ||
assert.equal(err.message, "(TestingDecorator7) No primary keys exist for this entity"); | ||
} | ||
}); | ||
}); |
import {assert, expect } from "chai"; | ||
import {BaseEntity, Column, Entity} from "../src/"; | ||
import {metaInstance} from "../src/metaInstance"; | ||
import {serviceInstance} from "../src/serviceInstance"; | ||
@@ -51,7 +51,7 @@ type NullableString = string | null; | ||
it("meta", async () => { | ||
assert.equal(metaInstance.getTable(TestingGeneral), "testing_general"); | ||
assert.deepEqual(metaInstance.getPrimaryKeys(TestingGeneral), ["id"]); | ||
assert.equal(metaInstance.getAutoIncrementKey(TestingGeneral), "id"); | ||
assert.includeMembers(metaInstance.getIndexKeys(TestingGeneral), ["uniqueNumber", "date", "boolean"]); | ||
assert.deepEqual(metaInstance.getUniqueKeys(TestingGeneral), ["uniqueNumber"]); | ||
assert.equal(serviceInstance.getTable(TestingGeneral), "testing_general"); | ||
assert.deepEqual(serviceInstance.getPrimaryKeys(TestingGeneral), ["id"]); | ||
assert.equal(serviceInstance.getAutoIncrementKey(TestingGeneral), "id"); | ||
assert.includeMembers(serviceInstance.getIndexKeys(TestingGeneral), ["uniqueNumber", "date", "boolean"]); | ||
assert.deepEqual(serviceInstance.getUniqueKeys(TestingGeneral), ["uniqueNumber"]); | ||
}); | ||
@@ -340,3 +340,3 @@ }); | ||
} catch (err) { | ||
assert.equal(err.message, `Entity not exist or deleted. Entity Id: ${entity.getEntityId()}`); | ||
assert.equal(err.message, `(${TestingGeneral.name}) Entity not exist or deleted. Entity Id: ${entity.getEntityId()}`); | ||
} | ||
@@ -349,3 +349,3 @@ | ||
} catch (err) { | ||
assert.equal(err.message, `Entity already deleted. Entity Id: ${entity.getEntityId()}`); | ||
assert.equal(err.message, `(${TestingGeneral.name}) Entity already deleted. Entity Id: ${entity.getEntityId()}`); | ||
} | ||
@@ -363,3 +363,3 @@ | ||
} catch (err) { | ||
assert.equal(err.message, `Entity not exist. Entity Id: ${entity.getEntityId()}`); | ||
assert.equal(err.message, `(${TestingGeneral.name}) Entity not exist. Entity Id: ${entity.getEntityId()}`); | ||
} | ||
@@ -475,2 +475,56 @@ }); | ||
describe("Events", () => { | ||
it("create, update, delete, restore, forceDelete", async () => { | ||
const id = 10001; | ||
const entity = TestingGeneral.create({id, uniqueNumber: id}); | ||
const events = TestingGeneral.getEventEmitter(); | ||
let createdEntity: any = null; | ||
let updatedEntity: any = null; | ||
let deletedEntity: any = null; | ||
let forcedDeletedEntity: any = null; | ||
let restoredEntity: any = null; | ||
// create | ||
events.once("create", (thisEntity) => { | ||
createdEntity = thisEntity; | ||
}); | ||
await entity.save(); | ||
assert.isNotNull(createdEntity); | ||
assert.equal(entity.id, (createdEntity as TestingGeneral).id); | ||
// create | ||
entity.string2 = "happy"; | ||
events.once("update", (thisEntity) => { | ||
updatedEntity = thisEntity; | ||
}); | ||
await entity.save(); | ||
assert.isNotNull(updatedEntity); | ||
assert.equal(entity.string2, (updatedEntity as TestingGeneral).string2); | ||
// delete | ||
events.once("delete", (thisEntity) => { | ||
deletedEntity = thisEntity; | ||
}); | ||
await entity.delete(); | ||
assert.isNotNull(deletedEntity); | ||
assert.equal(entity.isDeleted, (deletedEntity as TestingGeneral).isDeleted); | ||
// restore | ||
events.once("restore", (thisEntity) => { | ||
restoredEntity = thisEntity; | ||
}); | ||
await entity.restore(); | ||
assert.isDefined(restoredEntity); | ||
assert.equal(entity.isDeleted, (restoredEntity as TestingGeneral).isDeleted); | ||
// forceDelete | ||
events.once("forceDelete", (thisEntity) => { | ||
forcedDeletedEntity = thisEntity; | ||
}); | ||
await entity.forceDelete(); | ||
assert.isNotNull(forcedDeletedEntity); | ||
assert.equal(entity.isDeleted, (forcedDeletedEntity as TestingGeneral).isDeleted); | ||
}); | ||
}); | ||
describe("Clean up", () => { | ||
@@ -477,0 +531,0 @@ it("truncate", async () => { |
@@ -150,3 +150,3 @@ import { assert, expect } from "chai"; | ||
} catch (err) { | ||
assert.equal(err.message, "Resync can only apply to same primary keys. The remote primary key: id is not the same or not exist in current schemas"); | ||
assert.equal(err.message, "(TestingSchema3) Resync can only apply to same primary keys. The remote primary key: id is not the same or not exist in current schemas"); | ||
} | ||
@@ -197,3 +197,3 @@ }); | ||
} catch (err) { | ||
assert.equal(err.message, `Unique key: unique1 with value: 0 already exist on entity id: 1. Current entity id: ${duplicatedEntity.id}`); | ||
assert.equal(err.message, `(${TestingSchema1.name}) Unique key: unique1 with value: 0 already exist on entity id: 1. Current entity id: ${duplicatedEntity.id}`); | ||
} | ||
@@ -200,0 +200,0 @@ |
import {assert, expect } from "chai"; | ||
import {BaseEntity, Column, Entity} from "../src/"; | ||
import {metaInstance} from "../src/metaInstance"; | ||
import {serviceInstance} from "../src/serviceInstance"; | ||
@@ -44,3 +44,3 @@ type IObject = { | ||
beforeEach(async () => { | ||
const redis = await metaInstance.getRedis(TestingSpeed); | ||
const redis = await serviceInstance.getRedis(TestingSpeed); | ||
const info = await redis.info("all"); | ||
@@ -58,3 +58,3 @@ const matches1 = info.match(/used_memory:(.*)/); | ||
afterEach(async () => { | ||
const redis = await metaInstance.getRedis(TestingSpeed); | ||
const redis = await serviceInstance.getRedis(TestingSpeed); | ||
const info = await redis.info("all"); | ||
@@ -61,0 +61,0 @@ |
@@ -15,2 +15,3 @@ { | ||
"object-literal-sort-keys": false, | ||
"max-line-length": [200], | ||
"no-bitwise": false, | ||
@@ -17,0 +18,0 @@ "variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore"] |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
318623
7
80
6115
256
3
8
+ Added@types/ioredis@^4.0.18
+ Added@types/ioredis@4.28.10(transitive)
+ Added@types/node@22.9.0(transitive)
+ Addedundici-types@6.19.8(transitive)