Comparing version 0.1.15 to 0.1.16
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.InputTypes = void 0; | ||
class InputTypes { | ||
} | ||
var InputTypes = /** @class */ (function () { | ||
function InputTypes() { | ||
} | ||
InputTypes.number = 'number'; | ||
InputTypes.date = 'date'; | ||
InputTypes.checkbox = 'checkbox'; | ||
InputTypes.password = 'password'; | ||
InputTypes.email = 'email'; | ||
InputTypes.tel = 'tel'; | ||
InputTypes.time = "time"; | ||
return InputTypes; | ||
}()); | ||
exports.InputTypes = InputTypes; | ||
InputTypes.number = 'number'; | ||
InputTypes.date = 'date'; | ||
InputTypes.checkbox = 'checkbox'; | ||
InputTypes.password = 'password'; | ||
InputTypes.email = 'email'; | ||
InputTypes.tel = 'tel'; | ||
InputTypes.time = "time"; | ||
//# sourceMappingURL=inputTypes.js.map |
{ | ||
"name": "remult", | ||
"version": "0.1.15", | ||
"version": "0.1.16", | ||
"description": "remult core lib", | ||
@@ -5,0 +5,0 @@ "homepage": "https://remult.github.io/", |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const tslib_1 = require("tslib"); | ||
var tslib_1 = require("tslib"); | ||
tslib_1.__exportStar(require("./postgres-data-provider"), exports); | ||
//# sourceMappingURL=index.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.preparePostgresQueueStorage = exports.PostgresSchemaBuilder = exports.verifyStructureOfAllEntities = exports.PostgresDataProvider = void 0; | ||
const tslib_1 = require("tslib"); | ||
const context_1 = require("../src/context"); | ||
const expressBridge_1 = require("../server/expressBridge"); | ||
const valueConverters_1 = require("../valueConverters"); | ||
const sql_database_1 = require("../src/data-providers/sql-database"); | ||
class PostgresDataProvider { | ||
constructor(pool) { | ||
var tslib_1 = require("tslib"); | ||
var context_1 = require("../src/context"); | ||
var expressBridge_1 = require("../server/expressBridge"); | ||
var valueConverters_1 = require("../valueConverters"); | ||
var sql_database_1 = require("../src/data-providers/sql-database"); | ||
var PostgresDataProvider = /** @class */ (function () { | ||
function PostgresDataProvider(pool) { | ||
this.pool = pool; | ||
} | ||
entityIsUsedForTheFirstTime(entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
PostgresDataProvider.prototype.entityIsUsedForTheFirstTime = function (entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/]; | ||
}); | ||
}); | ||
} | ||
getLimitSqlSyntax(limit, offset) { | ||
}; | ||
PostgresDataProvider.prototype.getLimitSqlSyntax = function (limit, offset) { | ||
return ' limit ' + limit + ' offset ' + offset; | ||
} | ||
createCommand() { | ||
}; | ||
PostgresDataProvider.prototype.createCommand = function () { | ||
return new PostgresBridgeToSQLCommand(this.pool); | ||
} | ||
insertAndReturnAutoIncrementId(command, insertStatementString, entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let r = yield command.execute(insertStatementString); | ||
r = yield this.createCommand().execute("SELECT currval(pg_get_serial_sequence('" + (yield entity.getDbName()) + "','" + (yield entity.idMetadata.field.getDbName()) + "'));"); | ||
return +r.rows[0].currval; | ||
}; | ||
PostgresDataProvider.prototype.insertAndReturnAutoIncrementId = function (command, insertStatementString, entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var r, _a, _b, _c, _d; | ||
return tslib_1.__generator(this, function (_e) { | ||
switch (_e.label) { | ||
case 0: return [4 /*yield*/, command.execute(insertStatementString)]; | ||
case 1: | ||
r = _e.sent(); | ||
_b = (_a = this.createCommand()).execute; | ||
_c = "SELECT currval(pg_get_serial_sequence('"; | ||
return [4 /*yield*/, entity.getDbName()]; | ||
case 2: | ||
_d = _c + (_e.sent()) + "','"; | ||
return [4 /*yield*/, entity.idMetadata.field.getDbName()]; | ||
case 3: return [4 /*yield*/, _b.apply(_a, [_d + (_e.sent()) + "'));"])]; | ||
case 4: | ||
r = _e.sent(); | ||
return [2 /*return*/, +r.rows[0].currval]; | ||
} | ||
}); | ||
}); | ||
} | ||
transaction(action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let client = yield this.pool.connect(); | ||
try { | ||
yield client.query('BEGIN'); | ||
yield action({ | ||
createCommand: () => new PostgresBridgeToSQLCommand(client), | ||
entityIsUsedForTheFirstTime: this.entityIsUsedForTheFirstTime, | ||
transaction: () => { throw "nested transactions not allowed"; }, | ||
insertAndReturnAutoIncrementId: this.insertAndReturnAutoIncrementId, | ||
getLimitSqlSyntax: this.getLimitSqlSyntax | ||
}); | ||
yield client.query('COMMIT'); | ||
} | ||
catch (err) { | ||
yield client.query('ROLLBACK'); | ||
throw err; | ||
} | ||
finally { | ||
yield client.release(); | ||
} | ||
}; | ||
PostgresDataProvider.prototype.transaction = function (action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var client, err_1; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.pool.connect()]; | ||
case 1: | ||
client = _a.sent(); | ||
_a.label = 2; | ||
case 2: | ||
_a.trys.push([2, 6, 8, 10]); | ||
return [4 /*yield*/, client.query('BEGIN')]; | ||
case 3: | ||
_a.sent(); | ||
return [4 /*yield*/, action({ | ||
createCommand: function () { return new PostgresBridgeToSQLCommand(client); }, | ||
entityIsUsedForTheFirstTime: this.entityIsUsedForTheFirstTime, | ||
transaction: function () { throw "nested transactions not allowed"; }, | ||
insertAndReturnAutoIncrementId: this.insertAndReturnAutoIncrementId, | ||
getLimitSqlSyntax: this.getLimitSqlSyntax | ||
})]; | ||
case 4: | ||
_a.sent(); | ||
return [4 /*yield*/, client.query('COMMIT')]; | ||
case 5: | ||
_a.sent(); | ||
return [3 /*break*/, 10]; | ||
case 6: | ||
err_1 = _a.sent(); | ||
return [4 /*yield*/, client.query('ROLLBACK')]; | ||
case 7: | ||
_a.sent(); | ||
throw err_1; | ||
case 8: return [4 /*yield*/, client.release()]; | ||
case 9: | ||
_a.sent(); | ||
return [7 /*endfinally*/]; | ||
case 10: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return PostgresDataProvider; | ||
}()); | ||
exports.PostgresDataProvider = PostgresDataProvider; | ||
class PostgresBridgeToSQLCommand { | ||
constructor(source) { | ||
var PostgresBridgeToSQLCommand = /** @class */ (function () { | ||
function PostgresBridgeToSQLCommand(source) { | ||
this.source = source; | ||
this.values = []; | ||
} | ||
addParameterAndReturnSqlToken(val) { | ||
PostgresBridgeToSQLCommand.prototype.addParameterAndReturnSqlToken = function (val) { | ||
this.values.push(val); | ||
return '$' + this.values.length; | ||
} | ||
execute(sql) { | ||
return this.source.query(sql, this.values).then(r => new PostgresBridgeToSQLQueryResult(r)); | ||
} | ||
} | ||
class PostgresBridgeToSQLQueryResult { | ||
constructor(r) { | ||
}; | ||
PostgresBridgeToSQLCommand.prototype.execute = function (sql) { | ||
return this.source.query(sql, this.values).then(function (r) { return new PostgresBridgeToSQLQueryResult(r); }); | ||
}; | ||
return PostgresBridgeToSQLCommand; | ||
}()); | ||
var PostgresBridgeToSQLQueryResult = /** @class */ (function () { | ||
function PostgresBridgeToSQLQueryResult(r) { | ||
this.r = r; | ||
this.rows = r.rows; | ||
} | ||
getColumnKeyInResultForIndexInSelect(index) { | ||
PostgresBridgeToSQLQueryResult.prototype.getColumnKeyInResultForIndexInSelect = function (index) { | ||
return this.r.fields[index].name; | ||
} | ||
} | ||
}; | ||
return PostgresBridgeToSQLQueryResult; | ||
}()); | ||
function verifyStructureOfAllEntities(db) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield new PostgresSchemaBuilder(db).verifyStructureOfAllEntities(); | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, new PostgresSchemaBuilder(db).verifyStructureOfAllEntities()]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
}); | ||
} | ||
exports.verifyStructureOfAllEntities = verifyStructureOfAllEntities; | ||
class PostgresSchemaBuilder { | ||
constructor(pool, schema) { | ||
var PostgresSchemaBuilder = /** @class */ (function () { | ||
function PostgresSchemaBuilder(pool, schema) { | ||
this.pool = pool; | ||
@@ -91,49 +136,148 @@ this.additionalWhere = ''; | ||
} | ||
verifyStructureOfAllEntities() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
console.log("start verify structure"); | ||
let context = new context_1.Context(); | ||
for (const entity of context_1.allEntities) { | ||
let metadata = context.for(entity).metadata; | ||
try { | ||
if ((yield metadata.getDbName()).toLowerCase().indexOf('from ') < 0) { | ||
yield this.createIfNotExist(metadata); | ||
yield this.verifyAllColumns(metadata); | ||
} | ||
PostgresSchemaBuilder.prototype.verifyStructureOfAllEntities = function () { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var context, allEntities_1, allEntities_1_1, entity, metadata, err_2, _a, _b, _c, e_1_1; | ||
var e_1, _d; | ||
return tslib_1.__generator(this, function (_e) { | ||
switch (_e.label) { | ||
case 0: | ||
console.log("start verify structure"); | ||
context = new context_1.Context(); | ||
_e.label = 1; | ||
case 1: | ||
_e.trys.push([1, 12, 13, 14]); | ||
allEntities_1 = tslib_1.__values(context_1.allEntities), allEntities_1_1 = allEntities_1.next(); | ||
_e.label = 2; | ||
case 2: | ||
if (!!allEntities_1_1.done) return [3 /*break*/, 11]; | ||
entity = allEntities_1_1.value; | ||
metadata = context.for(entity).metadata; | ||
_e.label = 3; | ||
case 3: | ||
_e.trys.push([3, 8, , 10]); | ||
return [4 /*yield*/, metadata.getDbName()]; | ||
case 4: | ||
if (!((_e.sent()).toLowerCase().indexOf('from ') < 0)) return [3 /*break*/, 7]; | ||
return [4 /*yield*/, this.createIfNotExist(metadata)]; | ||
case 5: | ||
_e.sent(); | ||
return [4 /*yield*/, this.verifyAllColumns(metadata)]; | ||
case 6: | ||
_e.sent(); | ||
_e.label = 7; | ||
case 7: return [3 /*break*/, 10]; | ||
case 8: | ||
err_2 = _e.sent(); | ||
_b = (_a = console).log; | ||
_c = "failed verify structore of "; | ||
return [4 /*yield*/, metadata.getDbName()]; | ||
case 9: | ||
_b.apply(_a, [_c + (_e.sent()) + " ", err_2]); | ||
return [3 /*break*/, 10]; | ||
case 10: | ||
allEntities_1_1 = allEntities_1.next(); | ||
return [3 /*break*/, 2]; | ||
case 11: return [3 /*break*/, 14]; | ||
case 12: | ||
e_1_1 = _e.sent(); | ||
e_1 = { error: e_1_1 }; | ||
return [3 /*break*/, 14]; | ||
case 13: | ||
try { | ||
if (allEntities_1_1 && !allEntities_1_1.done && (_d = allEntities_1.return)) _d.call(allEntities_1); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
return [7 /*endfinally*/]; | ||
case 14: return [2 /*return*/]; | ||
} | ||
catch (err) { | ||
console.log("failed verify structore of " + (yield metadata.getDbName()) + " ", err); | ||
} | ||
} | ||
}); | ||
}); | ||
} | ||
createIfNotExist(e) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
var c = this.pool.createCommand(); | ||
yield c.execute("select 1 from information_Schema.tables where table_name=" + c.addParameterAndReturnSqlToken((yield e.getDbName()).toLowerCase()) + this.additionalWhere).then((r) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (r.rows.length == 0) { | ||
let result = ''; | ||
for (const x of e.fields) { | ||
if (!(yield sql_database_1.isDbReadonly(x))) { | ||
if (result.length != 0) | ||
result += ','; | ||
result += '\r\n '; | ||
if (x == e.idMetadata.field && e.options.dbAutoIncrementId) | ||
result += (yield x.getDbName()) + ' serial'; | ||
else { | ||
result += this.addColumnSqlSyntax(x, yield x.getDbName()); | ||
if (x == e.idMetadata.field) | ||
result += ' primary key'; | ||
} | ||
} | ||
} | ||
let sql = 'create table ' + (yield e.getDbName()) + ' (' + result + '\r\n)'; | ||
console.log(sql); | ||
yield this.pool.execute(sql); | ||
}; | ||
PostgresSchemaBuilder.prototype.createIfNotExist = function (e) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var c, _a, _b, _c, _d, _e; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_f) { | ||
switch (_f.label) { | ||
case 0: | ||
c = this.pool.createCommand(); | ||
_b = (_a = c).execute; | ||
_c = "select 1 from information_Schema.tables where table_name="; | ||
_e = (_d = c).addParameterAndReturnSqlToken; | ||
return [4 /*yield*/, e.getDbName()]; | ||
case 1: return [4 /*yield*/, _b.apply(_a, [_c + _e.apply(_d, [(_f.sent()).toLowerCase()]) + this.additionalWhere]).then(function (r) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var result, _a, _b, x, _c, _d, _e, _f, e_2_1, sql, _g; | ||
var e_2, _h; | ||
return tslib_1.__generator(this, function (_j) { | ||
switch (_j.label) { | ||
case 0: | ||
if (!(r.rows.length == 0)) return [3 /*break*/, 14]; | ||
result = ''; | ||
_j.label = 1; | ||
case 1: | ||
_j.trys.push([1, 9, 10, 11]); | ||
_a = tslib_1.__values(e.fields), _b = _a.next(); | ||
_j.label = 2; | ||
case 2: | ||
if (!!_b.done) return [3 /*break*/, 8]; | ||
x = _b.value; | ||
return [4 /*yield*/, sql_database_1.isDbReadonly(x)]; | ||
case 3: | ||
if (!!(_j.sent())) return [3 /*break*/, 7]; | ||
if (result.length != 0) | ||
result += ','; | ||
result += '\r\n '; | ||
if (!(x == e.idMetadata.field && e.options.dbAutoIncrementId)) return [3 /*break*/, 5]; | ||
_c = result; | ||
return [4 /*yield*/, x.getDbName()]; | ||
case 4: | ||
result = _c + ((_j.sent()) + ' serial'); | ||
return [3 /*break*/, 7]; | ||
case 5: | ||
_d = result; | ||
_e = this.addColumnSqlSyntax; | ||
_f = [x]; | ||
return [4 /*yield*/, x.getDbName()]; | ||
case 6: | ||
result = _d + _e.apply(this, _f.concat([_j.sent()])); | ||
if (x == e.idMetadata.field) | ||
result += ' primary key'; | ||
_j.label = 7; | ||
case 7: | ||
_b = _a.next(); | ||
return [3 /*break*/, 2]; | ||
case 8: return [3 /*break*/, 11]; | ||
case 9: | ||
e_2_1 = _j.sent(); | ||
e_2 = { error: e_2_1 }; | ||
return [3 /*break*/, 11]; | ||
case 10: | ||
try { | ||
if (_b && !_b.done && (_h = _a.return)) _h.call(_a); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
return [7 /*endfinally*/]; | ||
case 11: | ||
_g = 'create table '; | ||
return [4 /*yield*/, e.getDbName()]; | ||
case 12: | ||
sql = _g + (_j.sent()) + ' (' + result + '\r\n)'; | ||
console.log(sql); | ||
return [4 /*yield*/, this.pool.execute(sql)]; | ||
case 13: | ||
_j.sent(); | ||
_j.label = 14; | ||
case 14: return [2 /*return*/]; | ||
} | ||
}); | ||
}); })]; | ||
case 2: | ||
_f.sent(); | ||
return [2 /*return*/]; | ||
} | ||
})); | ||
}); | ||
}); | ||
} | ||
addColumnSqlSyntax(x, dbName) { | ||
let result = dbName; | ||
}; | ||
PostgresSchemaBuilder.prototype.addColumnSqlSyntax = function (x, dbName) { | ||
var result = dbName; | ||
if (x.valueConverter.fieldTypeInDb) { | ||
@@ -164,55 +308,141 @@ if (x.valueType == Number && !x.valueConverter.fieldTypeInDb) | ||
return result; | ||
} | ||
addColumnIfNotExist(e, c) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (yield sql_database_1.isDbReadonly(c(e))) | ||
return; | ||
try { | ||
let cmd = this.pool.createCommand(); | ||
if ((yield cmd.execute(`select 1 | ||
FROM information_schema.columns | ||
WHERE table_name=${cmd.addParameterAndReturnSqlToken((yield e.getDbName()).toLocaleLowerCase())} and column_name=${cmd.addParameterAndReturnSqlToken((yield c(e).getDbName()).toLocaleLowerCase())}` + this.additionalWhere)).rows.length == 0) { | ||
let sql = `alter table ${yield e.getDbName()} add column ${this.addColumnSqlSyntax(c(e), yield c(e).getDbName())}`; | ||
console.log(sql); | ||
yield this.pool.execute(sql); | ||
}; | ||
PostgresSchemaBuilder.prototype.addColumnIfNotExist = function (e, c) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var cmd, _a, _b, _c, _d, _e, _f, _g, _h, sql, _j, _k, _l, _m, err_3; | ||
return tslib_1.__generator(this, function (_o) { | ||
switch (_o.label) { | ||
case 0: return [4 /*yield*/, sql_database_1.isDbReadonly(c(e))]; | ||
case 1: | ||
if (_o.sent()) | ||
return [2 /*return*/]; | ||
_o.label = 2; | ||
case 2: | ||
_o.trys.push([2, 10, , 11]); | ||
cmd = this.pool.createCommand(); | ||
_b = (_a = cmd).execute; | ||
_c = "select 1 \n FROM information_schema.columns \n WHERE table_name="; | ||
_e = (_d = cmd).addParameterAndReturnSqlToken; | ||
return [4 /*yield*/, e.getDbName()]; | ||
case 3: | ||
_f = _c + _e.apply(_d, [(_o.sent()).toLocaleLowerCase()]) + " and column_name="; | ||
_h = (_g = cmd).addParameterAndReturnSqlToken; | ||
return [4 /*yield*/, c(e).getDbName()]; | ||
case 4: return [4 /*yield*/, _b.apply(_a, [_f + _h.apply(_g, [(_o.sent()).toLocaleLowerCase()]) + this.additionalWhere])]; | ||
case 5: | ||
if (!((_o.sent()).rows.length == 0)) return [3 /*break*/, 9]; | ||
_j = "alter table "; | ||
return [4 /*yield*/, e.getDbName()]; | ||
case 6: | ||
_k = _j + (_o.sent()) + " add column "; | ||
_l = this.addColumnSqlSyntax; | ||
_m = [c(e)]; | ||
return [4 /*yield*/, c(e).getDbName()]; | ||
case 7: | ||
sql = _k + _l.apply(this, _m.concat([_o.sent()])); | ||
console.log(sql); | ||
return [4 /*yield*/, this.pool.execute(sql)]; | ||
case 8: | ||
_o.sent(); | ||
_o.label = 9; | ||
case 9: return [3 /*break*/, 11]; | ||
case 10: | ||
err_3 = _o.sent(); | ||
console.log(err_3); | ||
return [3 /*break*/, 11]; | ||
case 11: return [2 /*return*/]; | ||
} | ||
} | ||
catch (err) { | ||
console.log(err); | ||
} | ||
}); | ||
}); | ||
} | ||
verifyAllColumns(e) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
try { | ||
let cmd = this.pool.createCommand(); | ||
let cols = (yield cmd.execute(`select column_name | ||
FROM information_schema.columns | ||
WHERE table_name=${cmd.addParameterAndReturnSqlToken((yield e.getDbName()).toLocaleLowerCase())} ` + this.additionalWhere)).rows.map(x => x.column_name); | ||
for (const col of e.fields) { | ||
if (!(yield sql_database_1.isDbReadonly(col))) | ||
if (!cols.includes((yield col.getDbName()).toLocaleLowerCase())) { | ||
let sql = `alter table ${yield e.getDbName()} add column ${this.addColumnSqlSyntax(col, yield col.getDbName())}`; | ||
console.log(sql); | ||
yield this.pool.execute(sql); | ||
}; | ||
PostgresSchemaBuilder.prototype.verifyAllColumns = function (e) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var cmd, cols, _a, _b, _c, _d, _e, _f, _g, col, _h, _j, sql, _k, _l, _m, _o, e_3_1, err_4; | ||
var e_3, _p; | ||
return tslib_1.__generator(this, function (_q) { | ||
switch (_q.label) { | ||
case 0: | ||
_q.trys.push([0, 15, , 16]); | ||
cmd = this.pool.createCommand(); | ||
_b = (_a = cmd).execute; | ||
_c = "select column_name \n FROM information_schema.columns \n WHERE table_name="; | ||
_e = (_d = cmd).addParameterAndReturnSqlToken; | ||
return [4 /*yield*/, e.getDbName()]; | ||
case 1: return [4 /*yield*/, _b.apply(_a, [_c + _e.apply(_d, [(_q.sent()).toLocaleLowerCase()]) + " " + this.additionalWhere])]; | ||
case 2: | ||
cols = (_q.sent()).rows.map(function (x) { return x.column_name; }); | ||
_q.label = 3; | ||
case 3: | ||
_q.trys.push([3, 12, 13, 14]); | ||
_f = tslib_1.__values(e.fields), _g = _f.next(); | ||
_q.label = 4; | ||
case 4: | ||
if (!!_g.done) return [3 /*break*/, 11]; | ||
col = _g.value; | ||
return [4 /*yield*/, sql_database_1.isDbReadonly(col)]; | ||
case 5: | ||
if (!!(_q.sent())) return [3 /*break*/, 10]; | ||
_j = (_h = cols).includes; | ||
return [4 /*yield*/, col.getDbName()]; | ||
case 6: | ||
if (!!_j.apply(_h, [(_q.sent()).toLocaleLowerCase()])) return [3 /*break*/, 10]; | ||
_k = "alter table "; | ||
return [4 /*yield*/, e.getDbName()]; | ||
case 7: | ||
_l = _k + (_q.sent()) + " add column "; | ||
_m = this.addColumnSqlSyntax; | ||
_o = [col]; | ||
return [4 /*yield*/, col.getDbName()]; | ||
case 8: | ||
sql = _l + _m.apply(this, _o.concat([_q.sent()])); | ||
console.log(sql); | ||
return [4 /*yield*/, this.pool.execute(sql)]; | ||
case 9: | ||
_q.sent(); | ||
_q.label = 10; | ||
case 10: | ||
_g = _f.next(); | ||
return [3 /*break*/, 4]; | ||
case 11: return [3 /*break*/, 14]; | ||
case 12: | ||
e_3_1 = _q.sent(); | ||
e_3 = { error: e_3_1 }; | ||
return [3 /*break*/, 14]; | ||
case 13: | ||
try { | ||
if (_g && !_g.done && (_p = _f.return)) _p.call(_f); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
return [7 /*endfinally*/]; | ||
case 14: return [3 /*break*/, 16]; | ||
case 15: | ||
err_4 = _q.sent(); | ||
console.log(err_4); | ||
return [3 /*break*/, 16]; | ||
case 16: return [2 /*return*/]; | ||
} | ||
} | ||
catch (err) { | ||
console.log(err); | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return PostgresSchemaBuilder; | ||
}()); | ||
exports.PostgresSchemaBuilder = PostgresSchemaBuilder; | ||
function preparePostgresQueueStorage(sql) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let c = new context_1.Context(); | ||
c.setDataProvider(sql); | ||
{ | ||
let e = c.for(expressBridge_1.JobsInQueueEntity); | ||
yield new PostgresSchemaBuilder(sql).createIfNotExist(e.metadata); | ||
yield new PostgresSchemaBuilder(sql).verifyAllColumns(e.metadata); | ||
} | ||
return new expressBridge_1.EntityQueueStorage(c.for(expressBridge_1.JobsInQueueEntity)); | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var c, e; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
c = new context_1.Context(); | ||
c.setDataProvider(sql); | ||
e = c.for(expressBridge_1.JobsInQueueEntity); | ||
return [4 /*yield*/, new PostgresSchemaBuilder(sql).createIfNotExist(e.metadata)]; | ||
case 1: | ||
_a.sent(); | ||
return [4 /*yield*/, new PostgresSchemaBuilder(sql).verifyAllColumns(e.metadata)]; | ||
case 2: | ||
_a.sent(); | ||
return [2 /*return*/, new expressBridge_1.EntityQueueStorage(c.for(expressBridge_1.JobsInQueueEntity))]; | ||
} | ||
}); | ||
}); | ||
@@ -219,0 +449,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.JobsInQueueEntity = exports.EntityQueueStorage = exports.ExpressRequestBridgeToDataApiRequest = exports.SiteArea = exports.ExpressBridge = exports.initExpress = void 0; | ||
const tslib_1 = require("tslib"); | ||
const __1 = require("../"); | ||
const bodyParser = require("body-parser"); | ||
const register_actions_on_server_1 = require("./register-actions-on-server"); | ||
const register_entities_on_server_1 = require("./register-entities-on-server"); | ||
const JsonEntityFileStorage_1 = require("./JsonEntityFileStorage"); | ||
const json_data_provider_1 = require("../src/data-providers/json-data-provider"); | ||
const remult3_1 = require("../src/remult3"); | ||
const server_action_1 = require("../src/server-action"); | ||
const data_api_1 = require("../src/data-api"); | ||
const context_1 = require("../src/context"); | ||
var tslib_1 = require("tslib"); | ||
var __1 = require("../"); | ||
var bodyParser = require("body-parser"); | ||
var register_actions_on_server_1 = require("./register-actions-on-server"); | ||
var register_entities_on_server_1 = require("./register-entities-on-server"); | ||
var JsonEntityFileStorage_1 = require("./JsonEntityFileStorage"); | ||
var json_data_provider_1 = require("../src/data-providers/json-data-provider"); | ||
var remult3_1 = require("../src/remult3"); | ||
var server_action_1 = require("../src/server-action"); | ||
var data_api_1 = require("../src/data-api"); | ||
var context_1 = require("../src/context"); | ||
function initExpress(app, options) { | ||
@@ -20,3 +20,3 @@ if (!options) { | ||
if (!options.getUserFromRequest) { | ||
options.getUserFromRequest = x => x['user']; | ||
options.getUserFromRequest = function (x) { return x['user']; }; | ||
} | ||
@@ -31,15 +31,15 @@ if (options.bodySizeLimit === undefined) { | ||
app.use(bodyParser.urlencoded({ extended: true, limit: options.bodySizeLimit })); | ||
let builder; | ||
var builder; | ||
if (options.dataProvider) { | ||
let dataProvider = options.dataProvider; | ||
if (typeof dataProvider === 'function') | ||
builder = dataProvider; | ||
var dataProvider_1 = options.dataProvider; | ||
if (typeof dataProvider_1 === 'function') | ||
builder = dataProvider_1; | ||
else | ||
builder = () => dataProvider; | ||
builder = function () { return dataProvider_1; }; | ||
} | ||
else { | ||
builder = () => new json_data_provider_1.JsonDataProvider(new JsonEntityFileStorage_1.JsonEntityFileStorage('./db')); | ||
builder = function () { return new json_data_provider_1.JsonDataProvider(new JsonEntityFileStorage_1.JsonEntityFileStorage('./db')); }; | ||
} | ||
let result = new ExpressBridge(app, options.getUserFromRequest, new inProcessQueueHandler(options.queueStorage), options.initRequest, builder); | ||
let apiArea = result.addArea('/' + __1.Context.apiBaseUrl); | ||
var result = new ExpressBridge(app, options.getUserFromRequest, new inProcessQueueHandler(options.queueStorage), options.initRequest, builder); | ||
var apiArea = result.addArea('/' + __1.Context.apiBaseUrl); | ||
if (!options.disableAutoApi) { | ||
@@ -52,4 +52,4 @@ register_actions_on_server_1.registerActionsOnServer(apiArea); | ||
exports.initExpress = initExpress; | ||
class ExpressBridge { | ||
constructor(app, getUserFromRequest, queue, initRequest, _dataProviderFactory) { | ||
var ExpressBridge = /** @class */ (function () { | ||
function ExpressBridge(app, getUserFromRequest, queue, initRequest, _dataProviderFactory) { | ||
this.app = app; | ||
@@ -62,3 +62,3 @@ this.getUserFromRequest = getUserFromRequest; | ||
} | ||
addArea(rootUrl, isUserValidForArea) { | ||
ExpressBridge.prototype.addArea = function (rootUrl, isUserValidForArea) { | ||
var r = new SiteArea(this, this.app, rootUrl, this.logApiEndPoints, isUserValidForArea); | ||
@@ -69,12 +69,15 @@ if (!this.firstArea) { | ||
return r; | ||
} | ||
getValidContext(req) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return this.firstArea.getValidContext(req); | ||
}; | ||
ExpressBridge.prototype.getValidContext = function (req) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, this.firstArea.getValidContext(req)]; | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return ExpressBridge; | ||
}()); | ||
exports.ExpressBridge = ExpressBridge; | ||
class SiteArea { | ||
constructor(bridge, app, rootUrl, logApiEndpoints, isUserValidForArea) { | ||
var SiteArea = /** @class */ (function () { | ||
function SiteArea(bridge, app, rootUrl, logApiEndpoints, isUserValidForArea) { | ||
this.bridge = bridge; | ||
@@ -86,8 +89,9 @@ this.app = app; | ||
} | ||
add(entityOrDataApiFactory) { | ||
let api; | ||
SiteArea.prototype.add = function (entityOrDataApiFactory) { | ||
var _this = this; | ||
var api; | ||
api = entityOrDataApiFactory; | ||
let contextForRouteExtraction = new context_1.ServerContext(); | ||
contextForRouteExtraction.setReq({ clientIp: 'onServer', user: undefined, get: (r) => '', getHeader: (x) => "", getBaseUrl: () => '' }); | ||
let myRoute = api(contextForRouteExtraction).getRoute(); | ||
var contextForRouteExtraction = new context_1.ServerContext(); | ||
contextForRouteExtraction.setReq({ clientIp: 'onServer', user: undefined, get: function (r) { return ''; }, getHeader: function (x) { return ""; }, getBaseUrl: function () { return ''; } }); | ||
var myRoute = api(contextForRouteExtraction).getRoute(); | ||
myRoute = this.rootUrl + '/' + myRoute; | ||
@@ -97,3 +101,3 @@ if (this.logApiEndpoints) | ||
this.app.route(myRoute) | ||
.get(this.process((c, req, res) => { | ||
.get(this.process(function (c, req, res) { | ||
if (req.get("__action") == "count") { | ||
@@ -104,93 +108,150 @@ return api(c).count(res, req); | ||
return api(c).getArray(res, req); | ||
})).put(this.process((c, req, res, orig) => tslib_1.__awaiter(this, void 0, void 0, function* () { return api(c).put(res, '', orig.body); }))) | ||
.delete(this.process((c, req, res, orig) => tslib_1.__awaiter(this, void 0, void 0, function* () { return api(c).delete(res, ''); }))) | ||
.post(this.process((c, req, res, orig) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
switch (req.get("__action")) { | ||
case "get": | ||
return api(c).getArray(res, req, orig.body); | ||
case "count": | ||
return api(c).count(res, req, orig.body); | ||
default: | ||
return api(c).post(res, orig.body); | ||
} | ||
}))); | ||
})).put(this.process(function (c, req, res, orig) { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, api(c).put(res, '', orig.body)]; | ||
}); }); })) | ||
.delete(this.process(function (c, req, res, orig) { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, api(c).delete(res, '')]; | ||
}); }); })) | ||
.post(this.process(function (c, req, res, orig) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (req.get("__action")) { | ||
case "get": | ||
return [2 /*return*/, api(c).getArray(res, req, orig.body)]; | ||
case "count": | ||
return [2 /*return*/, api(c).count(res, req, orig.body)]; | ||
default: | ||
return [2 /*return*/, api(c).post(res, orig.body)]; | ||
} | ||
return [2 /*return*/]; | ||
}); | ||
}); })); | ||
this.app.route(myRoute + '/:id') | ||
//@ts-ignore | ||
.get(this.process((c, req, res, orig) => tslib_1.__awaiter(this, void 0, void 0, function* () { return api(c).get(res, orig.params.id); }))) | ||
.get(this.process(function (c, req, res, orig) { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, api(c).get(res, orig.params.id)]; | ||
}); }); })) | ||
//@ts-ignore | ||
.put(this.process((c, req, res, orig) => tslib_1.__awaiter(this, void 0, void 0, function* () { return api(c).put(res, orig.params.id, orig.body); }))) | ||
.put(this.process(function (c, req, res, orig) { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, api(c).put(res, orig.params.id, orig.body)]; | ||
}); }); })) | ||
//@ts-ignore | ||
.delete(this.process((c, req, res, orig) => tslib_1.__awaiter(this, void 0, void 0, function* () { return api(c).delete(res, orig.params.id); }))); | ||
} | ||
process(what) { | ||
return (req, res) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let myReq = new ExpressRequestBridgeToDataApiRequest(req); | ||
let myRes = new ExpressResponseBridgeToDataApiResponse(res); | ||
myReq.user = yield this.bridge.getUserFromRequest(req); | ||
if (this.isUserValidForArea) | ||
if (!this.isUserValidForArea(myReq)) | ||
myReq.user = null; | ||
let context = new context_1.ServerContext(); | ||
context.setReq(myReq); | ||
context.setDataProvider(this.bridge._dataProviderFactory(context)); | ||
if (this.bridge.initRequest) { | ||
yield this.bridge.initRequest(context); | ||
} | ||
what(context, myReq, myRes, req); | ||
}); | ||
} | ||
.delete(this.process(function (c, req, res, orig) { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, api(c).delete(res, orig.params.id)]; | ||
}); }); })); | ||
}; | ||
SiteArea.prototype.process = function (what) { | ||
var _this = this; | ||
return function (req, res) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var myReq, myRes, _a, context; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
myReq = new ExpressRequestBridgeToDataApiRequest(req); | ||
myRes = new ExpressResponseBridgeToDataApiResponse(res); | ||
_a = myReq; | ||
return [4 /*yield*/, this.bridge.getUserFromRequest(req)]; | ||
case 1: | ||
_a.user = _b.sent(); | ||
if (this.isUserValidForArea) | ||
if (!this.isUserValidForArea(myReq)) | ||
myReq.user = null; | ||
context = new context_1.ServerContext(); | ||
context.setReq(myReq); | ||
context.setDataProvider(this.bridge._dataProviderFactory(context)); | ||
if (!this.bridge.initRequest) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, this.bridge.initRequest(context)]; | ||
case 2: | ||
_b.sent(); | ||
_b.label = 3; | ||
case 3: | ||
what(context, myReq, myRes, req); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }; | ||
}; | ||
; | ||
getValidContext(req) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let context; | ||
yield this.process((c) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
context = c; | ||
}))(req, undefined); | ||
return context; | ||
SiteArea.prototype.getValidContext = function (req) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var context; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.process(function (c) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
context = c; | ||
return [2 /*return*/]; | ||
}); | ||
}); })(req, undefined)]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/, context]; | ||
} | ||
}); | ||
}); | ||
} | ||
initQueue() { | ||
}; | ||
SiteArea.prototype.initQueue = function () { | ||
var _this = this; | ||
this.addAction({ | ||
__register: x => { | ||
x(server_action_1.Action.apiUrlForJobStatus, false, (data, req, res) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let job = yield this.bridge.queue.getJobInfo(data.queuedJobId); | ||
let userId = undefined; | ||
if (req.user) | ||
userId = req.user.id; | ||
if (job.userId == '') | ||
job.userId = undefined; | ||
if (userId != job.userId) | ||
res.forbidden(); | ||
else | ||
res.success(job.info); | ||
})); | ||
__register: function (x) { | ||
x(server_action_1.Action.apiUrlForJobStatus, false, function (data, req, res) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var job, userId; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.bridge.queue.getJobInfo(data.queuedJobId)]; | ||
case 1: | ||
job = _a.sent(); | ||
userId = undefined; | ||
if (req.user) | ||
userId = req.user.id; | ||
if (job.userId == '') | ||
job.userId = undefined; | ||
if (userId != job.userId) | ||
res.forbidden(); | ||
else | ||
res.success(job.info); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
} | ||
}); | ||
this.initQueue = () => { }; | ||
} | ||
addAction(action) { | ||
action.__register((url, queue, what) => { | ||
let myUrl = this.rootUrl + '/' + url; | ||
if (this.logApiEndpoints) | ||
this.initQueue = function () { }; | ||
}; | ||
SiteArea.prototype.addAction = function (action) { | ||
var _this = this; | ||
action.__register(function (url, queue, what) { | ||
var myUrl = _this.rootUrl + '/' + url; | ||
if (_this.logApiEndpoints) | ||
console.log(myUrl); | ||
if (queue) { | ||
this.initQueue(); | ||
this.bridge.queue.mapQueuedAction(myUrl, what); | ||
_this.initQueue(); | ||
_this.bridge.queue.mapQueuedAction(myUrl, what); | ||
} | ||
this.app.route(myUrl).post(this.process((context, req, res, orig) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (queue) { | ||
let r = { | ||
queuedJobId: yield this.bridge.queue.submitJob(myUrl, context, orig.body) | ||
}; | ||
res.success(r); | ||
} | ||
else | ||
return what(orig.body, context, res); | ||
}))); | ||
_this.app.route(myUrl).post(_this.process(function (context, req, res, orig) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var r; | ||
var _a; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
if (!queue) return [3 /*break*/, 2]; | ||
_a = {}; | ||
return [4 /*yield*/, this.bridge.queue.submitJob(myUrl, context, orig.body)]; | ||
case 1: | ||
r = (_a.queuedJobId = _b.sent(), | ||
_a); | ||
res.success(r); | ||
return [3 /*break*/, 3]; | ||
case 2: return [2 /*return*/, what(orig.body, context, res)]; | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); })); | ||
}); | ||
} | ||
} | ||
}; | ||
return SiteArea; | ||
}()); | ||
exports.SiteArea = SiteArea; | ||
class ExpressRequestBridgeToDataApiRequest { | ||
constructor(r) { | ||
var ExpressRequestBridgeToDataApiRequest = /** @class */ (function () { | ||
function ExpressRequestBridgeToDataApiRequest(r) { | ||
this.r = r; | ||
@@ -200,210 +261,285 @@ this.user = undefined; | ||
} | ||
get(key) { | ||
ExpressRequestBridgeToDataApiRequest.prototype.get = function (key) { | ||
return this.r.query[key]; | ||
} | ||
getBaseUrl() { | ||
}; | ||
ExpressRequestBridgeToDataApiRequest.prototype.getBaseUrl = function () { | ||
if (this.r.originalUrl) | ||
return this.r.originalUrl; | ||
return this.r.path; | ||
} | ||
getHeader(key) { return this.r.headers[key]; } | ||
}; | ||
ExpressRequestBridgeToDataApiRequest.prototype.getHeader = function (key) { return this.r.headers[key]; }; | ||
; | ||
} | ||
return ExpressRequestBridgeToDataApiRequest; | ||
}()); | ||
exports.ExpressRequestBridgeToDataApiRequest = ExpressRequestBridgeToDataApiRequest; | ||
class ExpressResponseBridgeToDataApiResponse { | ||
constructor(r) { | ||
var ExpressResponseBridgeToDataApiResponse = /** @class */ (function () { | ||
function ExpressResponseBridgeToDataApiResponse(r) { | ||
this.r = r; | ||
} | ||
forbidden() { | ||
ExpressResponseBridgeToDataApiResponse.prototype.forbidden = function () { | ||
this.r.sendStatus(403); | ||
} | ||
progress(progress) { | ||
} | ||
success(data) { | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.progress = function (progress) { | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.success = function (data) { | ||
this.r.json(data); | ||
} | ||
created(data) { | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.created = function (data) { | ||
this.r.statusCode = 201; | ||
this.r.json(data); | ||
} | ||
deleted() { | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.deleted = function () { | ||
this.r.sendStatus(204); | ||
} | ||
notFound() { | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.notFound = function () { | ||
this.r.sendStatus(404); | ||
} | ||
error(data) { | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.error = function (data) { | ||
data = data_api_1.serializeError(data); | ||
this.r.status(400).json(data); | ||
} | ||
} | ||
}; | ||
return ExpressResponseBridgeToDataApiResponse; | ||
}()); | ||
function throwError() { | ||
throw "Invalid"; | ||
} | ||
class inProcessQueueHandler { | ||
constructor(storage) { | ||
var inProcessQueueHandler = /** @class */ (function () { | ||
function inProcessQueueHandler(storage) { | ||
this.storage = storage; | ||
this.actions = new Map(); | ||
} | ||
submitJob(url, req, body) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let id = yield this.storage.createJob(url, req.user ? req.user.id : undefined); | ||
let job = yield this.storage.getJobInfo(id); | ||
this.actions.get(url)(body, req, { | ||
error: error => job.setErrorResult(data_api_1.serializeError(error)), | ||
success: result => job.setResult(result), | ||
progress: progress => job.setProgress(progress) | ||
inProcessQueueHandler.prototype.submitJob = function (url, req, body) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var id, job; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.storage.createJob(url, req.user ? req.user.id : undefined)]; | ||
case 1: | ||
id = _a.sent(); | ||
return [4 /*yield*/, this.storage.getJobInfo(id)]; | ||
case 2: | ||
job = _a.sent(); | ||
this.actions.get(url)(body, req, { | ||
error: function (error) { return job.setErrorResult(data_api_1.serializeError(error)); }, | ||
success: function (result) { return job.setResult(result); }, | ||
progress: function (progress) { return job.setProgress(progress); } | ||
}); | ||
return [2 /*return*/, id]; | ||
} | ||
}); | ||
return id; | ||
}); | ||
} | ||
mapQueuedAction(url, what) { | ||
}; | ||
inProcessQueueHandler.prototype.mapQueuedAction = function (url, what) { | ||
this.actions.set(url, what); | ||
} | ||
getJobInfo(queuedJobId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield this.storage.getJobInfo(queuedJobId); | ||
}; | ||
inProcessQueueHandler.prototype.getJobInfo = function (queuedJobId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.storage.getJobInfo(queuedJobId)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
class InMemoryQueueStorage { | ||
constructor() { | ||
}; | ||
return inProcessQueueHandler; | ||
}()); | ||
var InMemoryQueueStorage = /** @class */ (function () { | ||
function InMemoryQueueStorage() { | ||
this.jobs = new Map(); | ||
} | ||
getJobInfo(queuedJobId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return this.jobs.get(queuedJobId); | ||
InMemoryQueueStorage.prototype.getJobInfo = function (queuedJobId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, this.jobs.get(queuedJobId)]; | ||
}); | ||
}); | ||
} | ||
createJob(url, userId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let id = this.jobs.size.toString(); | ||
this.jobs.set(id, { | ||
info: { | ||
done: false | ||
}, | ||
userId: userId, | ||
setErrorResult: (error) => { | ||
let job = this.jobs.get(id); | ||
job.info.done = true; | ||
job.info.error = error; | ||
}, | ||
setResult: (result) => { | ||
let job = this.jobs.get(id); | ||
job.info.done = true; | ||
job.info.result = result; | ||
}, | ||
setProgress: (progress) => { | ||
let job = this.jobs.get(id); | ||
job.info.progress = progress; | ||
} | ||
}; | ||
InMemoryQueueStorage.prototype.createJob = function (url, userId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var id; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
id = this.jobs.size.toString(); | ||
this.jobs.set(id, { | ||
info: { | ||
done: false | ||
}, | ||
userId: userId, | ||
setErrorResult: function (error) { | ||
var job = _this.jobs.get(id); | ||
job.info.done = true; | ||
job.info.error = error; | ||
}, | ||
setResult: function (result) { | ||
var job = _this.jobs.get(id); | ||
job.info.done = true; | ||
job.info.result = result; | ||
}, | ||
setProgress: function (progress) { | ||
var job = _this.jobs.get(id); | ||
job.info.progress = progress; | ||
} | ||
}); | ||
return [2 /*return*/, id]; | ||
}); | ||
return id; | ||
}); | ||
} | ||
} | ||
let test = 0; | ||
class EntityQueueStorage { | ||
constructor(context) { | ||
}; | ||
return InMemoryQueueStorage; | ||
}()); | ||
var test = 0; | ||
var EntityQueueStorage = /** @class */ (function () { | ||
function EntityQueueStorage(context) { | ||
this.context = context; | ||
this.sync = Promise.resolve(); | ||
} | ||
doSync(what) { | ||
return this.sync = this.sync.then(() => what()); | ||
} | ||
getJobInfo(queuedJobId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let q = yield this.context.findId(queuedJobId); | ||
let lastProgress = undefined; | ||
return { | ||
userId: q.userId, | ||
info: { | ||
done: q.done, | ||
error: q.error ? JSON.parse(q.result) : undefined, | ||
result: q.done && !q.error ? JSON.parse(q.result) : undefined, | ||
progress: q.progress | ||
}, | ||
setErrorResult: (error) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.sync; | ||
q.error = true; | ||
q.done = true; | ||
q.result = JSON.stringify(error); | ||
q.doneTime = new Date(); | ||
q.progress = 1; | ||
yield this.doSync(() => q._.save()); | ||
}), | ||
setResult: (result) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.sync; | ||
q.done = true; | ||
q.result = JSON.stringify(result); | ||
q.doneTime = new Date(); | ||
yield this.doSync(() => q._.save()); | ||
}), | ||
setProgress: (progress) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (progress === 0) | ||
return; | ||
let now = new Date(); | ||
if (lastProgress && now.valueOf() - lastProgress.valueOf() < 200) | ||
return; | ||
lastProgress = new Date(); | ||
yield this.sync; | ||
q.progress = progress; | ||
yield this.doSync(() => q._.save()); | ||
}) | ||
}; | ||
EntityQueueStorage.prototype.doSync = function (what) { | ||
return this.sync = this.sync.then(function () { return what(); }); | ||
}; | ||
EntityQueueStorage.prototype.getJobInfo = function (queuedJobId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var q, lastProgress; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.context.findId(queuedJobId)]; | ||
case 1: | ||
q = _a.sent(); | ||
lastProgress = undefined; | ||
return [2 /*return*/, { | ||
userId: q.userId, | ||
info: { | ||
done: q.done, | ||
error: q.error ? JSON.parse(q.result) : undefined, | ||
result: q.done && !q.error ? JSON.parse(q.result) : undefined, | ||
progress: q.progress | ||
}, | ||
setErrorResult: function (error) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.sync]; | ||
case 1: | ||
_a.sent(); | ||
q.error = true; | ||
q.done = true; | ||
q.result = JSON.stringify(error); | ||
q.doneTime = new Date(); | ||
q.progress = 1; | ||
return [4 /*yield*/, this.doSync(function () { return q._.save(); })]; | ||
case 2: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }, | ||
setResult: function (result) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.sync]; | ||
case 1: | ||
_a.sent(); | ||
q.done = true; | ||
q.result = JSON.stringify(result); | ||
q.doneTime = new Date(); | ||
return [4 /*yield*/, this.doSync(function () { return q._.save(); })]; | ||
case 2: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }, | ||
setProgress: function (progress) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var now; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (progress === 0) | ||
return [2 /*return*/]; | ||
now = new Date(); | ||
if (lastProgress && now.valueOf() - lastProgress.valueOf() < 200) | ||
return [2 /*return*/]; | ||
lastProgress = new Date(); | ||
return [4 /*yield*/, this.sync]; | ||
case 1: | ||
_a.sent(); | ||
q.progress = progress; | ||
return [4 /*yield*/, this.doSync(function () { return q._.save(); })]; | ||
case 2: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); } | ||
}]; | ||
} | ||
}); | ||
}); | ||
} | ||
createJob(url, userId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let q = this.context.create(); | ||
q.userId = userId; | ||
q.submitTime = new Date(); | ||
q.url = url; | ||
yield q._.save(); | ||
return q.id; | ||
}; | ||
EntityQueueStorage.prototype.createJob = function (url, userId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var q; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
q = this.context.create(); | ||
q.userId = userId; | ||
q.submitTime = new Date(); | ||
q.url = url; | ||
return [4 /*yield*/, q._.save()]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/, q.id]; | ||
} | ||
}); | ||
}); | ||
}; | ||
return EntityQueueStorage; | ||
}()); | ||
exports.EntityQueueStorage = EntityQueueStorage; | ||
var JobsInQueueEntity = /** @class */ (function (_super) { | ||
tslib_1.__extends(JobsInQueueEntity, _super); | ||
function JobsInQueueEntity() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
} | ||
exports.EntityQueueStorage = EntityQueueStorage; | ||
let JobsInQueueEntity = class JobsInQueueEntity extends __1.IdEntity { | ||
}; | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], JobsInQueueEntity.prototype, "userId", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], JobsInQueueEntity.prototype, "url", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Date) | ||
], JobsInQueueEntity.prototype, "submitTime", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Date) | ||
], JobsInQueueEntity.prototype, "doneTime", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], JobsInQueueEntity.prototype, "result", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Boolean) | ||
], JobsInQueueEntity.prototype, "done", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Boolean) | ||
], JobsInQueueEntity.prototype, "error", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Number) | ||
], JobsInQueueEntity.prototype, "progress", void 0); | ||
JobsInQueueEntity = tslib_1.__decorate([ | ||
remult3_1.Entity({ | ||
key: 'jobsInQueue', | ||
includeInApi: false | ||
}) | ||
], JobsInQueueEntity); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], JobsInQueueEntity.prototype, "userId", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], JobsInQueueEntity.prototype, "url", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Date) | ||
], JobsInQueueEntity.prototype, "submitTime", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Date) | ||
], JobsInQueueEntity.prototype, "doneTime", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], JobsInQueueEntity.prototype, "result", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Boolean) | ||
], JobsInQueueEntity.prototype, "done", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Boolean) | ||
], JobsInQueueEntity.prototype, "error", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Number) | ||
], JobsInQueueEntity.prototype, "progress", void 0); | ||
JobsInQueueEntity = tslib_1.__decorate([ | ||
remult3_1.Entity({ | ||
key: 'jobsInQueue', | ||
includeInApi: false | ||
}) | ||
], JobsInQueueEntity); | ||
return JobsInQueueEntity; | ||
}(__1.IdEntity)); | ||
exports.JobsInQueueEntity = JobsInQueueEntity; | ||
//# sourceMappingURL=expressBridge.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.JsonEntityFileStorage = void 0; | ||
const path = require("path"); | ||
const fs = require("fs"); | ||
class JsonEntityFileStorage { | ||
constructor(folderPath) { | ||
var path = require("path"); | ||
var fs = require("fs"); | ||
var JsonEntityFileStorage = /** @class */ (function () { | ||
function JsonEntityFileStorage(folderPath) { | ||
this.folderPath = folderPath; | ||
} | ||
getItem(entityDbName) { | ||
let fn = path.join(this.folderPath, entityDbName) + '.json'; | ||
JsonEntityFileStorage.prototype.getItem = function (entityDbName) { | ||
var fn = path.join(this.folderPath, entityDbName) + '.json'; | ||
if (fs.existsSync(fn)) { | ||
@@ -16,4 +16,4 @@ return fs.readFileSync(fn).toString(); | ||
return undefined; | ||
} | ||
setItem(entityDbName, json) { | ||
}; | ||
JsonEntityFileStorage.prototype.setItem = function (entityDbName, json) { | ||
if (!fs.existsSync(this.folderPath)) { | ||
@@ -23,5 +23,6 @@ fs.mkdirSync(this.folderPath); | ||
return fs.writeFileSync(path.join(this.folderPath, entityDbName) + '.json', json); | ||
} | ||
} | ||
}; | ||
return JsonEntityFileStorage; | ||
}()); | ||
exports.JsonEntityFileStorage = JsonEntityFileStorage; | ||
//# sourceMappingURL=JsonEntityFileStorage.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.registerActionsOnServer = void 0; | ||
const server_action_1 = require("../src/server-action"); | ||
var server_action_1 = require("../src/server-action"); | ||
function registerActionsOnServer(area) { | ||
var addAction = (a) => { | ||
let x = a[server_action_1.serverActionField]; | ||
var addAction = function (a) { | ||
var x = a[server_action_1.serverActionField]; | ||
if (!x) { | ||
@@ -14,3 +14,3 @@ throw 'failed to set server action, did you forget the BackendMethod Decorator?'; | ||
server_action_1.actionInfo.runningOnServer = true; | ||
server_action_1.actionInfo.allActions.forEach((a) => { | ||
server_action_1.actionInfo.allActions.forEach(function (a) { | ||
addAction(a); | ||
@@ -17,0 +17,0 @@ }); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.registerEntitiesOnServer = void 0; | ||
const remult3_1 = require("../src/remult3"); | ||
const context_1 = require("../src/context"); | ||
const data_api_1 = require("../src/data-api"); | ||
var remult3_1 = require("../src/remult3"); | ||
var context_1 = require("../src/context"); | ||
var data_api_1 = require("../src/data-api"); | ||
function registerEntitiesOnServer(area) { | ||
let errors = ''; | ||
var errors = ''; | ||
//add Api Entries | ||
context_1.allEntities.forEach(e => { | ||
context_1.allEntities.forEach(function (e) { | ||
if (!(remult3_1.getEntitySettings(e).includeInApi === false)) | ||
area.add(c => { | ||
area.add(function (c) { | ||
return new data_api_1.DataApi(c.for(e), c); | ||
@@ -14,0 +14,0 @@ }); |
@@ -6,3 +6,3 @@ "use strict"; | ||
if (typeof f === 'function') { | ||
let x = f; | ||
var x = f; | ||
return x(); | ||
@@ -9,0 +9,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.OneToMany = exports.LookupColumn = exports.CompoundIdField = exports.makeTitle = void 0; | ||
const tslib_1 = require("tslib"); | ||
const set_1 = require("../set"); | ||
const filter_interfaces_1 = require("./filter/filter-interfaces"); | ||
const remult3_1 = require("./remult3"); | ||
var tslib_1 = require("tslib"); | ||
var set_1 = require("../set"); | ||
var filter_interfaces_1 = require("./filter/filter-interfaces"); | ||
var remult3_1 = require("./remult3"); | ||
function makeTitle(name) { | ||
@@ -12,15 +12,19 @@ // insert a space before all caps | ||
// uppercase the first character | ||
.replace(/^./, (str) => str.toUpperCase()).replace('Email', 'eMail').replace(" I D", " ID"); | ||
.replace(/^./, function (str) { return str.toUpperCase(); }).replace('Email', 'eMail').replace(" I D", " ID"); | ||
} | ||
exports.makeTitle = makeTitle; | ||
class CompoundIdField { | ||
constructor(...columns) { | ||
var CompoundIdField = /** @class */ (function () { | ||
function CompoundIdField() { | ||
var columns = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
columns[_i] = arguments[_i]; | ||
} | ||
this.fields = columns; | ||
} | ||
getDbName() { | ||
CompoundIdField.prototype.getDbName = function () { | ||
return Promise.resolve(""); | ||
} | ||
getId(instance) { | ||
let r = ""; | ||
this.fields.forEach(c => { | ||
}; | ||
CompoundIdField.prototype.getId = function (instance) { | ||
var r = ""; | ||
this.fields.forEach(function (c) { | ||
if (r.length > 0) | ||
@@ -31,22 +35,28 @@ r += ','; | ||
return r; | ||
} | ||
get valueConverter() { | ||
throw new Error("cant get value converter of compound id"); | ||
} | ||
isEqualTo(value) { | ||
return new filter_interfaces_1.Filter(add => { | ||
let val = value.toString(); | ||
let id = val.split(','); | ||
this.fields.forEach((c, i) => { | ||
}; | ||
Object.defineProperty(CompoundIdField.prototype, "valueConverter", { | ||
get: function () { | ||
throw new Error("cant get value converter of compound id"); | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
CompoundIdField.prototype.isEqualTo = function (value) { | ||
var _this = this; | ||
return new filter_interfaces_1.Filter(function (add) { | ||
var val = value.toString(); | ||
var id = val.split(','); | ||
_this.fields.forEach(function (c, i) { | ||
add.isEqualTo(c, id[i]); | ||
}); | ||
}); | ||
} | ||
resultIdFilter(id, data) { | ||
return new filter_interfaces_1.Filter(add => { | ||
let idParts = []; | ||
}; | ||
CompoundIdField.prototype.resultIdFilter = function (id, data) { | ||
var _this = this; | ||
return new filter_interfaces_1.Filter(function (add) { | ||
var idParts = []; | ||
if (id != undefined) | ||
idParts = id.split(','); | ||
this.fields.forEach((c, i) => { | ||
let val = undefined; | ||
_this.fields.forEach(function (c, i) { | ||
var val = undefined; | ||
if (i < idParts.length) | ||
@@ -59,26 +69,27 @@ val = idParts[i]; | ||
}); | ||
} | ||
} | ||
}; | ||
return CompoundIdField; | ||
}()); | ||
exports.CompoundIdField = CompoundIdField; | ||
class LookupColumn { | ||
constructor(repository, id) { | ||
var LookupColumn = /** @class */ (function () { | ||
function LookupColumn(repository, id) { | ||
this.repository = repository; | ||
this.id = id; | ||
} | ||
setId(val) { | ||
LookupColumn.prototype.setId = function (val) { | ||
if (this.repository.metadata.idMetadata.field.valueType == Number) | ||
val = +val; | ||
this.id = val; | ||
} | ||
waitLoadOf(id) { | ||
}; | ||
LookupColumn.prototype.waitLoadOf = function (id) { | ||
if (id === undefined || id === null) | ||
return null; | ||
return this.repository.getCachedByIdAsync(id); | ||
} | ||
get(id) { | ||
}; | ||
LookupColumn.prototype.get = function (id) { | ||
if (id === undefined || id === null) | ||
return null; | ||
return this.repository.getCachedById(id); | ||
} | ||
set(item) { | ||
}; | ||
LookupColumn.prototype.set = function (item) { | ||
if (item) { | ||
@@ -88,3 +99,3 @@ if (typeof item === "string" || typeof item === "number") | ||
else { | ||
let eo = remult3_1.getEntityRef(item, false); | ||
var eo = remult3_1.getEntityRef(item, false); | ||
if (eo) { | ||
@@ -102,16 +113,23 @@ this.repository.addToCache(item); | ||
} | ||
} | ||
get item() { | ||
return this.get(this.id); | ||
} | ||
waitLoad() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return this.waitLoadOf(this.id); | ||
}; | ||
Object.defineProperty(LookupColumn.prototype, "item", { | ||
get: function () { | ||
return this.get(this.id); | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
LookupColumn.prototype.waitLoad = function () { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, this.waitLoadOf(this.id)]; | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return LookupColumn; | ||
}()); | ||
exports.LookupColumn = LookupColumn; | ||
9000; | ||
class OneToMany { | ||
constructor(provider, settings) { | ||
var OneToMany = /** @class */ (function () { | ||
function OneToMany(provider, settings) { | ||
this.provider = provider; | ||
@@ -122,42 +140,63 @@ this.settings = settings; | ||
} | ||
get items() { | ||
this.load(); | ||
return this._items; | ||
} | ||
load() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (this._currentPromise != null) | ||
return this._currentPromise; | ||
if (this._items === undefined) | ||
this._items = []; | ||
return this._currentPromise = this.find().then(x => { | ||
this._items.splice(0); | ||
this._items.push(...x); | ||
return this._items; | ||
Object.defineProperty(OneToMany.prototype, "items", { | ||
get: function () { | ||
this.load(); | ||
return this._items; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
OneToMany.prototype.load = function () { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
if (this._currentPromise != null) | ||
return [2 /*return*/, this._currentPromise]; | ||
if (this._items === undefined) | ||
this._items = []; | ||
return [2 /*return*/, this._currentPromise = this.find().then(function (x) { | ||
var _a; | ||
_this._items.splice(0); | ||
(_a = _this._items).push.apply(_a, tslib_1.__spread(x)); | ||
return _this._items; | ||
})]; | ||
}); | ||
}); | ||
} | ||
reload() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
this._currentPromise = undefined; | ||
return this.load(); | ||
}; | ||
OneToMany.prototype.reload = function () { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
this._currentPromise = undefined; | ||
return [2 /*return*/, this.load()]; | ||
}); | ||
}); | ||
} | ||
find() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return this.provider.find(this.settings); | ||
}; | ||
OneToMany.prototype.find = function () { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, this.provider.find(this.settings)]; | ||
}); | ||
}); | ||
} | ||
create(item) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let r = this.provider.create(); | ||
yield remult3_1.__updateEntityBasedOnWhere(this.provider.metadata, this.settings.where, r); | ||
set_1.set(r, item); | ||
if (this.settings.create) | ||
this.settings.create(r); | ||
return r; | ||
}; | ||
OneToMany.prototype.create = function (item) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var r; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
r = this.provider.create(); | ||
return [4 /*yield*/, remult3_1.__updateEntityBasedOnWhere(this.provider.metadata, this.settings.where, r)]; | ||
case 1: | ||
_a.sent(); | ||
set_1.set(r, item); | ||
if (this.settings.create) | ||
this.settings.create(r); | ||
return [2 /*return*/, r]; | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return OneToMany; | ||
}()); | ||
exports.OneToMany = OneToMany; | ||
//# sourceMappingURL=column.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.EventSource = exports.iterateConfig = exports.Allow = exports.setControllerSettings = exports.MethodHelper = exports.ClassHelper = exports.classHelpers = exports.allEntities = exports.ServerContext = exports.Context = exports.toPromise = void 0; | ||
const tslib_1 = require("tslib"); | ||
const server_action_1 = require("./server-action"); | ||
const rest_data_provider_1 = require("./data-providers/rest-data-provider"); | ||
const RepositoryImplementation_1 = require("./remult3/RepositoryImplementation"); | ||
class HttpProviderBridgeToRestDataProviderHttpProvider { | ||
constructor(http) { | ||
var tslib_1 = require("tslib"); | ||
var server_action_1 = require("./server-action"); | ||
var rest_data_provider_1 = require("./data-providers/rest-data-provider"); | ||
var RepositoryImplementation_1 = require("./remult3/RepositoryImplementation"); | ||
var HttpProviderBridgeToRestDataProviderHttpProvider = /** @class */ (function () { | ||
function HttpProviderBridgeToRestDataProviderHttpProvider(http) { | ||
this.http = http; | ||
} | ||
post(url, data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield retry(() => toPromise(this.http.post(url, data))); | ||
HttpProviderBridgeToRestDataProviderHttpProvider.prototype.post = function (url, data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, retry(function () { return toPromise(_this.http.post(url, data)); })]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
}); | ||
} | ||
delete(url) { | ||
}; | ||
HttpProviderBridgeToRestDataProviderHttpProvider.prototype.delete = function (url) { | ||
return toPromise(this.http.delete(url)); | ||
} | ||
put(url, data) { | ||
}; | ||
HttpProviderBridgeToRestDataProviderHttpProvider.prototype.put = function (url, data) { | ||
return toPromise(this.http.put(url, data)); | ||
} | ||
get(url) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield retry(() => toPromise(this.http.get(url))); | ||
}; | ||
HttpProviderBridgeToRestDataProviderHttpProvider.prototype.get = function (url) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, retry(function () { return toPromise(_this.http.get(url)); })]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return HttpProviderBridgeToRestDataProviderHttpProvider; | ||
}()); | ||
function retry(what) { | ||
var _a; | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
while (true) { | ||
try { | ||
return yield what(); | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var err_1; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
if (!true) return [3 /*break*/, 7]; | ||
_b.label = 1; | ||
case 1: | ||
_b.trys.push([1, 3, , 6]); | ||
return [4 /*yield*/, what()]; | ||
case 2: return [2 /*return*/, _b.sent()]; | ||
case 3: | ||
err_1 = _b.sent(); | ||
if (!((_a = err_1.message) === null || _a === void 0 ? void 0 : _a.startsWith("Error occured while trying to proxy"))) return [3 /*break*/, 5]; | ||
return [4 /*yield*/, new Promise(function (res, req) { | ||
setTimeout(function () { | ||
res({}); | ||
}, 250); | ||
})]; | ||
case 4: | ||
_b.sent(); | ||
return [3 /*break*/, 0]; | ||
case 5: throw err_1; | ||
case 6: return [3 /*break*/, 0]; | ||
case 7: return [2 /*return*/]; | ||
} | ||
catch (err) { | ||
if ((_a = err.message) === null || _a === void 0 ? void 0 : _a.startsWith("Error occured while trying to proxy")) { | ||
yield new Promise((res, req) => { | ||
setTimeout(() => { | ||
res({}); | ||
}, 250); | ||
}); | ||
continue; | ||
} | ||
throw err; | ||
} | ||
} | ||
}); | ||
}); | ||
} | ||
function toPromise(p) { | ||
let r; | ||
var _this = this; | ||
var r; | ||
if (p["toPromise"] !== undefined) { | ||
@@ -58,27 +82,33 @@ r = p["toPromise"](); | ||
r = p; | ||
return r.catch((ex) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let z = yield ex; | ||
var error; | ||
if (z.error) | ||
error = z.error; | ||
else | ||
error = z.message; | ||
if (typeof error === 'string') { | ||
error = { | ||
message: error | ||
}; | ||
} | ||
var result = Object.assign(error, { | ||
// exception: ex disabled for now because JSON.stringify crashed with this | ||
return r.catch(function (ex) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var z, error, result; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, ex]; | ||
case 1: | ||
z = _a.sent(); | ||
if (z.error) | ||
error = z.error; | ||
else | ||
error = z.message; | ||
if (typeof error === 'string') { | ||
error = { | ||
message: error | ||
}; | ||
} | ||
result = Object.assign(error, { | ||
// exception: ex disabled for now because JSON.stringify crashed with this | ||
}); | ||
throw result; | ||
} | ||
}); | ||
throw result; | ||
})); | ||
}); }); | ||
} | ||
exports.toPromise = toPromise; | ||
class Context { | ||
constructor(http) { | ||
var Context = /** @class */ (function () { | ||
function Context(http) { | ||
this._backend = server_action_1.actionInfo.runningOnServer; | ||
this._userChangeEvent = new EventSource(); | ||
this.repCache = new Map(); | ||
let provider; | ||
var provider; | ||
if (http) { | ||
@@ -94,15 +124,15 @@ provider = new HttpProviderBridgeToRestDataProviderHttpProvider(http); | ||
} | ||
clearAllCache() { | ||
Context.prototype.clearAllCache = function () { | ||
this.repCache.clear(); | ||
} | ||
authenticated() { | ||
}; | ||
Context.prototype.authenticated = function () { | ||
return this.user.id !== undefined; | ||
} | ||
getCookie(name) { | ||
}; | ||
Context.prototype.getCookie = function (name) { | ||
return ''; | ||
} | ||
getHost() { | ||
}; | ||
Context.prototype.getHost = function () { | ||
return ''; | ||
} | ||
getPathInUrl() { | ||
}; | ||
Context.prototype.getPathInUrl = function () { | ||
if (this.req) | ||
@@ -113,38 +143,69 @@ return this.req.getBaseUrl(); | ||
return undefined; | ||
} | ||
getOrigin() { | ||
}; | ||
Context.prototype.getOrigin = function () { | ||
return ''; | ||
} | ||
setDataProvider(dataProvider) { | ||
}; | ||
Context.prototype.setDataProvider = function (dataProvider) { | ||
this._dataSource = dataProvider; | ||
} | ||
get backend() { | ||
return this._backend; | ||
} | ||
get user() { | ||
if (this._user === undefined) { | ||
return { | ||
id: undefined, | ||
name: '', | ||
roles: [] | ||
}; | ||
} | ||
return this._user; | ||
} | ||
get userChange() { | ||
return this._userChangeEvent.dispatcher; | ||
} | ||
setUser(info) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
this._user = info; | ||
yield this._userChangeEvent.fire(); | ||
}; | ||
Object.defineProperty(Context.prototype, "backend", { | ||
get: function () { | ||
return this._backend; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(Context.prototype, "user", { | ||
get: function () { | ||
if (this._user === undefined) { | ||
return { | ||
id: undefined, | ||
name: '', | ||
roles: [] | ||
}; | ||
} | ||
return this._user; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(Context.prototype, "userChange", { | ||
get: function () { | ||
return this._userChangeEvent.dispatcher; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Context.prototype.setUser = function (info) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
this._user = info; | ||
return [4 /*yield*/, this._userChangeEvent.fire()]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
isAllowedForInstance(instance, x) { | ||
}; | ||
Context.prototype.isAllowedForInstance = function (instance, x) { | ||
var e_1, _a; | ||
if (Array.isArray(x)) { | ||
{ | ||
for (const item of x) { | ||
if (this.isAllowedForInstance(instance, item)) | ||
return true; | ||
try { | ||
for (var x_1 = tslib_1.__values(x), x_1_1 = x_1.next(); !x_1_1.done; x_1_1 = x_1.next()) { | ||
var item = x_1_1.value; | ||
if (this.isAllowedForInstance(instance, item)) | ||
return true; | ||
} | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (x_1_1 && !x_1_1.done && (_a = x_1.return)) _a.call(x_1); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
} | ||
@@ -157,12 +218,23 @@ } | ||
return this.isAllowed(x); | ||
} | ||
isAllowed(roles) { | ||
}; | ||
Context.prototype.isAllowed = function (roles) { | ||
var e_2, _a; | ||
if (roles == undefined) | ||
return undefined; | ||
if (roles instanceof Array) { | ||
for (const role of roles) { | ||
if (this.isAllowed(role) === true) { | ||
return true; | ||
try { | ||
for (var roles_1 = tslib_1.__values(roles), roles_1_1 = roles_1.next(); !roles_1_1.done; roles_1_1 = roles_1.next()) { | ||
var role = roles_1_1.value; | ||
if (this.isAllowed(role) === true) { | ||
return true; | ||
} | ||
} | ||
} | ||
catch (e_2_1) { e_2 = { error: e_2_1 }; } | ||
finally { | ||
try { | ||
if (roles_1_1 && !roles_1_1.done && (_a = roles_1.return)) _a.call(roles_1); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
} | ||
return false; | ||
@@ -181,10 +253,10 @@ } | ||
return false; | ||
} | ||
for(entity, dataProvider) { | ||
}; | ||
Context.prototype.for = function (entity, dataProvider) { | ||
if (dataProvider === undefined) | ||
dataProvider = this._dataSource; | ||
let dpCache = this.repCache.get(dataProvider); | ||
var dpCache = this.repCache.get(dataProvider); | ||
if (!dpCache) | ||
this.repCache.set(dataProvider, dpCache = new Map()); | ||
let r = dpCache.get(entity); | ||
var r = dpCache.get(entity); | ||
if (!r) { | ||
@@ -194,71 +266,99 @@ dpCache.set(entity, r = new RepositoryImplementation_1.RepositoryImplementation(entity, this, dataProvider)); | ||
return r; | ||
} | ||
setReq(req) { | ||
}; | ||
Context.prototype.setReq = function (req) { | ||
this.req = req; | ||
this._user = req.user ? req.user : undefined; | ||
} | ||
} | ||
}; | ||
Context.apiBaseUrl = 'api'; | ||
return Context; | ||
}()); | ||
exports.Context = Context; | ||
Context.apiBaseUrl = 'api'; | ||
class ServerContext extends Context { | ||
constructor(dp) { | ||
super(); | ||
this._backend = true; | ||
var ServerContext = /** @class */ (function (_super) { | ||
tslib_1.__extends(ServerContext, _super); | ||
function ServerContext(dp) { | ||
var _this = _super.call(this) || this; | ||
_this._backend = true; | ||
if (dp) | ||
this.setDataProvider(dp); | ||
_this.setDataProvider(dp); | ||
return _this; | ||
} | ||
getHost() { | ||
ServerContext.prototype.getHost = function () { | ||
if (!this.req) | ||
return undefined; | ||
return this.req.getHeader('host'); | ||
} | ||
getPathInUrl() { | ||
}; | ||
ServerContext.prototype.getPathInUrl = function () { | ||
if (!this.req) | ||
return undefined; | ||
return this.req.getBaseUrl(); | ||
} | ||
getCookie(name) { | ||
}; | ||
ServerContext.prototype.getCookie = function (name) { | ||
var e_3, _a; | ||
if (this.req) { | ||
let cookie = this.req.getHeader('cookie'); | ||
var cookie = this.req.getHeader('cookie'); | ||
if (cookie) | ||
for (const iterator of cookie.split(';')) { | ||
let itemInfo = iterator.split('='); | ||
if (itemInfo && itemInfo[0].trim() == name) { | ||
return itemInfo[1]; | ||
try { | ||
for (var _b = tslib_1.__values(cookie.split(';')), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var iterator = _c.value; | ||
var itemInfo = iterator.split('='); | ||
if (itemInfo && itemInfo[0].trim() == name) { | ||
return itemInfo[1]; | ||
} | ||
} | ||
} | ||
catch (e_3_1) { e_3 = { error: e_3_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
} | ||
} | ||
return undefined; | ||
} | ||
getOrigin() { | ||
}; | ||
ServerContext.prototype.getOrigin = function () { | ||
if (!this.req) | ||
return undefined; | ||
return this.req.getHeader('origin'); | ||
} | ||
} | ||
}; | ||
return ServerContext; | ||
}(Context)); | ||
exports.ServerContext = ServerContext; | ||
exports.allEntities = []; | ||
exports.classHelpers = new Map(); | ||
class ClassHelper { | ||
constructor() { | ||
var ClassHelper = /** @class */ (function () { | ||
function ClassHelper() { | ||
this.methods = []; | ||
} | ||
} | ||
return ClassHelper; | ||
}()); | ||
exports.ClassHelper = ClassHelper; | ||
class MethodHelper { | ||
constructor() { | ||
var MethodHelper = /** @class */ (function () { | ||
function MethodHelper() { | ||
this.classes = new Map(); | ||
} | ||
} | ||
return MethodHelper; | ||
}()); | ||
exports.MethodHelper = MethodHelper; | ||
function setControllerSettings(target, options) { | ||
let r = target; | ||
var e_4, _a; | ||
var r = target; | ||
while (true) { | ||
let helper = exports.classHelpers.get(r); | ||
var helper = exports.classHelpers.get(r); | ||
if (helper) { | ||
for (const m of helper.methods) { | ||
m.classes.set(target, options); | ||
try { | ||
for (var _b = (e_4 = void 0, tslib_1.__values(helper.methods)), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var m = _c.value; | ||
m.classes.set(target, options); | ||
} | ||
} | ||
catch (e_4_1) { e_4 = { error: e_4_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_4) throw e_4.error; } | ||
} | ||
} | ||
let p = Object.getPrototypeOf(r.prototype); | ||
var p = Object.getPrototypeOf(r.prototype); | ||
if (p == null) | ||
@@ -270,32 +370,74 @@ break; | ||
exports.setControllerSettings = setControllerSettings; | ||
class Allow { | ||
} | ||
var Allow = /** @class */ (function () { | ||
function Allow() { | ||
} | ||
Allow.everyone = function () { return true; }; | ||
Allow.authenticated = function (context) { return context.authenticated(); }; | ||
return Allow; | ||
}()); | ||
exports.Allow = Allow; | ||
Allow.everyone = () => true; | ||
Allow.authenticated = (context) => context.authenticated(); | ||
exports.iterateConfig = { | ||
pageSize: 200 | ||
}; | ||
class EventSource { | ||
constructor() { | ||
var EventSource = /** @class */ (function () { | ||
function EventSource() { | ||
var _this = this; | ||
this.listeners = []; | ||
this.dispatcher = { | ||
observe: (what) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
this.listeners.push(what); | ||
yield what(); | ||
return () => { | ||
this.listeners = this.listeners.filter(x => x != what); | ||
}; | ||
}) | ||
observe: function (what) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
this.listeners.push(what); | ||
return [4 /*yield*/, what()]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/, function () { | ||
_this.listeners = _this.listeners.filter(function (x) { return x != what; }); | ||
}]; | ||
} | ||
}); | ||
}); } | ||
}; | ||
} | ||
fire() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
for (const l of this.listeners) { | ||
yield l(); | ||
} | ||
EventSource.prototype.fire = function () { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _a, _b, l, e_5_1; | ||
var e_5, _c; | ||
return tslib_1.__generator(this, function (_d) { | ||
switch (_d.label) { | ||
case 0: | ||
_d.trys.push([0, 5, 6, 7]); | ||
_a = tslib_1.__values(this.listeners), _b = _a.next(); | ||
_d.label = 1; | ||
case 1: | ||
if (!!_b.done) return [3 /*break*/, 4]; | ||
l = _b.value; | ||
return [4 /*yield*/, l()]; | ||
case 2: | ||
_d.sent(); | ||
_d.label = 3; | ||
case 3: | ||
_b = _a.next(); | ||
return [3 /*break*/, 1]; | ||
case 4: return [3 /*break*/, 7]; | ||
case 5: | ||
e_5_1 = _d.sent(); | ||
e_5 = { error: e_5_1 }; | ||
return [3 /*break*/, 7]; | ||
case 6: | ||
try { | ||
if (_b && !_b.done && (_c = _a.return)) _c.call(_a); | ||
} | ||
finally { if (e_5) throw e_5.error; } | ||
return [7 /*endfinally*/]; | ||
case 7: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return EventSource; | ||
}()); | ||
exports.EventSource = EventSource; | ||
//# sourceMappingURL=context.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.serializeError = exports.determineSort = exports.DataApi = void 0; | ||
const tslib_1 = require("tslib"); | ||
const filter_interfaces_1 = require("./filter/filter-interfaces"); | ||
const filter_interfaces_2 = require("./filter/filter-interfaces"); | ||
class DataApi { | ||
constructor(repository, context) { | ||
var tslib_1 = require("tslib"); | ||
var filter_interfaces_1 = require("./filter/filter-interfaces"); | ||
var filter_interfaces_2 = require("./filter/filter-interfaces"); | ||
var DataApi = /** @class */ (function () { | ||
function DataApi(repository, context) { | ||
this.repository = repository; | ||
@@ -13,143 +13,245 @@ this.context = context; | ||
} | ||
getRoute() { | ||
DataApi.prototype.getRoute = function () { | ||
return this.options.name; | ||
} | ||
get(response, id) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (this.options.allowRead == false) { | ||
response.forbidden(); | ||
return; | ||
} | ||
yield this.doOnId(response, id, (row) => tslib_1.__awaiter(this, void 0, void 0, function* () { return response.success(this.repository.getEntityRef(row).toApiJson()); })); | ||
}; | ||
DataApi.prototype.get = function (response, id) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (this.options.allowRead == false) { | ||
response.forbidden(); | ||
return [2 /*return*/]; | ||
} | ||
return [4 /*yield*/, this.doOnId(response, id, function (row) { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, response.success(this.repository.getEntityRef(row).toApiJson())]; | ||
}); }); })]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
count(response, request, filterBody) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
try { | ||
response.success({ count: +(yield this.repository.count(t => this.buildWhere(t, request, filterBody))) }); | ||
} | ||
catch (err) { | ||
response.error(err); | ||
} | ||
}; | ||
DataApi.prototype.count = function (response, request, filterBody) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _a, _b, err_1; | ||
var _c; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_d) { | ||
switch (_d.label) { | ||
case 0: | ||
_d.trys.push([0, 2, , 3]); | ||
_b = (_a = response).success; | ||
_c = {}; | ||
return [4 /*yield*/, this.repository.count(function (t) { return _this.buildWhere(t, request, filterBody); })]; | ||
case 1: | ||
_b.apply(_a, [(_c.count = +(_d.sent()), _c)]); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
err_1 = _d.sent(); | ||
response.error(err_1); | ||
return [3 /*break*/, 3]; | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
getArray(response, request, filterBody) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (this.options.allowRead == false) { | ||
response.forbidden(); | ||
return; | ||
} | ||
try { | ||
let findOptions = {}; | ||
if (this.options && this.options.get) { | ||
Object.assign(findOptions, this.options.get); | ||
}; | ||
DataApi.prototype.getArray = function (response, request, filterBody) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var findOptions, hasId_1, w, sort, dir, limit, err_2; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (this.options.allowRead == false) { | ||
response.forbidden(); | ||
return [2 /*return*/]; | ||
} | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 5, , 6]); | ||
findOptions = {}; | ||
if (this.options && this.options.get) { | ||
Object.assign(findOptions, this.options.get); | ||
} | ||
findOptions.where = function (t) { return _this.buildWhere(t, request, filterBody); }; | ||
if (!this.options.requireId) return [3 /*break*/, 3]; | ||
hasId_1 = false; | ||
return [4 /*yield*/, filter_interfaces_2.Filter.translateWhereToFilter(filter_interfaces_2.Filter.createFilterFactories(this.repository.metadata), findOptions.where)]; | ||
case 2: | ||
w = _a.sent(); | ||
if (w) { | ||
w.__applyToConsumer({ | ||
containsCaseInsensitive: function () { }, | ||
isDifferentFrom: function () { }, | ||
isEqualTo: function (col, val) { | ||
if (_this.repository.metadata.idMetadata.isIdField(col)) | ||
hasId_1 = true; | ||
}, | ||
custom: function () { }, | ||
databaseCustom: function () { }, | ||
isGreaterOrEqualTo: function () { }, | ||
isGreaterThan: function () { }, | ||
isIn: function () { }, | ||
isLessOrEqualTo: function () { }, | ||
isLessThan: function () { }, | ||
isNotNull: function () { }, | ||
isNull: function () { }, | ||
startsWith: function () { }, | ||
or: function () { } | ||
}); | ||
} | ||
if (!hasId_1) { | ||
response.forbidden(); | ||
return [2 /*return*/]; | ||
} | ||
_a.label = 3; | ||
case 3: | ||
if (request) { | ||
sort = request.get("_sort"); | ||
if (sort != undefined) { | ||
dir = request.get('_order'); | ||
findOptions.orderBy = determineSort(sort, dir); | ||
} | ||
limit = +request.get("_limit"); | ||
if (!limit) | ||
limit = 200; | ||
findOptions.limit = limit; | ||
findOptions.page = +request.get("_page"); | ||
} | ||
return [4 /*yield*/, this.repository.find(findOptions) | ||
.then(function (r) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var _a, _b; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
_b = (_a = response).success; | ||
return [4 /*yield*/, Promise.all(r.map(function (y) { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, this.repository.getEntityRef(y).toApiJson()]; | ||
}); }); }))]; | ||
case 1: | ||
_b.apply(_a, [_c.sent()]); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); })]; | ||
case 4: | ||
_a.sent(); | ||
return [3 /*break*/, 6]; | ||
case 5: | ||
err_2 = _a.sent(); | ||
response.error(err_2); | ||
return [3 /*break*/, 6]; | ||
case 6: return [2 /*return*/]; | ||
} | ||
findOptions.where = t => this.buildWhere(t, request, filterBody); | ||
if (this.options.requireId) { | ||
let hasId = false; | ||
let w = yield filter_interfaces_2.Filter.translateWhereToFilter(filter_interfaces_2.Filter.createFilterFactories(this.repository.metadata), findOptions.where); | ||
if (w) { | ||
w.__applyToConsumer({ | ||
containsCaseInsensitive: () => { }, | ||
isDifferentFrom: () => { }, | ||
isEqualTo: (col, val) => { | ||
if (this.repository.metadata.idMetadata.isIdField(col)) | ||
hasId = true; | ||
}, | ||
custom: () => { }, | ||
databaseCustom: () => { }, | ||
isGreaterOrEqualTo: () => { }, | ||
isGreaterThan: () => { }, | ||
isIn: () => { }, | ||
isLessOrEqualTo: () => { }, | ||
isLessThan: () => { }, | ||
isNotNull: () => { }, | ||
isNull: () => { }, | ||
startsWith: () => { }, | ||
or: () => { } | ||
}); | ||
} | ||
if (!hasId) { | ||
response.forbidden(); | ||
return; | ||
} | ||
} | ||
if (request) { | ||
let sort = request.get("_sort"); | ||
if (sort != undefined) { | ||
let dir = request.get('_order'); | ||
findOptions.orderBy = determineSort(sort, dir); | ||
} | ||
let limit = +request.get("_limit"); | ||
if (!limit) | ||
limit = 200; | ||
findOptions.limit = limit; | ||
findOptions.page = +request.get("_page"); | ||
} | ||
yield this.repository.find(findOptions) | ||
.then((r) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
response.success(yield Promise.all(r.map((y) => tslib_1.__awaiter(this, void 0, void 0, function* () { return this.repository.getEntityRef(y).toApiJson(); })))); | ||
})); | ||
} | ||
catch (err) { | ||
response.error(err); | ||
} | ||
}); | ||
}); | ||
} | ||
buildWhere(entity, request, filterBody) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
}; | ||
DataApi.prototype.buildWhere = function (entity, request, filterBody) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var where; | ||
if (this.options && this.options.get && this.options.get.where) | ||
where = yield filter_interfaces_2.Filter.translateWhereToFilter(entity, this.options.get.where); | ||
if (request) { | ||
where = new filter_interfaces_1.AndFilter(where, filter_interfaces_2.Filter.extractWhere(this.repository.metadata, { | ||
get: key => { | ||
let result = request.get(key); | ||
if (key == filter_interfaces_1.customUrlToken && result) | ||
return JSON.parse(result); | ||
return result; | ||
} | ||
})); | ||
} | ||
if (filterBody) | ||
where = new filter_interfaces_1.AndFilter(where, filter_interfaces_2.Filter.unpackWhere(this.repository.metadata, filterBody)); | ||
return where; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(this.options && this.options.get && this.options.get.where)) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, filter_interfaces_2.Filter.translateWhereToFilter(entity, this.options.get.where)]; | ||
case 1: | ||
where = _a.sent(); | ||
_a.label = 2; | ||
case 2: | ||
if (request) { | ||
where = new filter_interfaces_1.AndFilter(where, filter_interfaces_2.Filter.extractWhere(this.repository.metadata, { | ||
get: function (key) { | ||
var result = request.get(key); | ||
if (key == filter_interfaces_1.customUrlToken && result) | ||
return JSON.parse(result); | ||
return result; | ||
} | ||
})); | ||
} | ||
if (filterBody) | ||
where = new filter_interfaces_1.AndFilter(where, filter_interfaces_2.Filter.unpackWhere(this.repository.metadata, filterBody)); | ||
return [2 /*return*/, where]; | ||
} | ||
}); | ||
}); | ||
} | ||
doOnId(response, id, what) { | ||
}; | ||
DataApi.prototype.doOnId = function (response, id, what) { | ||
var _a, _b; | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
try { | ||
yield this.repository.find({ | ||
where: [(_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.get) === null || _b === void 0 ? void 0 : _b.where, x => this.repository.metadata.idMetadata.getIdFilter(id)] | ||
}) | ||
.then((r) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (r.length == 0) | ||
response.notFound(); | ||
else if (r.length > 1) | ||
response.error({ message: "id is not unique" }); | ||
else | ||
yield what(r[0]); | ||
})); | ||
} | ||
catch (err) { | ||
response.error(err); | ||
} | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var err_3; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
_c.trys.push([0, 2, , 3]); | ||
return [4 /*yield*/, this.repository.find({ | ||
where: [(_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.get) === null || _b === void 0 ? void 0 : _b.where, function (x) { return _this.repository.metadata.idMetadata.getIdFilter(id); }] | ||
}) | ||
.then(function (r) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(r.length == 0)) return [3 /*break*/, 1]; | ||
response.notFound(); | ||
return [3 /*break*/, 4]; | ||
case 1: | ||
if (!(r.length > 1)) return [3 /*break*/, 2]; | ||
response.error({ message: "id is not unique" }); | ||
return [3 /*break*/, 4]; | ||
case 2: return [4 /*yield*/, what(r[0])]; | ||
case 3: | ||
_a.sent(); | ||
_a.label = 4; | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); })]; | ||
case 1: | ||
_c.sent(); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
err_3 = _c.sent(); | ||
response.error(err_3); | ||
return [3 /*break*/, 3]; | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
put(response, id, body) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.doOnId(response, id, (row) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
this.repository.getEntityRef(row)._updateEntityBasedOnApi(body); | ||
if (!this._getApiSettings().allowUpdate(row)) { | ||
response.forbidden(); | ||
return; | ||
}; | ||
DataApi.prototype.put = function (response, id, body) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.doOnId(response, id, function (row) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
this.repository.getEntityRef(row)._updateEntityBasedOnApi(body); | ||
if (!this._getApiSettings().allowUpdate(row)) { | ||
response.forbidden(); | ||
return [2 /*return*/]; | ||
} | ||
return [4 /*yield*/, this.repository.getEntityRef(row).save()]; | ||
case 1: | ||
_a.sent(); | ||
response.success(this.repository.getEntityRef(row).toApiJson()); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); })]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
yield this.repository.getEntityRef(row).save(); | ||
response.success(this.repository.getEntityRef(row).toApiJson()); | ||
})); | ||
}); | ||
}); | ||
} | ||
_getApiSettings() { | ||
let options = this.repository.metadata.options; | ||
}; | ||
DataApi.prototype._getApiSettings = function () { | ||
var _this = this; | ||
var options = this.repository.metadata.options; | ||
if (options.allowApiCrud !== undefined) { | ||
@@ -168,10 +270,10 @@ if (options.allowApiDelete === undefined) | ||
allowRead: this.context.isAllowed(options.allowApiRead), | ||
allowUpdate: (e) => this.context.isAllowedForInstance(e, options.allowApiUpdate), | ||
allowDelete: (e) => this.context.isAllowedForInstance(e, options.allowApiDelete), | ||
allowInsert: (e) => this.context.isAllowedForInstance(e, options.allowApiInsert), | ||
allowUpdate: function (e) { return _this.context.isAllowedForInstance(e, options.allowApiUpdate); }, | ||
allowDelete: function (e) { return _this.context.isAllowedForInstance(e, options.allowApiDelete); }, | ||
allowInsert: function (e) { return _this.context.isAllowedForInstance(e, options.allowApiInsert); }, | ||
requireId: this.context.isAllowed(options.apiRequireId), | ||
get: { | ||
where: x => { | ||
where: function (x) { | ||
if (options.apiDataFilter) { | ||
return options.apiDataFilter(x, this.context); | ||
return options.apiDataFilter(x, _this.context); | ||
} | ||
@@ -182,41 +284,68 @@ return undefined; | ||
}; | ||
} | ||
delete(response, id) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.doOnId(response, id, (row) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (!this._getApiSettings().allowDelete(row)) { | ||
response.forbidden(); | ||
return; | ||
}; | ||
DataApi.prototype.delete = function (response, id) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.doOnId(response, id, function (row) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!this._getApiSettings().allowDelete(row)) { | ||
response.forbidden(); | ||
return [2 /*return*/]; | ||
} | ||
return [4 /*yield*/, this.repository.getEntityRef(row).delete()]; | ||
case 1: | ||
_a.sent(); | ||
response.deleted(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); })]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
yield this.repository.getEntityRef(row).delete(); | ||
response.deleted(); | ||
})); | ||
}); | ||
}); | ||
} | ||
post(response, body) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
try { | ||
let newr = this.repository.create(); | ||
this.repository.getEntityRef(newr)._updateEntityBasedOnApi(body); | ||
if (!this._getApiSettings().allowInsert(newr)) { | ||
response.forbidden(); | ||
return; | ||
}; | ||
DataApi.prototype.post = function (response, body) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var newr, err_4; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
_a.trys.push([0, 2, , 3]); | ||
newr = this.repository.create(); | ||
this.repository.getEntityRef(newr)._updateEntityBasedOnApi(body); | ||
if (!this._getApiSettings().allowInsert(newr)) { | ||
response.forbidden(); | ||
return [2 /*return*/]; | ||
} | ||
return [4 /*yield*/, this.repository.getEntityRef(newr).save()]; | ||
case 1: | ||
_a.sent(); | ||
response.created(this.repository.getEntityRef(newr).toApiJson()); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
err_4 = _a.sent(); | ||
response.error(err_4); | ||
return [3 /*break*/, 3]; | ||
case 3: return [2 /*return*/]; | ||
} | ||
yield this.repository.getEntityRef(newr).save(); | ||
response.created(this.repository.getEntityRef(newr).toApiJson()); | ||
} | ||
catch (err) { | ||
response.error(err); | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return DataApi; | ||
}()); | ||
exports.DataApi = DataApi; | ||
function determineSort(sortUrlParm, dirUrlParam) { | ||
let dirItems = []; | ||
var dirItems = []; | ||
if (dirUrlParam) | ||
dirItems = dirUrlParam.split(','); | ||
return x => { | ||
return sortUrlParm.split(',').map((name, i) => { | ||
let r = x[name.trim()]; | ||
return function (x) { | ||
return sortUrlParm.split(',').map(function (name, i) { | ||
var r = x[name.trim()]; | ||
if (i < dirItems.length && dirItems[i].toLowerCase().trim().startsWith("d")) | ||
@@ -233,3 +362,3 @@ return { field: r.field, isDescending: true }; | ||
} | ||
let x = JSON.parse(JSON.stringify(data)); | ||
var x = JSON.parse(JSON.stringify(data)); | ||
if (!x.message && !x.modelState) | ||
@@ -236,0 +365,0 @@ data = { message: data.message, stack: data.stack }; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.extractSort = void 0; | ||
const sort_1 = require("./sort"); | ||
var sort_1 = require("./sort"); | ||
function extractSort(sort) { | ||
@@ -9,7 +9,7 @@ if (sort instanceof sort_1.Sort) | ||
if (sort instanceof Array) { | ||
let r = new sort_1.Sort(); | ||
sort.forEach(i => { | ||
r.Segments.push(i); | ||
var r_1 = new sort_1.Sort(); | ||
sort.forEach(function (i) { | ||
r_1.Segments.push(i); | ||
}); | ||
return r; | ||
return r_1; | ||
} | ||
@@ -16,0 +16,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ArrayEntityDataProvider = void 0; | ||
const tslib_1 = require("tslib"); | ||
const filter_interfaces_1 = require("../filter/filter-interfaces"); | ||
const column_1 = require("../column"); | ||
const sort_1 = require("../sort"); | ||
class ArrayEntityDataProvider { | ||
constructor(entity, rows) { | ||
var tslib_1 = require("tslib"); | ||
var filter_interfaces_1 = require("../filter/filter-interfaces"); | ||
var column_1 = require("../column"); | ||
var sort_1 = require("../sort"); | ||
var ArrayEntityDataProvider = /** @class */ (function () { | ||
function ArrayEntityDataProvider(entity, rows) { | ||
this.entity = entity; | ||
@@ -15,88 +15,119 @@ this.rows = rows; | ||
} | ||
static customFilter(filter) { | ||
return new filter_interfaces_1.Filter(x => x.databaseCustom({ | ||
ArrayEntityDataProvider.customFilter = function (filter) { | ||
return new filter_interfaces_1.Filter(function (x) { return x.databaseCustom({ | ||
arrayFilter: filter | ||
})); | ||
} | ||
count(where) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let rows = this.rows; | ||
let j = 0; | ||
for (let i = 0; i < rows.length; i++) { | ||
if (!where) { | ||
j++; | ||
} | ||
else { | ||
let x = new FilterConsumerBridgeToObject(rows[i]); | ||
where.__applyToConsumer(x); | ||
if (x.ok) | ||
}); }); | ||
}; | ||
ArrayEntityDataProvider.prototype.count = function (where) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var rows, j, i, x; | ||
return tslib_1.__generator(this, function (_a) { | ||
rows = this.rows; | ||
j = 0; | ||
for (i = 0; i < rows.length; i++) { | ||
if (!where) { | ||
j++; | ||
} | ||
else { | ||
x = new FilterConsumerBridgeToObject(rows[i]); | ||
where.__applyToConsumer(x); | ||
if (x.ok) | ||
j++; | ||
} | ||
} | ||
} | ||
return j; | ||
return [2 /*return*/, j]; | ||
}); | ||
}); | ||
} | ||
find(options) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let rows = this.rows; | ||
if (options) { | ||
if (options.where) { | ||
rows = rows.filter(i => { | ||
let x = new FilterConsumerBridgeToObject(i); | ||
options.where.__applyToConsumer(x); | ||
return x.ok; | ||
}); | ||
} | ||
if (options.orderBy) { | ||
rows = rows.sort((a, b) => { | ||
let r = 0; | ||
for (let i = 0; i < options.orderBy.Segments.length; i++) { | ||
let seg = options.orderBy.Segments[i]; | ||
let left = a[seg.field.key]; | ||
let right = b[seg.field.key]; | ||
if (left > right) | ||
r = 1; | ||
else if (left < right) | ||
r = -1; | ||
if (r != 0) { | ||
if (seg.isDescending) | ||
r *= -1; | ||
return r; | ||
}; | ||
ArrayEntityDataProvider.prototype.find = function (options) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var rows; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
rows = this.rows; | ||
if (options) { | ||
if (options.where) { | ||
rows = rows.filter(function (i) { | ||
var x = new FilterConsumerBridgeToObject(i); | ||
options.where.__applyToConsumer(x); | ||
return x.ok; | ||
}); | ||
} | ||
if (options.orderBy) { | ||
rows = rows.sort(function (a, b) { | ||
var r = 0; | ||
for (var i = 0; i < options.orderBy.Segments.length; i++) { | ||
var seg = options.orderBy.Segments[i]; | ||
var left = a[seg.field.key]; | ||
var right = b[seg.field.key]; | ||
if (left > right) | ||
r = 1; | ||
else if (left < right) | ||
r = -1; | ||
if (r != 0) { | ||
if (seg.isDescending) | ||
r *= -1; | ||
return r; | ||
} | ||
} | ||
} | ||
return r; | ||
}); | ||
return r; | ||
}); | ||
} | ||
rows = pageArray(rows, options); | ||
} | ||
rows = pageArray(rows, options); | ||
if (rows) | ||
return [2 /*return*/, rows.map(function (i) { | ||
return _this.translateFromJson(i); | ||
})]; | ||
return [2 /*return*/]; | ||
}); | ||
}); | ||
}; | ||
ArrayEntityDataProvider.prototype.translateFromJson = function (row) { | ||
var e_1, _a; | ||
var result = {}; | ||
try { | ||
for (var _b = tslib_1.__values(this.entity.fields), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var col = _c.value; | ||
result[col.key] = col.valueConverter.fromJson(row[col.key]); | ||
} | ||
if (rows) | ||
return rows.map(i => { | ||
return this.translateFromJson(i); | ||
}); | ||
}); | ||
} | ||
translateFromJson(row) { | ||
let result = {}; | ||
for (const col of this.entity.fields) { | ||
result[col.key] = col.valueConverter.fromJson(row[col.key]); | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
return result; | ||
} | ||
translateToJson(row) { | ||
let result = {}; | ||
for (const col of this.entity.fields) { | ||
result[col.key] = col.valueConverter.toJson(row[col.key]); | ||
}; | ||
ArrayEntityDataProvider.prototype.translateToJson = function (row) { | ||
var e_2, _a; | ||
var result = {}; | ||
try { | ||
for (var _b = tslib_1.__values(this.entity.fields), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var col = _c.value; | ||
result[col.key] = col.valueConverter.toJson(row[col.key]); | ||
} | ||
} | ||
catch (e_2_1) { e_2 = { error: e_2_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
} | ||
return result; | ||
} | ||
idMatches(id) { | ||
return item => { | ||
let x = new FilterConsumerBridgeToObject(item); | ||
this.entity.idMetadata.getIdFilter(id).__applyToConsumer(x); | ||
}; | ||
ArrayEntityDataProvider.prototype.idMatches = function (id) { | ||
var _this = this; | ||
return function (item) { | ||
var x = new FilterConsumerBridgeToObject(item); | ||
_this.entity.idMetadata.getIdFilter(id).__applyToConsumer(x); | ||
return x.ok; | ||
}; | ||
} | ||
update(id, data) { | ||
let idMatches = this.idMatches(id); | ||
for (let i = 0; i < this.rows.length; i++) { | ||
}; | ||
ArrayEntityDataProvider.prototype.update = function (id, data) { | ||
var idMatches = this.idMatches(id); | ||
for (var i = 0; i < this.rows.length; i++) { | ||
if (idMatches(this.rows[i])) { | ||
@@ -108,6 +139,6 @@ this.rows[i] = Object.assign({}, this.rows[i], this.translateToJson(data)); | ||
throw new Error("couldn't find id to update: " + id); | ||
} | ||
delete(id) { | ||
let idMatches = this.idMatches(id); | ||
for (let i = 0; i < this.rows.length; i++) { | ||
}; | ||
ArrayEntityDataProvider.prototype.delete = function (id) { | ||
var idMatches = this.idMatches(id); | ||
for (var i = 0; i < this.rows.length; i++) { | ||
if (idMatches(this.rows[i])) { | ||
@@ -119,26 +150,37 @@ this.rows.splice(i, 1); | ||
throw new Error("couldn't find id to delete: " + id); | ||
} | ||
insert(data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let idf = this.entity.idMetadata.field; | ||
if (!(idf instanceof column_1.CompoundIdField)) { | ||
if (this.entity.options.dbAutoIncrementId) { | ||
let lastRow = yield this.find({ orderBy: new sort_1.Sort({ field: idf, isDescending: true }) }); | ||
if (lastRow.length > 0) | ||
data[idf.key] = lastRow[0][idf.key] + 1; | ||
else | ||
data[idf.key] = 1; | ||
}; | ||
ArrayEntityDataProvider.prototype.insert = function (data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var idf, lastRow, j; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
idf = this.entity.idMetadata.field; | ||
if (!!(idf instanceof column_1.CompoundIdField)) return [3 /*break*/, 3]; | ||
if (!this.entity.options.dbAutoIncrementId) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, this.find({ orderBy: new sort_1.Sort({ field: idf, isDescending: true }) })]; | ||
case 1: | ||
lastRow = _a.sent(); | ||
if (lastRow.length > 0) | ||
data[idf.key] = lastRow[0][idf.key] + 1; | ||
else | ||
data[idf.key] = 1; | ||
_a.label = 2; | ||
case 2: | ||
if (data[idf.key]) | ||
this.rows.forEach(function (i) { | ||
if (data[idf.key] == i[idf.key]) | ||
throw Error("id already exists"); | ||
}); | ||
_a.label = 3; | ||
case 3: | ||
j = this.translateToJson(data); | ||
this.rows.push(j); | ||
return [2 /*return*/, Promise.resolve(this.translateFromJson(j))]; | ||
} | ||
if (data[idf.key]) | ||
this.rows.forEach(i => { | ||
if (data[idf.key] == i[idf.key]) | ||
throw Error("id already exists"); | ||
}); | ||
} | ||
let j = this.translateToJson(data); | ||
this.rows.push(j); | ||
return Promise.resolve(this.translateFromJson(j)); | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return ArrayEntityDataProvider; | ||
}()); | ||
exports.ArrayEntityDataProvider = ArrayEntityDataProvider; | ||
@@ -150,3 +192,3 @@ function pageArray(rows, options) { | ||
return rows; | ||
let page = 1; | ||
var page = 1; | ||
if (options.page) | ||
@@ -156,16 +198,16 @@ page = options.page; | ||
page = 1; | ||
let x = 0; | ||
return rows.filter(i => { | ||
var x = 0; | ||
return rows.filter(function (i) { | ||
x++; | ||
let max = page * options.limit; | ||
let min = max - options.limit; | ||
var max = page * options.limit; | ||
var min = max - options.limit; | ||
return x > min && x <= max; | ||
}); | ||
} | ||
class FilterConsumerBridgeToObject { | ||
constructor(row) { | ||
var FilterConsumerBridgeToObject = /** @class */ (function () { | ||
function FilterConsumerBridgeToObject(row) { | ||
this.row = row; | ||
this.ok = true; | ||
} | ||
databaseCustom(databaseCustom) { | ||
FilterConsumerBridgeToObject.prototype.databaseCustom = function (databaseCustom) { | ||
if (databaseCustom && databaseCustom.arrayFilter) { | ||
@@ -175,58 +217,80 @@ if (!databaseCustom.arrayFilter(this.row)) | ||
} | ||
} | ||
custom(customItem) { | ||
}; | ||
FilterConsumerBridgeToObject.prototype.custom = function (customItem) { | ||
throw new Error('Custom Filter should be translated before it gets here'); | ||
} | ||
or(orElements) { | ||
for (const element of orElements) { | ||
let filter = new FilterConsumerBridgeToObject(this.row); | ||
element.__applyToConsumer(filter); | ||
if (filter.ok) { | ||
return; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.or = function (orElements) { | ||
var e_3, _a; | ||
try { | ||
for (var orElements_1 = tslib_1.__values(orElements), orElements_1_1 = orElements_1.next(); !orElements_1_1.done; orElements_1_1 = orElements_1.next()) { | ||
var element = orElements_1_1.value; | ||
var filter = new FilterConsumerBridgeToObject(this.row); | ||
element.__applyToConsumer(filter); | ||
if (filter.ok) { | ||
return; | ||
} | ||
} | ||
} | ||
catch (e_3_1) { e_3 = { error: e_3_1 }; } | ||
finally { | ||
try { | ||
if (orElements_1_1 && !orElements_1_1.done && (_a = orElements_1.return)) _a.call(orElements_1); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
} | ||
this.ok = false; | ||
} | ||
isNull(col) { | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isNull = function (col) { | ||
if (this.row[col.key] != null) | ||
this.ok = false; | ||
} | ||
isNotNull(col) { | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isNotNull = function (col) { | ||
if (this.row[col.key] == null) | ||
this.ok = false; | ||
} | ||
isIn(col, val) { | ||
for (const v of val) { | ||
if (this.row[col.key] == col.valueConverter.toJson(v)) { | ||
return; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isIn = function (col, val) { | ||
var e_4, _a; | ||
try { | ||
for (var val_1 = tslib_1.__values(val), val_1_1 = val_1.next(); !val_1_1.done; val_1_1 = val_1.next()) { | ||
var v = val_1_1.value; | ||
if (this.row[col.key] == col.valueConverter.toJson(v)) { | ||
return; | ||
} | ||
} | ||
} | ||
catch (e_4_1) { e_4 = { error: e_4_1 }; } | ||
finally { | ||
try { | ||
if (val_1_1 && !val_1_1.done && (_a = val_1.return)) _a.call(val_1); | ||
} | ||
finally { if (e_4) throw e_4.error; } | ||
} | ||
this.ok = false; | ||
} | ||
isEqualTo(col, val) { | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isEqualTo = function (col, val) { | ||
if (this.row[col.key] != col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
} | ||
isDifferentFrom(col, val) { | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isDifferentFrom = function (col, val) { | ||
if (this.row[col.key] == col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
} | ||
isGreaterOrEqualTo(col, val) { | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isGreaterOrEqualTo = function (col, val) { | ||
if (this.row[col.key] < col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
} | ||
isGreaterThan(col, val) { | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isGreaterThan = function (col, val) { | ||
if (this.row[col.key] <= col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
} | ||
isLessOrEqualTo(col, val) { | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isLessOrEqualTo = function (col, val) { | ||
if (this.row[col.key] > col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
} | ||
isLessThan(col, val) { | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isLessThan = function (col, val) { | ||
if (this.row[col.key] >= col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
} | ||
containsCaseInsensitive(col, val) { | ||
let v = this.row[col.key]; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.containsCaseInsensitive = function (col, val) { | ||
var v = this.row[col.key]; | ||
if (!v) { | ||
@@ -236,3 +300,3 @@ this.ok = false; | ||
} | ||
let s = '' + v; | ||
var s = '' + v; | ||
if (val) | ||
@@ -244,5 +308,5 @@ val = col.valueConverter.toJson(val); | ||
this.ok = false; | ||
} | ||
startsWith(col, val) { | ||
let v = this.row[col.key]; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.startsWith = function (col, val) { | ||
var v = this.row[col.key]; | ||
if (!v) { | ||
@@ -252,7 +316,8 @@ this.ok = false; | ||
} | ||
let s = '' + v; | ||
var s = '' + v; | ||
if (s.indexOf(col.valueConverter.toJson(val)) != 0) | ||
this.ok = false; | ||
} | ||
} | ||
}; | ||
return FilterConsumerBridgeToObject; | ||
}()); | ||
//# sourceMappingURL=array-entity-data-provider.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.InMemoryDataProvider = void 0; | ||
const tslib_1 = require("tslib"); | ||
const array_entity_data_provider_1 = require("./array-entity-data-provider"); | ||
class InMemoryDataProvider { | ||
constructor() { | ||
var tslib_1 = require("tslib"); | ||
var array_entity_data_provider_1 = require("./array-entity-data-provider"); | ||
var InMemoryDataProvider = /** @class */ (function () { | ||
function InMemoryDataProvider() { | ||
this.rows = {}; | ||
} | ||
transaction(action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield action(this); | ||
InMemoryDataProvider.prototype.transaction = function (action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, action(this)]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
getEntityDataProvider(entity) { | ||
let name = entity.key; | ||
}; | ||
InMemoryDataProvider.prototype.getEntityDataProvider = function (entity) { | ||
var name = entity.key; | ||
if (!this.rows[name]) | ||
this.rows[name] = []; | ||
return new array_entity_data_provider_1.ArrayEntityDataProvider(entity, this.rows[name]); | ||
} | ||
toString() { return "InMemoryDataProvider"; } | ||
} | ||
}; | ||
InMemoryDataProvider.prototype.toString = function () { return "InMemoryDataProvider"; }; | ||
return InMemoryDataProvider; | ||
}()); | ||
exports.InMemoryDataProvider = InMemoryDataProvider; | ||
//# sourceMappingURL=in-memory-database.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.JsonDataProvider = void 0; | ||
const tslib_1 = require("tslib"); | ||
const array_entity_data_provider_1 = require("./array-entity-data-provider"); | ||
class JsonDataProvider { | ||
constructor(storage) { | ||
var tslib_1 = require("tslib"); | ||
var array_entity_data_provider_1 = require("./array-entity-data-provider"); | ||
var JsonDataProvider = /** @class */ (function () { | ||
function JsonDataProvider(storage) { | ||
this.storage = storage; | ||
} | ||
getEntityDataProvider(entity) { | ||
JsonDataProvider.prototype.getEntityDataProvider = function (entity) { | ||
return new JsonEntityDataProvider(entity, this.storage); | ||
} | ||
transaction(action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield action(this); | ||
}; | ||
JsonDataProvider.prototype.transaction = function (action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, action(this)]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return JsonDataProvider; | ||
}()); | ||
exports.JsonDataProvider = JsonDataProvider; | ||
class JsonEntityDataProvider { | ||
constructor(entity, helper) { | ||
var JsonEntityDataProvider = /** @class */ (function () { | ||
function JsonEntityDataProvider(entity, helper) { | ||
this.entity = entity; | ||
@@ -26,40 +34,57 @@ this.helper = helper; | ||
} | ||
loadEntityData(what) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let data = []; | ||
let dbName = yield this.entity.getDbName(); | ||
let s = this.helper.getItem(dbName); | ||
if (s) | ||
data = JSON.parse(s); | ||
let dp = new array_entity_data_provider_1.ArrayEntityDataProvider(this.entity, data); | ||
return what(dp, () => this.helper.setItem(dbName, JSON.stringify(data, undefined, 2))); | ||
JsonEntityDataProvider.prototype.loadEntityData = function (what) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var data, dbName, s, dp; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
data = []; | ||
return [4 /*yield*/, this.entity.getDbName()]; | ||
case 1: | ||
dbName = _a.sent(); | ||
s = this.helper.getItem(dbName); | ||
if (s) | ||
data = JSON.parse(s); | ||
dp = new array_entity_data_provider_1.ArrayEntityDataProvider(this.entity, data); | ||
return [2 /*return*/, what(dp, function () { return _this.helper.setItem(dbName, JSON.stringify(data, undefined, 2)); })]; | ||
} | ||
}); | ||
}); | ||
} | ||
find(options) { | ||
return this.p = this.p.then(() => this.loadEntityData((dp, save) => dp.find(options))); | ||
} | ||
count(where) { | ||
return this.p = this.p.then(() => this.loadEntityData((dp, save) => dp.count(where))); | ||
} | ||
update(id, data) { | ||
return this.p = this.p.then(() => this.loadEntityData((dp, save) => dp.update(id, data).then(x => { | ||
}; | ||
JsonEntityDataProvider.prototype.find = function (options) { | ||
var _this = this; | ||
return this.p = this.p.then(function () { return _this.loadEntityData(function (dp, save) { return dp.find(options); }); }); | ||
}; | ||
JsonEntityDataProvider.prototype.count = function (where) { | ||
var _this = this; | ||
return this.p = this.p.then(function () { return _this.loadEntityData(function (dp, save) { return dp.count(where); }); }); | ||
}; | ||
JsonEntityDataProvider.prototype.update = function (id, data) { | ||
var _this = this; | ||
return this.p = this.p.then(function () { return _this.loadEntityData(function (dp, save) { return dp.update(id, data).then(function (x) { | ||
save(); | ||
return x; | ||
}))); | ||
} | ||
delete(id) { | ||
return this.p = this.p.then(() => this.loadEntityData((dp, save) => dp.delete(id).then(x => { | ||
}); }); }); | ||
}; | ||
JsonEntityDataProvider.prototype.delete = function (id) { | ||
var _this = this; | ||
return this.p = this.p.then(function () { return _this.loadEntityData(function (dp, save) { return dp.delete(id).then(function (x) { | ||
save(); | ||
return x; | ||
}))); | ||
} | ||
insert(data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return this.p = this.p.then(() => this.loadEntityData((dp, save) => dp.insert(data).then(x => { | ||
save(); | ||
return x; | ||
}))); | ||
}); }); }); | ||
}; | ||
JsonEntityDataProvider.prototype.insert = function (data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
return [2 /*return*/, this.p = this.p.then(function () { return _this.loadEntityData(function (dp, save) { return dp.insert(data).then(function (x) { | ||
save(); | ||
return x; | ||
}); }); })]; | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return JsonEntityDataProvider; | ||
}()); | ||
//# sourceMappingURL=json-data-provider.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.addFilterToUrlAndReturnTrueIfSuccessful = exports.RestDataProviderHttpProviderUsingFetch = exports.RestDataProvider = void 0; | ||
const tslib_1 = require("tslib"); | ||
const urlBuilder_1 = require("../../urlBuilder"); | ||
const filter_interfaces_1 = require("../filter/filter-interfaces"); | ||
class RestDataProvider { | ||
constructor(url, http) { | ||
var tslib_1 = require("tslib"); | ||
var urlBuilder_1 = require("../../urlBuilder"); | ||
var filter_interfaces_1 = require("../filter/filter-interfaces"); | ||
var RestDataProvider = /** @class */ (function () { | ||
function RestDataProvider(url, http) { | ||
this.url = url; | ||
@@ -13,14 +13,17 @@ this.http = http; | ||
} | ||
getEntityDataProvider(entity) { | ||
RestDataProvider.prototype.getEntityDataProvider = function (entity) { | ||
return new RestEntityDataProvider(this.url + '/' + entity.key, this.http, entity); | ||
} | ||
transaction(action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
throw new Error("Method not implemented."); | ||
}; | ||
RestDataProvider.prototype.transaction = function (action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
throw new Error("Method not implemented."); | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return RestDataProvider; | ||
}()); | ||
exports.RestDataProvider = RestDataProvider; | ||
class RestEntityDataProvider { | ||
constructor(url, http, entity) { | ||
var RestEntityDataProvider = /** @class */ (function () { | ||
function RestEntityDataProvider(url, http, entity) { | ||
this.url = url; | ||
@@ -30,35 +33,61 @@ this.http = http; | ||
} | ||
translateFromJson(row) { | ||
let result = {}; | ||
for (const col of this.entity.fields) { | ||
result[col.key] = col.valueConverter.fromJson(row[col.key]); | ||
RestEntityDataProvider.prototype.translateFromJson = function (row) { | ||
var e_1, _a; | ||
var result = {}; | ||
try { | ||
for (var _b = tslib_1.__values(this.entity.fields), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var col = _c.value; | ||
result[col.key] = col.valueConverter.fromJson(row[col.key]); | ||
} | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
return result; | ||
} | ||
translateToJson(row) { | ||
let result = {}; | ||
for (const col of this.entity.fields) { | ||
result[col.key] = col.valueConverter.toJson(row[col.key]); | ||
}; | ||
RestEntityDataProvider.prototype.translateToJson = function (row) { | ||
var e_2, _a; | ||
var result = {}; | ||
try { | ||
for (var _b = tslib_1.__values(this.entity.fields), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var col = _c.value; | ||
result[col.key] = col.valueConverter.toJson(row[col.key]); | ||
} | ||
} | ||
catch (e_2_1) { e_2 = { error: e_2_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
} | ||
return result; | ||
} | ||
count(where) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let url = new urlBuilder_1.UrlBuilder(this.url); | ||
url.add("__action", "count"); | ||
let filterObject; | ||
if (where) { | ||
filterObject = filter_interfaces_1.Filter.packToRawWhere(where); | ||
if (addFilterToUrlAndReturnTrueIfSuccessful(filterObject, url)) | ||
filterObject = undefined; | ||
} | ||
if (filterObject) | ||
return this.http.post(url.url, filterObject).then(r => +(r.count)); | ||
else | ||
return this.http.get(url.url).then(r => +(r.count)); | ||
}; | ||
RestEntityDataProvider.prototype.count = function (where) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var url, filterObject; | ||
return tslib_1.__generator(this, function (_a) { | ||
url = new urlBuilder_1.UrlBuilder(this.url); | ||
url.add("__action", "count"); | ||
if (where) { | ||
filterObject = filter_interfaces_1.Filter.packToRawWhere(where); | ||
if (addFilterToUrlAndReturnTrueIfSuccessful(filterObject, url)) | ||
filterObject = undefined; | ||
} | ||
if (filterObject) | ||
return [2 /*return*/, this.http.post(url.url, filterObject).then(function (r) { return +(r.count); })]; | ||
else | ||
return [2 /*return*/, this.http.get(url.url).then(function (r) { return +(r.count); })]; | ||
return [2 /*return*/]; | ||
}); | ||
}); | ||
} | ||
find(options) { | ||
let url = new urlBuilder_1.UrlBuilder(this.url); | ||
let filterObject; | ||
}; | ||
RestEntityDataProvider.prototype.find = function (options) { | ||
var _this = this; | ||
var url = new urlBuilder_1.UrlBuilder(this.url); | ||
var filterObject; | ||
if (options) { | ||
@@ -71,14 +100,14 @@ if (options.where) { | ||
if (options.orderBy && options.orderBy.Segments) { | ||
let sort = ''; | ||
let order = ''; | ||
options.orderBy.Segments.forEach(c => { | ||
if (sort.length > 0) { | ||
sort += ","; | ||
order += ","; | ||
var sort_1 = ''; | ||
var order_1 = ''; | ||
options.orderBy.Segments.forEach(function (c) { | ||
if (sort_1.length > 0) { | ||
sort_1 += ","; | ||
order_1 += ","; | ||
} | ||
sort += c.field.key; | ||
order += c.isDescending ? "desc" : "asc"; | ||
sort_1 += c.field.key; | ||
order_1 += c.isDescending ? "desc" : "asc"; | ||
}); | ||
url.add('_sort', sort); | ||
url.add('_order', order); | ||
url.add('_sort', sort_1); | ||
url.add('_order', order_1); | ||
} | ||
@@ -94,33 +123,36 @@ if (options.limit) | ||
url.add("__action", "get"); | ||
return this.http.post(url.url, filterObject).then(x => x.map(y => this.translateFromJson(y))); | ||
return this.http.post(url.url, filterObject).then(function (x) { return x.map(function (y) { return _this.translateFromJson(y); }); }); | ||
} | ||
else | ||
return this.http.get(url.url).then(x => x.map(y => this.translateFromJson(y))); | ||
return this.http.get(url.url).then(function (x) { return x.map(function (y) { return _this.translateFromJson(y); }); }); | ||
; | ||
} | ||
update(id, data) { | ||
return this.http.put(this.url + '/' + encodeURIComponent(id), this.translateToJson(data)).then(y => this.translateFromJson(y)); | ||
} | ||
delete(id) { | ||
}; | ||
RestEntityDataProvider.prototype.update = function (id, data) { | ||
var _this = this; | ||
return this.http.put(this.url + '/' + encodeURIComponent(id), this.translateToJson(data)).then(function (y) { return _this.translateFromJson(y); }); | ||
}; | ||
RestEntityDataProvider.prototype.delete = function (id) { | ||
return this.http.delete(this.url + '/' + encodeURIComponent(id)); | ||
} | ||
insert(data) { | ||
return this.http.post(this.url, this.translateToJson(data)).then(y => this.translateFromJson(y)); | ||
} | ||
} | ||
}; | ||
RestEntityDataProvider.prototype.insert = function (data) { | ||
var _this = this; | ||
return this.http.post(this.url, this.translateToJson(data)).then(function (y) { return _this.translateFromJson(y); }); | ||
}; | ||
return RestEntityDataProvider; | ||
}()); | ||
function JsonContent(add) { | ||
add('Content-type', "application/json"); | ||
} | ||
class RestDataProviderHttpProviderUsingFetch { | ||
constructor(addRequestHeader) { | ||
var RestDataProviderHttpProviderUsingFetch = /** @class */ (function () { | ||
function RestDataProviderHttpProviderUsingFetch(addRequestHeader) { | ||
this.addRequestHeader = addRequestHeader; | ||
if (!addRequestHeader) | ||
this.addRequestHeader = () => { }; | ||
this.addRequestHeader = function () { }; | ||
} | ||
get(url) { | ||
return myFetch(url, undefined, this.addRequestHeader).then(r => { | ||
RestDataProviderHttpProviderUsingFetch.prototype.get = function (url) { | ||
return myFetch(url, undefined, this.addRequestHeader).then(function (r) { | ||
return r; | ||
}); | ||
} | ||
put(url, data) { | ||
}; | ||
RestDataProviderHttpProviderUsingFetch.prototype.put = function (url, data) { | ||
return myFetch(url, { | ||
@@ -130,9 +162,9 @@ method: 'put', | ||
}, this.addRequestHeader, JsonContent); | ||
} | ||
delete(url) { | ||
let h = new Headers(); | ||
this.addRequestHeader((name, value) => h.append(name, value)); | ||
}; | ||
RestDataProviderHttpProviderUsingFetch.prototype.delete = function (url) { | ||
var h = new Headers(); | ||
this.addRequestHeader(function (name, value) { return h.append(name, value); }); | ||
return fetch(url, { method: 'delete', credentials: 'include' }).then(onSuccess, onError); | ||
} | ||
post(url, data) { | ||
}; | ||
RestDataProviderHttpProviderUsingFetch.prototype.post = function (url, data) { | ||
return myFetch(url, { | ||
@@ -142,6 +174,12 @@ method: 'post', | ||
}, this.addRequestHeader, JsonContent); | ||
}; | ||
return RestDataProviderHttpProviderUsingFetch; | ||
}()); | ||
exports.RestDataProviderHttpProviderUsingFetch = RestDataProviderHttpProviderUsingFetch; | ||
function myFetch(url, init) { | ||
var _this = this; | ||
var addRequestHeader = []; | ||
for (var _i = 2; _i < arguments.length; _i++) { | ||
addRequestHeader[_i - 2] = arguments[_i]; | ||
} | ||
} | ||
exports.RestDataProviderHttpProviderUsingFetch = RestDataProviderHttpProviderUsingFetch; | ||
function myFetch(url, init, ...addRequestHeader) { | ||
if (!init) | ||
@@ -152,11 +190,18 @@ init = {}; | ||
var h = init.headers; | ||
addRequestHeader.forEach(x => x((n, v) => h.append(n, v))); | ||
addRequestHeader.forEach(function (x) { return x(function (n, v) { return h.append(n, v); }); }); | ||
init.credentials = 'include'; | ||
return fetch(url, init).then(response => { | ||
return fetch(url, init).then(function (response) { | ||
return onSuccess(response); | ||
}).catch((error) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let r = yield error; | ||
console.log(r); | ||
throw r; | ||
})); | ||
}).catch(function (error) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var r; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, error]; | ||
case 1: | ||
r = _a.sent(); | ||
console.log(r); | ||
throw r; | ||
} | ||
}); | ||
}); }); | ||
} | ||
@@ -169,7 +214,7 @@ function onSuccess(response) { | ||
else { | ||
throw response.json().then(x => { | ||
throw response.json().then(function (x) { | ||
if (!x.message) | ||
x.message = response.statusText; | ||
return x; | ||
}).catch(() => { | ||
}).catch(function () { | ||
throw { | ||
@@ -187,5 +232,5 @@ message: response.statusText, | ||
function addFilterToUrlAndReturnTrueIfSuccessful(filter, url) { | ||
for (const key in filter) { | ||
for (var key in filter) { | ||
if (Object.prototype.hasOwnProperty.call(filter, key)) { | ||
const element = filter[key]; | ||
var element = filter[key]; | ||
if (Array.isArray(element)) { | ||
@@ -199,5 +244,5 @@ if (element.length > 0 && typeof element[0] === 'object') | ||
} | ||
for (const key in filter) { | ||
var _loop_1 = function (key) { | ||
if (Object.prototype.hasOwnProperty.call(filter, key)) { | ||
const element = filter[key]; | ||
var element = filter[key]; | ||
if (Array.isArray(element)) { | ||
@@ -207,3 +252,3 @@ if (key.endsWith("_in")) | ||
else | ||
element.forEach(e => url.add(key, e)); | ||
element.forEach(function (e) { return url.add(key, e); }); | ||
} | ||
@@ -215,2 +260,5 @@ else if (key == filter_interfaces_1.customUrlToken) | ||
} | ||
}; | ||
for (var key in filter) { | ||
_loop_1(key); | ||
} | ||
@@ -217,0 +265,0 @@ return true; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isDbReadonly = exports.SqlDatabase = void 0; | ||
const tslib_1 = require("tslib"); | ||
const column_1 = require("../column"); | ||
const filter_consumer_bridge_to_sql_request_1 = require("../filter/filter-consumer-bridge-to-sql-request"); | ||
const filter_interfaces_1 = require("../filter/filter-interfaces"); | ||
const sort_1 = require("../sort"); | ||
var tslib_1 = require("tslib"); | ||
var column_1 = require("../column"); | ||
var filter_consumer_bridge_to_sql_request_1 = require("../filter/filter-consumer-bridge-to-sql-request"); | ||
var filter_interfaces_1 = require("../filter/filter-interfaces"); | ||
var sort_1 = require("../sort"); | ||
// @dynamic | ||
class SqlDatabase { | ||
constructor(sql) { | ||
var SqlDatabase = /** @class */ (function () { | ||
function SqlDatabase(sql) { | ||
this.sql = sql; | ||
this.createdEntities = []; | ||
} | ||
createCommand() { | ||
SqlDatabase.prototype.createCommand = function () { | ||
return new LogSQLCommand(this.sql.createCommand(), SqlDatabase.LogToConsole); | ||
} | ||
execute(sql) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield this.createCommand().execute(sql); | ||
}; | ||
SqlDatabase.prototype.execute = function (sql) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.createCommand().execute(sql)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
}); | ||
} | ||
getEntityDataProvider(entity) { | ||
return new ActualSQLServerDataProvider(entity, this, () => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (this.createdEntities.indexOf(yield entity.getDbName()) < 0) { | ||
this.createdEntities.push(yield entity.getDbName()); | ||
yield this.sql.entityIsUsedForTheFirstTime(entity); | ||
} | ||
}), this.sql); | ||
} | ||
transaction(action) { | ||
return this.sql.transaction((x) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let completed = false; | ||
try { | ||
yield action(new SqlDatabase({ | ||
createCommand: () => { | ||
let c = x.createCommand(); | ||
return { | ||
addParameterAndReturnSqlToken: x => c.addParameterAndReturnSqlToken(x), | ||
execute: (sql) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (completed) | ||
throw "can't run a command after the transaction was completed"; | ||
return c.execute(sql); | ||
}) | ||
}; | ||
}, | ||
getLimitSqlSyntax: this.sql.getLimitSqlSyntax, | ||
entityIsUsedForTheFirstTime: y => x.entityIsUsedForTheFirstTime(y), | ||
transaction: z => x.transaction(z), | ||
insertAndReturnAutoIncrementId: x.insertAndReturnAutoIncrementId | ||
})); | ||
} | ||
finally { | ||
completed = true; | ||
} | ||
})); | ||
} | ||
static customFilter(build) { | ||
return new filter_interfaces_1.Filter(x => x.databaseCustom({ | ||
}; | ||
SqlDatabase.prototype.getEntityDataProvider = function (entity) { | ||
var _this = this; | ||
return new ActualSQLServerDataProvider(entity, this, function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var _a, _b, _c, _d; | ||
return tslib_1.__generator(this, function (_e) { | ||
switch (_e.label) { | ||
case 0: | ||
_b = (_a = this.createdEntities).indexOf; | ||
return [4 /*yield*/, entity.getDbName()]; | ||
case 1: | ||
if (!(_b.apply(_a, [_e.sent()]) < 0)) return [3 /*break*/, 4]; | ||
_d = (_c = this.createdEntities).push; | ||
return [4 /*yield*/, entity.getDbName()]; | ||
case 2: | ||
_d.apply(_c, [_e.sent()]); | ||
return [4 /*yield*/, this.sql.entityIsUsedForTheFirstTime(entity)]; | ||
case 3: | ||
_e.sent(); | ||
_e.label = 4; | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }, this.sql); | ||
}; | ||
SqlDatabase.prototype.transaction = function (action) { | ||
var _this = this; | ||
return this.sql.transaction(function (x) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var completed; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
completed = false; | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, , 3, 4]); | ||
return [4 /*yield*/, action(new SqlDatabase({ | ||
createCommand: function () { | ||
var c = x.createCommand(); | ||
return { | ||
addParameterAndReturnSqlToken: function (x) { return c.addParameterAndReturnSqlToken(x); }, | ||
execute: function (sql) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
if (completed) | ||
throw "can't run a command after the transaction was completed"; | ||
return [2 /*return*/, c.execute(sql)]; | ||
}); | ||
}); } | ||
}; | ||
}, | ||
getLimitSqlSyntax: this.sql.getLimitSqlSyntax, | ||
entityIsUsedForTheFirstTime: function (y) { return x.entityIsUsedForTheFirstTime(y); }, | ||
transaction: function (z) { return x.transaction(z); }, | ||
insertAndReturnAutoIncrementId: x.insertAndReturnAutoIncrementId | ||
}))]; | ||
case 2: | ||
_a.sent(); | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
completed = true; | ||
return [7 /*endfinally*/]; | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
}; | ||
SqlDatabase.customFilter = function (build) { | ||
return new filter_interfaces_1.Filter(function (x) { return x.databaseCustom({ | ||
buildSql: build | ||
})); | ||
} | ||
} | ||
}); }); | ||
}; | ||
SqlDatabase.LogToConsole = false; | ||
SqlDatabase.durationThreshold = 0; | ||
return SqlDatabase; | ||
}()); | ||
exports.SqlDatabase = SqlDatabase; | ||
SqlDatabase.LogToConsole = false; | ||
SqlDatabase.durationThreshold = 0; | ||
class LogSQLCommand { | ||
constructor(origin, allQueries) { | ||
var LogSQLCommand = /** @class */ (function () { | ||
function LogSQLCommand(origin, allQueries) { | ||
this.origin = origin; | ||
@@ -73,33 +110,42 @@ this.allQueries = allQueries; | ||
} | ||
addParameterAndReturnSqlToken(val) { | ||
let r = this.origin.addParameterAndReturnSqlToken(val); | ||
LogSQLCommand.prototype.addParameterAndReturnSqlToken = function (val) { | ||
var r = this.origin.addParameterAndReturnSqlToken(val); | ||
this.args[r] = val; | ||
return r; | ||
} | ||
execute(sql) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
try { | ||
let start = new Date(); | ||
let r = yield this.origin.execute(sql); | ||
if (this.allQueries) { | ||
var d = new Date().valueOf() - start.valueOf(); | ||
if (d > SqlDatabase.durationThreshold) { | ||
console.log('Query:', sql); | ||
console.log("Arguments:", this.args); | ||
console.log("Duration", d / 1000); | ||
} | ||
}; | ||
LogSQLCommand.prototype.execute = function (sql) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var start, r, d, err_1; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
_a.trys.push([0, 2, , 3]); | ||
start = new Date(); | ||
return [4 /*yield*/, this.origin.execute(sql)]; | ||
case 1: | ||
r = _a.sent(); | ||
if (this.allQueries) { | ||
d = new Date().valueOf() - start.valueOf(); | ||
if (d > SqlDatabase.durationThreshold) { | ||
console.log('Query:', sql); | ||
console.log("Arguments:", this.args); | ||
console.log("Duration", d / 1000); | ||
} | ||
} | ||
return [2 /*return*/, r]; | ||
case 2: | ||
err_1 = _a.sent(); | ||
console.error('Error:', err_1); | ||
console.error('Query:', sql); | ||
console.error("Arguments", this.args); | ||
throw err_1; | ||
case 3: return [2 /*return*/]; | ||
} | ||
return r; | ||
} | ||
catch (err) { | ||
console.error('Error:', err); | ||
console.error('Query:', sql); | ||
console.error("Arguments", this.args); | ||
throw err; | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
class ActualSQLServerDataProvider { | ||
constructor(entity, sql, iAmUsed, strategy) { | ||
}; | ||
return LogSQLCommand; | ||
}()); | ||
var ActualSQLServerDataProvider = /** @class */ (function () { | ||
function ActualSQLServerDataProvider(entity, sql, iAmUsed, strategy) { | ||
this.entity = entity; | ||
@@ -110,54 +156,125 @@ this.sql = sql; | ||
} | ||
count(where) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.iAmUsed(); | ||
let select = 'select count(*) count from ' + (yield this.entity.getDbName()); | ||
let r = this.sql.createCommand(); | ||
if (where) { | ||
let wc = new filter_consumer_bridge_to_sql_request_1.FilterConsumerBridgeToSqlRequest(r); | ||
where.__applyToConsumer(wc); | ||
select += yield wc.resolveWhere(); | ||
} | ||
return r.execute(select).then(r => { | ||
return +r.rows[0].count; | ||
ActualSQLServerDataProvider.prototype.count = function (where) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var select, _a, r, wc, _b; | ||
return tslib_1.__generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: return [4 /*yield*/, this.iAmUsed()]; | ||
case 1: | ||
_c.sent(); | ||
_a = 'select count(*) count from '; | ||
return [4 /*yield*/, this.entity.getDbName()]; | ||
case 2: | ||
select = _a + (_c.sent()); | ||
r = this.sql.createCommand(); | ||
if (!where) return [3 /*break*/, 4]; | ||
wc = new filter_consumer_bridge_to_sql_request_1.FilterConsumerBridgeToSqlRequest(r); | ||
where.__applyToConsumer(wc); | ||
_b = select; | ||
return [4 /*yield*/, wc.resolveWhere()]; | ||
case 3: | ||
select = _b + _c.sent(); | ||
_c.label = 4; | ||
case 4: return [2 /*return*/, r.execute(select).then(function (r) { | ||
return +r.rows[0].count; | ||
})]; | ||
} | ||
}); | ||
}); | ||
} | ||
find(options) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.iAmUsed(); | ||
let select = 'select '; | ||
let colKeys = []; | ||
for (const x of this.entity.fields) { | ||
if (x.isServerExpression) { | ||
} | ||
else { | ||
if (colKeys.length > 0) | ||
select += ', '; | ||
select += yield x.getDbName(); | ||
colKeys.push(x); | ||
} | ||
} | ||
select += '\n from ' + (yield this.entity.getDbName()); | ||
let r = this.sql.createCommand(); | ||
if (options) { | ||
if (options.where) { | ||
let where = new filter_consumer_bridge_to_sql_request_1.FilterConsumerBridgeToSqlRequest(r); | ||
options.where.__applyToConsumer(where); | ||
select += yield where.resolveWhere(); | ||
} | ||
if (options.limit) { | ||
options.orderBy = sort_1.Sort.createUniqueSort(this.entity, x => { var _a; return (_a = options.orderBy) === null || _a === void 0 ? void 0 : _a.Segments; }); | ||
} | ||
if (options.orderBy) { | ||
let first = true; | ||
let segs = []; | ||
for (const s of options.orderBy.Segments) { | ||
if (s.field instanceof column_1.CompoundIdField) { | ||
segs.push(...s.field.fields.map(c => ({ field: c, isDescending: s.isDescending }))); | ||
}; | ||
ActualSQLServerDataProvider.prototype.find = function (options) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var select, colKeys, _a, _b, x, _c, e_1_1, _d, _e, r, where, _f, first, segs, _loop_1, _g, _h, s, segs_1, segs_1_1, c, _j, e_2_1, page; | ||
var e_1, _k, e_3, _l, e_2, _m; | ||
return tslib_1.__generator(this, function (_o) { | ||
switch (_o.label) { | ||
case 0: return [4 /*yield*/, this.iAmUsed()]; | ||
case 1: | ||
_o.sent(); | ||
select = 'select '; | ||
colKeys = []; | ||
_o.label = 2; | ||
case 2: | ||
_o.trys.push([2, 8, 9, 10]); | ||
_a = tslib_1.__values(this.entity.fields), _b = _a.next(); | ||
_o.label = 3; | ||
case 3: | ||
if (!!_b.done) return [3 /*break*/, 7]; | ||
x = _b.value; | ||
if (!x.isServerExpression) return [3 /*break*/, 4]; | ||
return [3 /*break*/, 6]; | ||
case 4: | ||
if (colKeys.length > 0) | ||
select += ', '; | ||
_c = select; | ||
return [4 /*yield*/, x.getDbName()]; | ||
case 5: | ||
select = _c + _o.sent(); | ||
colKeys.push(x); | ||
_o.label = 6; | ||
case 6: | ||
_b = _a.next(); | ||
return [3 /*break*/, 3]; | ||
case 7: return [3 /*break*/, 10]; | ||
case 8: | ||
e_1_1 = _o.sent(); | ||
e_1 = { error: e_1_1 }; | ||
return [3 /*break*/, 10]; | ||
case 9: | ||
try { | ||
if (_b && !_b.done && (_k = _a.return)) _k.call(_a); | ||
} | ||
else | ||
segs.push(s); | ||
} | ||
for (const c of segs) { | ||
finally { if (e_1) throw e_1.error; } | ||
return [7 /*endfinally*/]; | ||
case 10: | ||
_d = select; | ||
_e = '\n from '; | ||
return [4 /*yield*/, this.entity.getDbName()]; | ||
case 11: | ||
select = _d + (_e + (_o.sent())); | ||
r = this.sql.createCommand(); | ||
if (!options) return [3 /*break*/, 22]; | ||
if (!options.where) return [3 /*break*/, 13]; | ||
where = new filter_consumer_bridge_to_sql_request_1.FilterConsumerBridgeToSqlRequest(r); | ||
options.where.__applyToConsumer(where); | ||
_f = select; | ||
return [4 /*yield*/, where.resolveWhere()]; | ||
case 12: | ||
select = _f + _o.sent(); | ||
_o.label = 13; | ||
case 13: | ||
if (options.limit) { | ||
options.orderBy = sort_1.Sort.createUniqueSort(this.entity, function (x) { var _a; return (_a = options.orderBy) === null || _a === void 0 ? void 0 : _a.Segments; }); | ||
} | ||
if (!options.orderBy) return [3 /*break*/, 21]; | ||
first = true; | ||
segs = []; | ||
_loop_1 = function (s) { | ||
if (s.field instanceof column_1.CompoundIdField) { | ||
segs.push.apply(segs, tslib_1.__spread(s.field.fields.map(function (c) { return ({ field: c, isDescending: s.isDescending }); }))); | ||
} | ||
else | ||
segs.push(s); | ||
}; | ||
try { | ||
for (_g = tslib_1.__values(options.orderBy.Segments), _h = _g.next(); !_h.done; _h = _g.next()) { | ||
s = _h.value; | ||
_loop_1(s); | ||
} | ||
} | ||
catch (e_3_1) { e_3 = { error: e_3_1 }; } | ||
finally { | ||
try { | ||
if (_h && !_h.done && (_l = _g.return)) _l.call(_g); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
} | ||
_o.label = 14; | ||
case 14: | ||
_o.trys.push([14, 19, 20, 21]); | ||
segs_1 = tslib_1.__values(segs), segs_1_1 = segs_1.next(); | ||
_o.label = 15; | ||
case 15: | ||
if (!!segs_1_1.done) return [3 /*break*/, 18]; | ||
c = segs_1_1.value; | ||
if (first) { | ||
@@ -169,52 +286,91 @@ select += ' Order By '; | ||
select += ', '; | ||
select += yield c.field.getDbName(); | ||
_j = select; | ||
return [4 /*yield*/, c.field.getDbName()]; | ||
case 16: | ||
select = _j + _o.sent(); | ||
if (c.isDescending) | ||
select += ' desc'; | ||
} | ||
} | ||
if (options.limit) { | ||
let page = 1; | ||
if (options.page) | ||
page = options.page; | ||
if (page < 1) | ||
page = 1; | ||
select += ' ' + this.strategy.getLimitSqlSyntax(options.limit, (page - 1) * options.limit); | ||
} | ||
} | ||
return r.execute(select).then(r => { | ||
return r.rows.map(y => { | ||
let result = {}; | ||
for (let index = 0; index < colKeys.length; index++) { | ||
const col = colKeys[index]; | ||
_o.label = 17; | ||
case 17: | ||
segs_1_1 = segs_1.next(); | ||
return [3 /*break*/, 15]; | ||
case 18: return [3 /*break*/, 21]; | ||
case 19: | ||
e_2_1 = _o.sent(); | ||
e_2 = { error: e_2_1 }; | ||
return [3 /*break*/, 21]; | ||
case 20: | ||
try { | ||
result[col.key] = col.valueConverter.fromDb(y[r.getColumnKeyInResultForIndexInSelect(index)]); | ||
if (segs_1_1 && !segs_1_1.done && (_m = segs_1.return)) _m.call(segs_1); | ||
} | ||
catch (err) { | ||
throw new Error("Failed to load from db:" + col.key + "\r\n" + err); | ||
finally { if (e_2) throw e_2.error; } | ||
return [7 /*endfinally*/]; | ||
case 21: | ||
if (options.limit) { | ||
page = 1; | ||
if (options.page) | ||
page = options.page; | ||
if (page < 1) | ||
page = 1; | ||
select += ' ' + this.strategy.getLimitSqlSyntax(options.limit, (page - 1) * options.limit); | ||
} | ||
} | ||
return result; | ||
}); | ||
_o.label = 22; | ||
case 22: return [2 /*return*/, r.execute(select).then(function (r) { | ||
return r.rows.map(function (y) { | ||
var result = {}; | ||
for (var index = 0; index < colKeys.length; index++) { | ||
var col = colKeys[index]; | ||
try { | ||
result[col.key] = col.valueConverter.fromDb(y[r.getColumnKeyInResultForIndexInSelect(index)]); | ||
} | ||
catch (err) { | ||
throw new Error("Failed to load from db:" + col.key + "\r\n" + err); | ||
} | ||
} | ||
return result; | ||
}); | ||
})]; | ||
} | ||
}); | ||
}); | ||
} | ||
update(id, data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.iAmUsed(); | ||
let r = this.sql.createCommand(); | ||
let f = new filter_consumer_bridge_to_sql_request_1.FilterConsumerBridgeToSqlRequest(r); | ||
this.entity.idMetadata.getIdFilter(id).__applyToConsumer(f); | ||
let statement = 'update ' + (yield this.entity.getDbName()) + ' set '; | ||
let added = false; | ||
let resultFilter = this.entity.idMetadata.getIdFilter(id); | ||
if (data.id != undefined) | ||
resultFilter = this.entity.idMetadata.getIdFilter(data.id); | ||
for (const x of this.entity.fields) { | ||
if (x instanceof column_1.CompoundIdField) { | ||
resultFilter = x.resultIdFilter(id, data); | ||
} | ||
if (yield isDbReadonly(x)) { } | ||
else { | ||
let v = x.valueConverter.toDb(data[x.key]); | ||
if (v !== undefined) { | ||
}; | ||
ActualSQLServerDataProvider.prototype.update = function (id, data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var r, f, statement, _a, added, resultFilter, _b, _c, x, v, _d, e_4_1, _e; | ||
var e_4, _f; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_g) { | ||
switch (_g.label) { | ||
case 0: return [4 /*yield*/, this.iAmUsed()]; | ||
case 1: | ||
_g.sent(); | ||
r = this.sql.createCommand(); | ||
f = new filter_consumer_bridge_to_sql_request_1.FilterConsumerBridgeToSqlRequest(r); | ||
this.entity.idMetadata.getIdFilter(id).__applyToConsumer(f); | ||
_a = 'update '; | ||
return [4 /*yield*/, this.entity.getDbName()]; | ||
case 2: | ||
statement = _a + (_g.sent()) + ' set '; | ||
added = false; | ||
resultFilter = this.entity.idMetadata.getIdFilter(id); | ||
if (data.id != undefined) | ||
resultFilter = this.entity.idMetadata.getIdFilter(data.id); | ||
_g.label = 3; | ||
case 3: | ||
_g.trys.push([3, 10, 11, 12]); | ||
_b = tslib_1.__values(this.entity.fields), _c = _b.next(); | ||
_g.label = 4; | ||
case 4: | ||
if (!!_c.done) return [3 /*break*/, 9]; | ||
x = _c.value; | ||
if (x instanceof column_1.CompoundIdField) { | ||
resultFilter = x.resultIdFilter(id, data); | ||
} | ||
return [4 /*yield*/, isDbReadonly(x)]; | ||
case 5: | ||
if (!_g.sent()) return [3 /*break*/, 6]; | ||
return [3 /*break*/, 8]; | ||
case 6: | ||
v = x.valueConverter.toDb(data[x.key]); | ||
if (!(v !== undefined)) return [3 /*break*/, 8]; | ||
if (!added) | ||
@@ -224,41 +380,91 @@ added = true; | ||
statement += ', '; | ||
statement += (yield x.getDbName()) + ' = ' + r.addParameterAndReturnSqlToken(v); | ||
} | ||
_d = statement; | ||
return [4 /*yield*/, x.getDbName()]; | ||
case 7: | ||
statement = _d + ((_g.sent()) + ' = ' + r.addParameterAndReturnSqlToken(v)); | ||
_g.label = 8; | ||
case 8: | ||
_c = _b.next(); | ||
return [3 /*break*/, 4]; | ||
case 9: return [3 /*break*/, 12]; | ||
case 10: | ||
e_4_1 = _g.sent(); | ||
e_4 = { error: e_4_1 }; | ||
return [3 /*break*/, 12]; | ||
case 11: | ||
try { | ||
if (_c && !_c.done && (_f = _b.return)) _f.call(_b); | ||
} | ||
finally { if (e_4) throw e_4.error; } | ||
return [7 /*endfinally*/]; | ||
case 12: | ||
_e = statement; | ||
return [4 /*yield*/, f.resolveWhere()]; | ||
case 13: | ||
statement = _e + _g.sent(); | ||
return [2 /*return*/, r.execute(statement).then(function () { | ||
return _this.find({ where: resultFilter }).then(function (y) { return y[0]; }); | ||
})]; | ||
} | ||
} | ||
statement += yield f.resolveWhere(); | ||
return r.execute(statement).then(() => { | ||
return this.find({ where: resultFilter }).then(y => y[0]); | ||
}); | ||
}); | ||
} | ||
delete(id) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.iAmUsed(); | ||
let r = this.sql.createCommand(); | ||
let f = new filter_consumer_bridge_to_sql_request_1.FilterConsumerBridgeToSqlRequest(r); | ||
this.entity.idMetadata.getIdFilter(id).__applyToConsumer(f); | ||
let statement = 'delete from ' + (yield this.entity.getDbName()); | ||
statement += yield f.resolveWhere(); | ||
return r.execute(statement).then(() => { }); | ||
}; | ||
ActualSQLServerDataProvider.prototype.delete = function (id) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var r, f, statement, _a, _b; | ||
return tslib_1.__generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: return [4 /*yield*/, this.iAmUsed()]; | ||
case 1: | ||
_c.sent(); | ||
r = this.sql.createCommand(); | ||
f = new filter_consumer_bridge_to_sql_request_1.FilterConsumerBridgeToSqlRequest(r); | ||
this.entity.idMetadata.getIdFilter(id).__applyToConsumer(f); | ||
_a = 'delete from '; | ||
return [4 /*yield*/, this.entity.getDbName()]; | ||
case 2: | ||
statement = _a + (_c.sent()); | ||
_b = statement; | ||
return [4 /*yield*/, f.resolveWhere()]; | ||
case 3: | ||
statement = _b + _c.sent(); | ||
return [2 /*return*/, r.execute(statement).then(function () { })]; | ||
} | ||
}); | ||
}); | ||
} | ||
insert(data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.iAmUsed(); | ||
let r = this.sql.createCommand(); | ||
let f = new filter_consumer_bridge_to_sql_request_1.FilterConsumerBridgeToSqlRequest(r); | ||
let cols = ''; | ||
let vals = ''; | ||
let added = false; | ||
let resultFilter; | ||
if (this.entity.idMetadata.field instanceof column_1.CompoundIdField) | ||
resultFilter = this.entity.idMetadata.field.resultIdFilter(undefined, data); | ||
else | ||
resultFilter = this.entity.idMetadata.getIdFilter(data[this.entity.idMetadata.field.key]); | ||
for (const x of this.entity.fields) { | ||
if (yield isDbReadonly(x)) { } | ||
else { | ||
let v = x.valueConverter.toDb(data[x.key]); | ||
if (v != undefined) { | ||
}; | ||
ActualSQLServerDataProvider.prototype.insert = function (data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var r, f, cols, vals, added, resultFilter, _a, _b, x, v, _c, e_5_1, statement, _d, newId_1; | ||
var e_5, _e; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_f) { | ||
switch (_f.label) { | ||
case 0: return [4 /*yield*/, this.iAmUsed()]; | ||
case 1: | ||
_f.sent(); | ||
r = this.sql.createCommand(); | ||
f = new filter_consumer_bridge_to_sql_request_1.FilterConsumerBridgeToSqlRequest(r); | ||
cols = ''; | ||
vals = ''; | ||
added = false; | ||
if (this.entity.idMetadata.field instanceof column_1.CompoundIdField) | ||
resultFilter = this.entity.idMetadata.field.resultIdFilter(undefined, data); | ||
else | ||
resultFilter = this.entity.idMetadata.getIdFilter(data[this.entity.idMetadata.field.key]); | ||
_f.label = 2; | ||
case 2: | ||
_f.trys.push([2, 9, 10, 11]); | ||
_a = tslib_1.__values(this.entity.fields), _b = _a.next(); | ||
_f.label = 3; | ||
case 3: | ||
if (!!_b.done) return [3 /*break*/, 8]; | ||
x = _b.value; | ||
return [4 /*yield*/, isDbReadonly(x)]; | ||
case 4: | ||
if (!_f.sent()) return [3 /*break*/, 5]; | ||
return [3 /*break*/, 7]; | ||
case 5: | ||
v = x.valueConverter.toDb(data[x.key]); | ||
if (!(v != undefined)) return [3 /*break*/, 7]; | ||
if (!added) | ||
@@ -270,24 +476,62 @@ added = true; | ||
} | ||
cols += yield x.getDbName(); | ||
_c = cols; | ||
return [4 /*yield*/, x.getDbName()]; | ||
case 6: | ||
cols = _c + _f.sent(); | ||
vals += r.addParameterAndReturnSqlToken(v); | ||
} | ||
_f.label = 7; | ||
case 7: | ||
_b = _a.next(); | ||
return [3 /*break*/, 3]; | ||
case 8: return [3 /*break*/, 11]; | ||
case 9: | ||
e_5_1 = _f.sent(); | ||
e_5 = { error: e_5_1 }; | ||
return [3 /*break*/, 11]; | ||
case 10: | ||
try { | ||
if (_b && !_b.done && (_e = _a.return)) _e.call(_a); | ||
} | ||
finally { if (e_5) throw e_5.error; } | ||
return [7 /*endfinally*/]; | ||
case 11: | ||
_d = "insert into "; | ||
return [4 /*yield*/, this.entity.getDbName()]; | ||
case 12: | ||
statement = _d + (_f.sent()) + " (" + cols + ") values (" + vals + ")"; | ||
if (!this.entity.options.dbAutoIncrementId) return [3 /*break*/, 14]; | ||
return [4 /*yield*/, this.strategy.insertAndReturnAutoIncrementId(r, statement, this.entity)]; | ||
case 13: | ||
newId_1 = _f.sent(); | ||
resultFilter = new filter_interfaces_1.Filter(function (x) { return x.isEqualTo(_this.entity.idMetadata.field, newId_1); }); | ||
return [3 /*break*/, 16]; | ||
case 14: return [4 /*yield*/, r.execute(statement)]; | ||
case 15: | ||
_f.sent(); | ||
_f.label = 16; | ||
case 16: return [2 /*return*/, this.find({ where: resultFilter }).then(function (y) { | ||
return y[0]; | ||
})]; | ||
} | ||
} | ||
let statement = `insert into ${yield this.entity.getDbName()} (${cols}) values (${vals})`; | ||
if (this.entity.options.dbAutoIncrementId) { | ||
let newId = yield this.strategy.insertAndReturnAutoIncrementId(r, statement, this.entity); | ||
resultFilter = new filter_interfaces_1.Filter(x => x.isEqualTo(this.entity.idMetadata.field, newId)); | ||
} | ||
else | ||
yield r.execute(statement); | ||
return this.find({ where: resultFilter }).then(y => { | ||
return y[0]; | ||
}); | ||
}); | ||
} | ||
} | ||
ActualSQLServerDataProvider.LogToConsole = false; | ||
}; | ||
ActualSQLServerDataProvider.LogToConsole = false; | ||
return ActualSQLServerDataProvider; | ||
}()); | ||
function isDbReadonly(x) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return (x.dbReadOnly || x.isServerExpression || (yield x.getDbName()) != x.options.dbName); | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _a; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_a = x.dbReadOnly || x.isServerExpression; | ||
if (_a) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, x.getDbName()]; | ||
case 1: | ||
_a = (_b.sent()) != x.options.dbName; | ||
_b.label = 2; | ||
case 2: return [2 /*return*/, (_a)]; | ||
} | ||
}); | ||
}); | ||
@@ -294,0 +538,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.WebSqlDataProvider = void 0; | ||
const tslib_1 = require("tslib"); | ||
const sql_database_1 = require("./sql-database"); | ||
var tslib_1 = require("tslib"); | ||
var sql_database_1 = require("./sql-database"); | ||
//SqlDatabase.LogToConsole = true; | ||
class WebSqlDataProvider { | ||
constructor(databaseName) { | ||
var WebSqlDataProvider = /** @class */ (function () { | ||
function WebSqlDataProvider(databaseName) { | ||
this.databaseName = databaseName; | ||
@@ -13,56 +13,125 @@ //@ts-ignore | ||
} | ||
insertAndReturnAutoIncrementId(command, insertStatementString, entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let r = yield command.execute(insertStatementString); | ||
return r.r.insertId; | ||
WebSqlDataProvider.prototype.insertAndReturnAutoIncrementId = function (command, insertStatementString, entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var r; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, command.execute(insertStatementString)]; | ||
case 1: | ||
r = _a.sent(); | ||
return [2 /*return*/, r.r.insertId]; | ||
} | ||
}); | ||
}); | ||
} | ||
getLimitSqlSyntax(limit, offset) { | ||
}; | ||
WebSqlDataProvider.prototype.getLimitSqlSyntax = function (limit, offset) { | ||
return ' limit ' + limit + ' offset ' + offset; | ||
} | ||
entityIsUsedForTheFirstTime(entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.createTable(entity); | ||
}; | ||
WebSqlDataProvider.prototype.entityIsUsedForTheFirstTime = function (entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.createTable(entity)]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
dropTable(entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let sql = 'drop table if exists ' + (yield entity.getDbName()); | ||
if (sql_database_1.SqlDatabase.LogToConsole) | ||
console.log(sql); | ||
yield this.createCommand().execute(sql); | ||
}; | ||
WebSqlDataProvider.prototype.dropTable = function (entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var sql, _a; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_a = 'drop table if exists '; | ||
return [4 /*yield*/, entity.getDbName()]; | ||
case 1: | ||
sql = _a + (_b.sent()); | ||
if (sql_database_1.SqlDatabase.LogToConsole) | ||
console.log(sql); | ||
return [4 /*yield*/, this.createCommand().execute(sql)]; | ||
case 2: | ||
_b.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
createTable(entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let result = ''; | ||
for (const x of entity.fields) { | ||
if (!(yield sql_database_1.isDbReadonly(x))) { | ||
if (result.length != 0) | ||
result += ','; | ||
result += '\r\n '; | ||
result += this.addColumnSqlSyntax(x, yield x.getDbName()); | ||
if (x.key == entity.idMetadata.field.key) { | ||
result += ' primary key'; | ||
if (entity.options.dbAutoIncrementId) | ||
result += " autoincrement"; | ||
} | ||
}; | ||
WebSqlDataProvider.prototype.createTable = function (entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var result, _a, _b, x, _c, _d, _e, e_1_1, sql, _f; | ||
var e_1, _g; | ||
return tslib_1.__generator(this, function (_h) { | ||
switch (_h.label) { | ||
case 0: | ||
result = ''; | ||
_h.label = 1; | ||
case 1: | ||
_h.trys.push([1, 7, 8, 9]); | ||
_a = tslib_1.__values(entity.fields), _b = _a.next(); | ||
_h.label = 2; | ||
case 2: | ||
if (!!_b.done) return [3 /*break*/, 6]; | ||
x = _b.value; | ||
return [4 /*yield*/, sql_database_1.isDbReadonly(x)]; | ||
case 3: | ||
if (!!(_h.sent())) return [3 /*break*/, 5]; | ||
if (result.length != 0) | ||
result += ','; | ||
result += '\r\n '; | ||
_c = result; | ||
_d = this.addColumnSqlSyntax; | ||
_e = [x]; | ||
return [4 /*yield*/, x.getDbName()]; | ||
case 4: | ||
result = _c + _d.apply(this, _e.concat([_h.sent()])); | ||
if (x.key == entity.idMetadata.field.key) { | ||
result += ' primary key'; | ||
if (entity.options.dbAutoIncrementId) | ||
result += " autoincrement"; | ||
} | ||
_h.label = 5; | ||
case 5: | ||
_b = _a.next(); | ||
return [3 /*break*/, 2]; | ||
case 6: return [3 /*break*/, 9]; | ||
case 7: | ||
e_1_1 = _h.sent(); | ||
e_1 = { error: e_1_1 }; | ||
return [3 /*break*/, 9]; | ||
case 8: | ||
try { | ||
if (_b && !_b.done && (_g = _a.return)) _g.call(_a); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
return [7 /*endfinally*/]; | ||
case 9: | ||
_f = 'create table if not exists '; | ||
return [4 /*yield*/, entity.getDbName()]; | ||
case 10: | ||
sql = _f + (_h.sent()) + ' (' + result + '\r\n)'; | ||
if (sql_database_1.SqlDatabase.LogToConsole) | ||
console.log(sql); | ||
return [4 /*yield*/, this.createCommand().execute(sql)]; | ||
case 11: | ||
_h.sent(); | ||
return [2 /*return*/]; | ||
} | ||
} | ||
let sql = 'create table if not exists ' + (yield entity.getDbName()) + ' (' + result + '\r\n)'; | ||
if (sql_database_1.SqlDatabase.LogToConsole) | ||
console.log(sql); | ||
yield this.createCommand().execute(sql); | ||
}); | ||
}); | ||
} | ||
createCommand() { | ||
}; | ||
WebSqlDataProvider.prototype.createCommand = function () { | ||
return new WebSqlBridgeToSQLCommand(this.db); | ||
} | ||
transaction(action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
throw new Error("Method not implemented."); | ||
}; | ||
WebSqlDataProvider.prototype.transaction = function (action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
throw new Error("Method not implemented."); | ||
}); | ||
}); | ||
} | ||
addColumnSqlSyntax(x, dbName) { | ||
let result = dbName; | ||
}; | ||
WebSqlDataProvider.prototype.addColumnSqlSyntax = function (x, dbName) { | ||
var result = dbName; | ||
if (x.valueType == Date) | ||
@@ -81,47 +150,52 @@ result += " integer"; | ||
return result; | ||
} | ||
toString() { return "WebSqlDataProvider"; } | ||
} | ||
}; | ||
WebSqlDataProvider.prototype.toString = function () { return "WebSqlDataProvider"; }; | ||
return WebSqlDataProvider; | ||
}()); | ||
exports.WebSqlDataProvider = WebSqlDataProvider; | ||
class WebSqlBridgeToSQLCommand { | ||
var WebSqlBridgeToSQLCommand = /** @class */ (function () { | ||
//@ts-ignore | ||
constructor(source) { | ||
function WebSqlBridgeToSQLCommand(source) { | ||
this.source = source; | ||
this.values = []; | ||
} | ||
addParameterAndReturnSqlToken(val) { | ||
WebSqlBridgeToSQLCommand.prototype.addParameterAndReturnSqlToken = function (val) { | ||
this.values.push(val); | ||
return '~' + this.values.length + '~'; | ||
} | ||
execute(sql) { | ||
return new Promise((resolve, reject) => this.source.transaction(t => { | ||
let s = sql; | ||
let v = []; | ||
var m = s.match(/~\d+~/g); | ||
if (m != null) | ||
m.forEach(mr => { | ||
s = s.replace(mr, '?'); | ||
v.push(this.values[Number.parseInt(mr.substring(1, mr.length - 1)) - 1]); | ||
}; | ||
WebSqlBridgeToSQLCommand.prototype.execute = function (sql) { | ||
var _this = this; | ||
return new Promise(function (resolve, reject) { | ||
return _this.source.transaction(function (t) { | ||
var s = sql; | ||
var v = []; | ||
var m = s.match(/~\d+~/g); | ||
if (m != null) | ||
m.forEach(function (mr) { | ||
s = s.replace(mr, '?'); | ||
v.push(_this.values[Number.parseInt(mr.substring(1, mr.length - 1)) - 1]); | ||
}); | ||
t.executeSql(s, v, function (t1, r) { return resolve(new WebSqlBridgeToSQLQueryResult(r)); }, function (t2, err) { | ||
reject(err.message); | ||
return undefined; | ||
}); | ||
t.executeSql(s, v, (t1, r) => resolve(new WebSqlBridgeToSQLQueryResult(r)), (t2, err) => { | ||
reject(err.message); | ||
return undefined; | ||
}); | ||
})); | ||
} | ||
} | ||
class WebSqlBridgeToSQLQueryResult { | ||
}); | ||
}; | ||
return WebSqlBridgeToSQLCommand; | ||
}()); | ||
var WebSqlBridgeToSQLQueryResult = /** @class */ (function () { | ||
//@ts-ignore | ||
constructor(r) { | ||
function WebSqlBridgeToSQLQueryResult(r) { | ||
this.r = r; | ||
this.rows = []; | ||
for (let i = 0; i < r.rows.length; i++) { | ||
for (var i = 0; i < r.rows.length; i++) { | ||
this.rows.push(r.rows.item(i)); | ||
} | ||
} | ||
getColumnKeyInResultForIndexInSelect(index) { | ||
WebSqlBridgeToSQLQueryResult.prototype.getColumnKeyInResultForIndexInSelect = function (index) { | ||
if (this.rows.length == 0) | ||
return undefined; | ||
let i = 0; | ||
for (let m in this.rows[0]) { | ||
var i = 0; | ||
for (var m in this.rows[0]) { | ||
if (i++ == index) | ||
@@ -131,4 +205,5 @@ return m; | ||
return undefined; | ||
} | ||
} | ||
}; | ||
return WebSqlBridgeToSQLQueryResult; | ||
}()); | ||
//# sourceMappingURL=web-sql-data-provider.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.CustomSqlFilterBuilder = exports.FilterConsumerBridgeToSqlRequest = void 0; | ||
const tslib_1 = require("tslib"); | ||
class FilterConsumerBridgeToSqlRequest { | ||
constructor(r) { | ||
var tslib_1 = require("tslib"); | ||
var FilterConsumerBridgeToSqlRequest = /** @class */ (function () { | ||
function FilterConsumerBridgeToSqlRequest(r) { | ||
this.r = r; | ||
@@ -12,86 +12,198 @@ this.where = ""; | ||
} | ||
resolveWhere() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
while (this.promises.length > 0) { | ||
let p = this.promises; | ||
this.promises = []; | ||
for (const pr of p) { | ||
yield pr; | ||
FilterConsumerBridgeToSqlRequest.prototype.resolveWhere = function () { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var p, p_1, p_1_1, pr, e_1_1; | ||
var e_1, _a; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
if (!(this.promises.length > 0)) return [3 /*break*/, 9]; | ||
p = this.promises; | ||
this.promises = []; | ||
_b.label = 1; | ||
case 1: | ||
_b.trys.push([1, 6, 7, 8]); | ||
p_1 = (e_1 = void 0, tslib_1.__values(p)), p_1_1 = p_1.next(); | ||
_b.label = 2; | ||
case 2: | ||
if (!!p_1_1.done) return [3 /*break*/, 5]; | ||
pr = p_1_1.value; | ||
return [4 /*yield*/, pr]; | ||
case 3: | ||
_b.sent(); | ||
_b.label = 4; | ||
case 4: | ||
p_1_1 = p_1.next(); | ||
return [3 /*break*/, 2]; | ||
case 5: return [3 /*break*/, 8]; | ||
case 6: | ||
e_1_1 = _b.sent(); | ||
e_1 = { error: e_1_1 }; | ||
return [3 /*break*/, 8]; | ||
case 7: | ||
try { | ||
if (p_1_1 && !p_1_1.done && (_a = p_1.return)) _a.call(p_1); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
return [7 /*endfinally*/]; | ||
case 8: return [3 /*break*/, 0]; | ||
case 9: return [2 /*return*/, this.where]; | ||
} | ||
} | ||
return this.where; | ||
}); | ||
}); | ||
} | ||
custom(customItem) { | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.custom = function (customItem) { | ||
throw new Error("Custom filter should be translated before it gets here"); | ||
} | ||
or(orElements) { | ||
let statement = ''; | ||
this.promises.push((() => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
for (const element of orElements) { | ||
let f = new FilterConsumerBridgeToSqlRequest(this.r); | ||
f._addWhere = false; | ||
element.__applyToConsumer(f); | ||
let where = yield f.resolveWhere(); | ||
if (where.length > 0) { | ||
if (statement.length > 0) { | ||
statement += " or "; | ||
} | ||
if (orElements.length > 1) { | ||
statement += "(" + where + ")"; | ||
} | ||
else | ||
statement += where; | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.or = function (orElements) { | ||
var _this = this; | ||
var statement = ''; | ||
this.promises.push((function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var orElements_1, orElements_1_1, element, f, where, e_2_1; | ||
var e_2, _a; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_b.trys.push([0, 5, 6, 7]); | ||
orElements_1 = tslib_1.__values(orElements), orElements_1_1 = orElements_1.next(); | ||
_b.label = 1; | ||
case 1: | ||
if (!!orElements_1_1.done) return [3 /*break*/, 4]; | ||
element = orElements_1_1.value; | ||
f = new FilterConsumerBridgeToSqlRequest(this.r); | ||
f._addWhere = false; | ||
element.__applyToConsumer(f); | ||
return [4 /*yield*/, f.resolveWhere()]; | ||
case 2: | ||
where = _b.sent(); | ||
if (where.length > 0) { | ||
if (statement.length > 0) { | ||
statement += " or "; | ||
} | ||
if (orElements.length > 1) { | ||
statement += "(" + where + ")"; | ||
} | ||
else | ||
statement += where; | ||
} | ||
_b.label = 3; | ||
case 3: | ||
orElements_1_1 = orElements_1.next(); | ||
return [3 /*break*/, 1]; | ||
case 4: return [3 /*break*/, 7]; | ||
case 5: | ||
e_2_1 = _b.sent(); | ||
e_2 = { error: e_2_1 }; | ||
return [3 /*break*/, 7]; | ||
case 6: | ||
try { | ||
if (orElements_1_1 && !orElements_1_1.done && (_a = orElements_1.return)) _a.call(orElements_1); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
return [7 /*endfinally*/]; | ||
case 7: | ||
this.addToWhere("(" + statement + ")"); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); })()); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isNull = function (col) { | ||
var _this = this; | ||
this.promises.push((function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { var _a; return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_a = this.addToWhere; | ||
return [4 /*yield*/, col.getDbName()]; | ||
case 1: return [2 /*return*/, _a.apply(this, [(_b.sent()) + ' is null'])]; | ||
} | ||
this.addToWhere("(" + statement + ")"); | ||
}))()); | ||
} | ||
isNull(col) { | ||
this.promises.push((() => tslib_1.__awaiter(this, void 0, void 0, function* () { return this.addToWhere((yield col.getDbName()) + ' is null'); }))()); | ||
} | ||
isNotNull(col) { | ||
this.promises.push((() => tslib_1.__awaiter(this, void 0, void 0, function* () { return this.addToWhere((yield col.getDbName()) + ' is not null'); }))()); | ||
} | ||
isIn(col, val) { | ||
this.promises.push((() => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (val && val.length > 0) | ||
this.addToWhere((yield col.getDbName()) + " in (" + val.map(x => this.r.addParameterAndReturnSqlToken(col.valueConverter.toDb(x))).join(",") + ")"); | ||
else | ||
this.addToWhere('1 = 0 /*isIn with no values*/'); | ||
}))()); | ||
} | ||
isEqualTo(col, val) { | ||
}); }); })()); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isNotNull = function (col) { | ||
var _this = this; | ||
this.promises.push((function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { var _a; return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_a = this.addToWhere; | ||
return [4 /*yield*/, col.getDbName()]; | ||
case 1: return [2 /*return*/, _a.apply(this, [(_b.sent()) + ' is not null'])]; | ||
} | ||
}); }); })()); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isIn = function (col, val) { | ||
var _this = this; | ||
this.promises.push((function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var _a; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
if (!(val && val.length > 0)) return [3 /*break*/, 2]; | ||
_a = this.addToWhere; | ||
return [4 /*yield*/, col.getDbName()]; | ||
case 1: | ||
_a.apply(this, [(_b.sent()) + " in (" + val.map(function (x) { return _this.r.addParameterAndReturnSqlToken(col.valueConverter.toDb(x)); }).join(",") + ")"]); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
this.addToWhere('1 = 0 /*isIn with no values*/'); | ||
_b.label = 3; | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}); })()); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isEqualTo = function (col, val) { | ||
this.add(col, val, "="); | ||
} | ||
isDifferentFrom(col, val) { | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isDifferentFrom = function (col, val) { | ||
this.add(col, val, "<>"); | ||
} | ||
isGreaterOrEqualTo(col, val) { | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isGreaterOrEqualTo = function (col, val) { | ||
this.add(col, val, ">="); | ||
} | ||
isGreaterThan(col, val) { | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isGreaterThan = function (col, val) { | ||
this.add(col, val, ">"); | ||
} | ||
isLessOrEqualTo(col, val) { | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isLessOrEqualTo = function (col, val) { | ||
this.add(col, val, "<="); | ||
} | ||
isLessThan(col, val) { | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isLessThan = function (col, val) { | ||
this.add(col, val, "<"); | ||
} | ||
containsCaseInsensitive(col, val) { | ||
this.promises.push((() => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
this.addToWhere('lower (' + (yield col.getDbName()) + ") like lower ('%" + val.replace(/'/g, '\'\'') + "%')"); | ||
}))()); | ||
} | ||
startsWith(col, val) { | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.containsCaseInsensitive = function (col, val) { | ||
var _this = this; | ||
this.promises.push((function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var _a, _b; | ||
return tslib_1.__generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
_a = this.addToWhere; | ||
_b = 'lower ('; | ||
return [4 /*yield*/, col.getDbName()]; | ||
case 1: | ||
_a.apply(this, [_b + (_c.sent()) + ") like lower ('%" + val.replace(/'/g, '\'\'') + "%')"]); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); })()); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.startsWith = function (col, val) { | ||
this.add(col, val + '%', 'like'); | ||
} | ||
add(col, val, operator) { | ||
this.promises.push((() => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let x = (yield col.getDbName()) + ' ' + operator + ' ' + this.r.addParameterAndReturnSqlToken(col.valueConverter.toDb(val)); | ||
this.addToWhere(x); | ||
}))()); | ||
} | ||
addToWhere(x) { | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.add = function (col, val, operator) { | ||
var _this = this; | ||
this.promises.push((function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var x; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, col.getDbName()]; | ||
case 1: | ||
x = (_a.sent()) + ' ' + operator + ' ' + this.r.addParameterAndReturnSqlToken(col.valueConverter.toDb(val)); | ||
this.addToWhere(x); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); })()); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.addToWhere = function (x) { | ||
if (this.where.length == 0) { | ||
@@ -104,28 +216,40 @@ if (this._addWhere) | ||
this.where += x; | ||
} | ||
databaseCustom(databaseCustom) { | ||
this.promises.push((() => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (databaseCustom === null || databaseCustom === void 0 ? void 0 : databaseCustom.buildSql) { | ||
let item = new CustomSqlFilterBuilder(this.r); | ||
yield databaseCustom.buildSql(item); | ||
if (item.sql) { | ||
this.addToWhere("(" + item.sql + ")"); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.databaseCustom = function (databaseCustom) { | ||
var _this = this; | ||
this.promises.push((function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var item; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(databaseCustom === null || databaseCustom === void 0 ? void 0 : databaseCustom.buildSql)) return [3 /*break*/, 2]; | ||
item = new CustomSqlFilterBuilder(this.r); | ||
return [4 /*yield*/, databaseCustom.buildSql(item)]; | ||
case 1: | ||
_a.sent(); | ||
if (item.sql) { | ||
this.addToWhere("(" + item.sql + ")"); | ||
} | ||
_a.label = 2; | ||
case 2: return [2 /*return*/]; | ||
} | ||
} | ||
}))()); | ||
} | ||
} | ||
}); | ||
}); })()); | ||
}; | ||
return FilterConsumerBridgeToSqlRequest; | ||
}()); | ||
exports.FilterConsumerBridgeToSqlRequest = FilterConsumerBridgeToSqlRequest; | ||
class CustomSqlFilterBuilder { | ||
constructor(r) { | ||
var CustomSqlFilterBuilder = /** @class */ (function () { | ||
function CustomSqlFilterBuilder(r) { | ||
this.r = r; | ||
this.sql = ''; | ||
} | ||
addParameterAndReturnSqlToken(val, field) { | ||
CustomSqlFilterBuilder.prototype.addParameterAndReturnSqlToken = function (val, field) { | ||
if (field) | ||
val = field.valueConverter.toDb(val); | ||
return this.r.addParameterAndReturnSqlToken(val); | ||
} | ||
} | ||
}; | ||
return CustomSqlFilterBuilder; | ||
}()); | ||
exports.CustomSqlFilterBuilder = CustomSqlFilterBuilder; | ||
//# sourceMappingURL=filter-consumer-bridge-to-sql-request.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.CustomFilterBuilder = exports.extractWhere = exports.unpackWhere = exports.FilterSerializer = exports.customUrlToken = exports.OrFilter = exports.AndFilter = exports.filterHelper = exports.Filter = void 0; | ||
const tslib_1 = require("tslib"); | ||
const remult3_1 = require("../remult3"); | ||
class Filter { | ||
constructor(apply) { | ||
var tslib_1 = require("tslib"); | ||
var remult3_1 = require("../remult3"); | ||
var Filter = /** @class */ (function () { | ||
function Filter(apply) { | ||
this.apply = apply; | ||
if (!this.apply) { | ||
this.apply = () => { }; | ||
this.apply = function () { }; | ||
} | ||
} | ||
__applyToConsumer(add) { | ||
Filter.prototype.__applyToConsumer = function (add) { | ||
this.apply(add); | ||
} | ||
and(filter) { | ||
}; | ||
Filter.prototype.and = function (filter) { | ||
return new AndFilter(this, filter); | ||
} | ||
or(filter) { | ||
}; | ||
Filter.prototype.or = function (filter) { | ||
return new OrFilter(this, filter); | ||
} | ||
static createFilterFactories(entityDefs) { | ||
let r = {}; | ||
for (const c of entityDefs.fields) { | ||
r[c.key] = new filterHelper(c); | ||
}; | ||
Filter.createFilterFactories = function (entityDefs) { | ||
var e_1, _a; | ||
var r = {}; | ||
try { | ||
for (var _b = tslib_1.__values(entityDefs.fields), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var c = _c.value; | ||
r[c.key] = new filterHelper(c); | ||
} | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
return r; | ||
} | ||
static translateWhereToFilter(entity, where) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (Array.isArray(where)) { | ||
return new AndFilter(...yield Promise.all(where.map(x => Filter.translateWhereToFilter(entity, x)))); | ||
} | ||
else if (typeof where === 'function') { | ||
let r = where(entity); | ||
if (Array.isArray(r)) | ||
return new AndFilter( | ||
//@ts-ignore | ||
...yield Promise.all(r.map((x) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (typeof x === "function") | ||
return this.translateWhereToFilter(entity, x); | ||
return yield x; | ||
})))); | ||
else if (typeof r === 'function') | ||
return this.translateWhereToFilter(entity, r); | ||
return r; | ||
} | ||
}; | ||
Filter.translateWhereToFilter = function (entity, where) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _a, _b, _c, _d, r, _e, _f, _g, _h; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_j) { | ||
switch (_j.label) { | ||
case 0: | ||
if (!Array.isArray(where)) return [3 /*break*/, 2]; | ||
_b = (_a = AndFilter.bind).apply; | ||
_c = [AndFilter]; | ||
_d = [[void 0]]; | ||
return [4 /*yield*/, Promise.all(where.map(function (x) { | ||
return Filter.translateWhereToFilter(entity, x); | ||
}))]; | ||
case 1: return [2 /*return*/, new (_b.apply(_a, _c.concat([tslib_1.__spread.apply(void 0, _d.concat([_j.sent()]))])))()]; | ||
case 2: | ||
if (!(typeof where === 'function')) return [3 /*break*/, 6]; | ||
r = where(entity); | ||
if (!Array.isArray(r)) return [3 /*break*/, 4]; | ||
_f = (_e = AndFilter.bind).apply; | ||
_g = [AndFilter]; | ||
_h = [[void 0]]; | ||
return [4 /*yield*/, Promise.all(r.map(function (x) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (typeof x === "function") | ||
return [2 /*return*/, this.translateWhereToFilter(entity, x)]; | ||
return [4 /*yield*/, x]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
}); }))]; | ||
case 3: return [2 /*return*/, new (_f.apply(_e, _g.concat([tslib_1.__spread.apply(void 0, _h.concat([_j.sent()]))])))()]; | ||
case 4: | ||
if (typeof r === 'function') | ||
return [2 /*return*/, this.translateWhereToFilter(entity, r)]; | ||
_j.label = 5; | ||
case 5: return [2 /*return*/, r]; | ||
case 6: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
static packWhere(entityDefs, where) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (!where) | ||
return {}; | ||
return Filter.packToRawWhere(yield this.translateWhereToFilter(this.createFilterFactories(entityDefs), where)); | ||
}; | ||
Filter.packWhere = function (entityDefs, where) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _a, _b; | ||
return tslib_1.__generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
if (!where) | ||
return [2 /*return*/, {}]; | ||
_b = (_a = Filter).packToRawWhere; | ||
return [4 /*yield*/, this.translateWhereToFilter(this.createFilterFactories(entityDefs), where)]; | ||
case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])]; | ||
} | ||
}); | ||
}); | ||
} | ||
static packToRawWhere(w) { | ||
let r = new FilterSerializer(); | ||
}; | ||
Filter.packToRawWhere = function (w) { | ||
var r = new FilterSerializer(); | ||
if (w) | ||
w.__applyToConsumer(r); | ||
return r.result; | ||
} | ||
static unpackWhere(entityDefs, packed) { | ||
return this.extractWhere(entityDefs, { get: (key) => packed[key] }); | ||
} | ||
static extractWhere(entityDefs, filterInfo) { | ||
return extractWhere([...entityDefs.fields], filterInfo); | ||
} | ||
static translateCustomWhere(entity, filterFactories, r, context) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let f = new customTranslator((custom) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield entity.options.customFilterBuilder().translateFilter(filterFactories, custom, context); | ||
})); | ||
r.__applyToConsumer(f); | ||
yield f.resolve(); | ||
r = new Filter(x => f.applyTo(x)); | ||
return r; | ||
}; | ||
Filter.unpackWhere = function (entityDefs, packed) { | ||
return this.extractWhere(entityDefs, { get: function (key) { return packed[key]; } }); | ||
}; | ||
Filter.extractWhere = function (entityDefs, filterInfo) { | ||
return extractWhere(tslib_1.__spread(entityDefs.fields), filterInfo); | ||
}; | ||
Filter.translateCustomWhere = function (entity, filterFactories, r, context) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var f; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
f = new customTranslator(function (custom) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, entity.options.customFilterBuilder().translateFilter(filterFactories, custom, context)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
}); }); | ||
r.__applyToConsumer(f); | ||
return [4 /*yield*/, f.resolve()]; | ||
case 1: | ||
_a.sent(); | ||
r = new Filter(function (x) { return f.applyTo(x); }); | ||
return [2 /*return*/, r]; | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return Filter; | ||
}()); | ||
exports.Filter = Filter; | ||
class filterHelper { | ||
constructor(metadata) { | ||
var filterHelper = /** @class */ (function () { | ||
function filterHelper(metadata) { | ||
this.metadata = metadata; | ||
} | ||
processVal(val) { | ||
let ei = remult3_1.getEntitySettings(this.metadata.valueType, false); | ||
filterHelper.prototype.processVal = function (val) { | ||
var ei = remult3_1.getEntitySettings(this.metadata.valueType, false); | ||
if (ei) { | ||
@@ -96,65 +153,110 @@ if (!val) | ||
return val; | ||
} | ||
startsWith(val) { | ||
return new Filter(add => add.startsWith(this.metadata, val)); | ||
} | ||
contains(val) { | ||
return new Filter(add => add.containsCaseInsensitive(this.metadata, val)); | ||
} | ||
isLessThan(val) { | ||
return new Filter(add => add.isLessThan(this.metadata, val)); | ||
} | ||
isGreaterOrEqualTo(val) { | ||
return new Filter(add => add.isGreaterOrEqualTo(this.metadata, val)); | ||
} | ||
isNotIn(values) { | ||
return new Filter(add => { | ||
for (const v of values) { | ||
add.isDifferentFrom(this.metadata, v); | ||
}; | ||
filterHelper.prototype.startsWith = function (val) { | ||
var _this = this; | ||
return new Filter(function (add) { return add.startsWith(_this.metadata, val); }); | ||
}; | ||
filterHelper.prototype.contains = function (val) { | ||
var _this = this; | ||
return new Filter(function (add) { return add.containsCaseInsensitive(_this.metadata, val); }); | ||
}; | ||
filterHelper.prototype.isLessThan = function (val) { | ||
var _this = this; | ||
return new Filter(function (add) { return add.isLessThan(_this.metadata, val); }); | ||
}; | ||
filterHelper.prototype.isGreaterOrEqualTo = function (val) { | ||
var _this = this; | ||
return new Filter(function (add) { return add.isGreaterOrEqualTo(_this.metadata, val); }); | ||
}; | ||
filterHelper.prototype.isNotIn = function (values) { | ||
var _this = this; | ||
return new Filter(function (add) { | ||
var e_2, _a; | ||
try { | ||
for (var values_1 = tslib_1.__values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) { | ||
var v = values_1_1.value; | ||
add.isDifferentFrom(_this.metadata, v); | ||
} | ||
} | ||
catch (e_2_1) { e_2 = { error: e_2_1 }; } | ||
finally { | ||
try { | ||
if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
} | ||
}); | ||
} | ||
isDifferentFrom(val) { | ||
}; | ||
filterHelper.prototype.isDifferentFrom = function (val) { | ||
var _this = this; | ||
val = this.processVal(val); | ||
if (val === null && this.metadata.allowNull) | ||
return new Filter(add => add.isNotNull(this.metadata)); | ||
return new Filter(add => add.isDifferentFrom(this.metadata, val)); | ||
} | ||
isLessOrEqualTo(val) { | ||
return new Filter(add => add.isLessOrEqualTo(this.metadata, val)); | ||
} | ||
isGreaterThan(val) { | ||
return new Filter(add => add.isGreaterThan(this.metadata, val)); | ||
} | ||
isEqualTo(val) { | ||
return new Filter(function (add) { return add.isNotNull(_this.metadata); }); | ||
return new Filter(function (add) { return add.isDifferentFrom(_this.metadata, val); }); | ||
}; | ||
filterHelper.prototype.isLessOrEqualTo = function (val) { | ||
var _this = this; | ||
return new Filter(function (add) { return add.isLessOrEqualTo(_this.metadata, val); }); | ||
}; | ||
filterHelper.prototype.isGreaterThan = function (val) { | ||
var _this = this; | ||
return new Filter(function (add) { return add.isGreaterThan(_this.metadata, val); }); | ||
}; | ||
filterHelper.prototype.isEqualTo = function (val) { | ||
var _this = this; | ||
val = this.processVal(val); | ||
if (val === null && this.metadata.allowNull) | ||
return new Filter(add => add.isNull(this.metadata)); | ||
return new Filter(add => add.isEqualTo(this.metadata, val)); | ||
} | ||
isIn(val) { | ||
val = val.map(x => this.processVal(x)); | ||
return new Filter(add => add.isIn(this.metadata, val)); | ||
} | ||
} | ||
return new Filter(function (add) { return add.isNull(_this.metadata); }); | ||
return new Filter(function (add) { return add.isEqualTo(_this.metadata, val); }); | ||
}; | ||
filterHelper.prototype.isIn = function (val) { | ||
var _this = this; | ||
val = val.map(function (x) { return _this.processVal(x); }); | ||
return new Filter(function (add) { return add.isIn(_this.metadata, val); }); | ||
}; | ||
return filterHelper; | ||
}()); | ||
exports.filterHelper = filterHelper; | ||
class AndFilter extends Filter { | ||
constructor(...filters) { | ||
super(add => { | ||
for (const iterator of this.filters) { | ||
if (iterator) | ||
iterator.__applyToConsumer(add); | ||
var AndFilter = /** @class */ (function (_super) { | ||
tslib_1.__extends(AndFilter, _super); | ||
function AndFilter() { | ||
var filters = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
filters[_i] = arguments[_i]; | ||
} | ||
var _this = _super.call(this, function (add) { | ||
var e_3, _a; | ||
try { | ||
for (var _b = tslib_1.__values(_this.filters), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var iterator = _c.value; | ||
if (iterator) | ||
iterator.__applyToConsumer(add); | ||
} | ||
} | ||
}); | ||
this.filters = filters; | ||
catch (e_3_1) { e_3 = { error: e_3_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
} | ||
}) || this; | ||
_this.filters = filters; | ||
return _this; | ||
} | ||
add(filter) { | ||
AndFilter.prototype.add = function (filter) { | ||
this.filters.push(filter); | ||
} | ||
} | ||
}; | ||
return AndFilter; | ||
}(Filter)); | ||
exports.AndFilter = AndFilter; | ||
class OrFilter extends Filter { | ||
constructor(...filters) { | ||
super(add => { | ||
let f = this.filters.filter(x => x !== undefined); | ||
var OrFilter = /** @class */ (function (_super) { | ||
tslib_1.__extends(OrFilter, _super); | ||
function OrFilter() { | ||
var filters = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
filters[_i] = arguments[_i]; | ||
} | ||
var _this = _super.call(this, function (add) { | ||
var f = _this.filters.filter(function (x) { return x !== undefined; }); | ||
if (f.length > 1) { | ||
@@ -165,23 +267,25 @@ add.or(f); | ||
f[0].__applyToConsumer(add); | ||
}); | ||
this.filters = filters; | ||
}) || this; | ||
_this.filters = filters; | ||
return _this; | ||
} | ||
} | ||
return OrFilter; | ||
}(Filter)); | ||
exports.OrFilter = OrFilter; | ||
exports.customUrlToken = "_$custom"; | ||
class FilterSerializer { | ||
constructor() { | ||
var FilterSerializer = /** @class */ (function () { | ||
function FilterSerializer() { | ||
this.result = {}; | ||
this.hasUndefined = false; | ||
} | ||
databaseCustom(databaseCustom) { | ||
FilterSerializer.prototype.databaseCustom = function (databaseCustom) { | ||
throw new Error("database custom is not allowed with rest calls."); | ||
} | ||
custom(customItem) { | ||
}; | ||
FilterSerializer.prototype.custom = function (customItem) { | ||
this.add(exports.customUrlToken, customItem); | ||
} | ||
add(key, val) { | ||
}; | ||
FilterSerializer.prototype.add = function (key, val) { | ||
if (val === undefined) | ||
this.hasUndefined = true; | ||
let r = this.result; | ||
var r = this.result; | ||
if (!r[key]) { | ||
@@ -191,3 +295,3 @@ r[key] = val; | ||
} | ||
let v = r[key]; | ||
var v = r[key]; | ||
if (v instanceof Array) { | ||
@@ -199,59 +303,62 @@ v.push(val); | ||
r[key] = v; | ||
} | ||
or(orElements) { | ||
this.add("OR", orElements.map(x => { | ||
let f = new FilterSerializer(); | ||
}; | ||
FilterSerializer.prototype.or = function (orElements) { | ||
this.add("OR", orElements.map(function (x) { | ||
var f = new FilterSerializer(); | ||
x.__applyToConsumer(f); | ||
return f.result; | ||
})); | ||
} | ||
isNull(col) { | ||
}; | ||
FilterSerializer.prototype.isNull = function (col) { | ||
this.add(col.key + "_null", true); | ||
} | ||
isNotNull(col) { | ||
}; | ||
FilterSerializer.prototype.isNotNull = function (col) { | ||
this.add(col.key + "_null", false); | ||
} | ||
isIn(col, val) { | ||
this.add(col.key + "_in", val.map(x => col.valueConverter.toJson(x))); | ||
} | ||
isEqualTo(col, val) { | ||
}; | ||
FilterSerializer.prototype.isIn = function (col, val) { | ||
this.add(col.key + "_in", val.map(function (x) { return col.valueConverter.toJson(x); })); | ||
}; | ||
FilterSerializer.prototype.isEqualTo = function (col, val) { | ||
this.add(col.key, col.valueConverter.toJson(val)); | ||
} | ||
isDifferentFrom(col, val) { | ||
}; | ||
FilterSerializer.prototype.isDifferentFrom = function (col, val) { | ||
this.add(col.key + '_ne', col.valueConverter.toJson(val)); | ||
} | ||
isGreaterOrEqualTo(col, val) { | ||
}; | ||
FilterSerializer.prototype.isGreaterOrEqualTo = function (col, val) { | ||
this.add(col.key + '_gte', col.valueConverter.toJson(val)); | ||
} | ||
isGreaterThan(col, val) { | ||
}; | ||
FilterSerializer.prototype.isGreaterThan = function (col, val) { | ||
this.add(col.key + '_gt', col.valueConverter.toJson(val)); | ||
} | ||
isLessOrEqualTo(col, val) { | ||
}; | ||
FilterSerializer.prototype.isLessOrEqualTo = function (col, val) { | ||
this.add(col.key + '_lte', col.valueConverter.toJson(val)); | ||
} | ||
isLessThan(col, val) { | ||
}; | ||
FilterSerializer.prototype.isLessThan = function (col, val) { | ||
this.add(col.key + '_lt', col.valueConverter.toJson(val)); | ||
} | ||
containsCaseInsensitive(col, val) { | ||
}; | ||
FilterSerializer.prototype.containsCaseInsensitive = function (col, val) { | ||
this.add(col.key + "_contains", val); | ||
} | ||
startsWith(col, val) { | ||
}; | ||
FilterSerializer.prototype.startsWith = function (col, val) { | ||
this.add(col.key + "_st", col.valueConverter.toJson(val)); | ||
} | ||
} | ||
}; | ||
return FilterSerializer; | ||
}()); | ||
exports.FilterSerializer = FilterSerializer; | ||
function unpackWhere(columns, packed) { | ||
return extractWhere(columns, { get: (key) => packed[key] }); | ||
return extractWhere(columns, { get: function (key) { return packed[key]; } }); | ||
} | ||
exports.unpackWhere = unpackWhere; | ||
function extractWhere(columns, filterInfo) { | ||
let where = []; | ||
columns.forEach(col => { | ||
function addFilter(operation, theFilter, jsonArray = false, asString = false) { | ||
let val = filterInfo.get(col.key + operation); | ||
var where = []; | ||
columns.forEach(function (col) { | ||
function addFilter(operation, theFilter, jsonArray, asString) { | ||
if (jsonArray === void 0) { jsonArray = false; } | ||
if (asString === void 0) { asString = false; } | ||
var val = filterInfo.get(col.key + operation); | ||
if (val !== undefined) { | ||
let addFilter = (val) => { | ||
let theVal = val; | ||
var addFilter_1 = function (val) { | ||
var theVal = val; | ||
if (jsonArray) { | ||
let arr; | ||
var arr = void 0; | ||
if (typeof val === 'string') | ||
@@ -261,3 +368,3 @@ arr = JSON.parse(val); | ||
arr = val; | ||
theVal = arr.map(x => asString ? x : col.valueConverter.fromJson(x)); | ||
theVal = arr.map(function (x) { return asString ? x : col.valueConverter.fromJson(x); }); | ||
} | ||
@@ -267,3 +374,3 @@ else { | ||
} | ||
let f = theFilter(theVal); | ||
var f = theFilter(theVal); | ||
if (f) { | ||
@@ -274,19 +381,21 @@ where.push(f); | ||
if (!jsonArray && val instanceof Array) { | ||
val.forEach(v => { | ||
addFilter(v); | ||
val.forEach(function (v) { | ||
addFilter_1(v); | ||
}); | ||
} | ||
else | ||
addFilter(val); | ||
addFilter_1(val); | ||
} | ||
} | ||
let c = new filterHelper(col); | ||
addFilter('', val => c.isEqualTo(val)); | ||
addFilter('_gt', val => c.isGreaterThan(val)); | ||
addFilter('_gte', val => c.isGreaterOrEqualTo(val)); | ||
addFilter('_lt', val => c.isLessThan(val)); | ||
addFilter('_lte', val => c.isLessOrEqualTo(val)); | ||
addFilter('_ne', val => c.isDifferentFrom(val)); | ||
addFilter('_in', val => c.isIn(val), true); | ||
addFilter('_null', val => { | ||
var c = new filterHelper(col); | ||
addFilter('', function (val) { return c.isEqualTo(val); }); | ||
addFilter('_gt', function (val) { return c.isGreaterThan(val); }); | ||
addFilter('_gte', function (val) { return c.isGreaterOrEqualTo(val); }); | ||
addFilter('_lt', function (val) { return c.isLessThan(val); }); | ||
addFilter('_lte', function (val) { return c.isLessOrEqualTo(val); }); | ||
addFilter('_ne', function (val) { return c.isDifferentFrom(val); }); | ||
addFilter('_in', function (val) { | ||
return c.isIn(val); | ||
}, true); | ||
addFilter('_null', function (val) { | ||
val = val.toString().trim().toLowerCase(); | ||
@@ -302,29 +411,32 @@ switch (val) { | ||
}); | ||
addFilter('_contains', val => { | ||
addFilter('_contains', function (val) { | ||
return c.contains(val); | ||
}, false, true); | ||
addFilter('_st', val => { | ||
addFilter('_st', function (val) { | ||
return c.startsWith(val); | ||
}); | ||
}); | ||
let val = filterInfo.get('OR'); | ||
var val = filterInfo.get('OR'); | ||
if (val) | ||
where.push(new OrFilter(...val.map(x => unpackWhere(columns, x)))); | ||
let custom = filterInfo.get(exports.customUrlToken); | ||
where.push(new (OrFilter.bind.apply(OrFilter, tslib_1.__spread([void 0], val.map(function (x) { | ||
return unpackWhere(columns, x); | ||
}))))()); | ||
var custom = filterInfo.get(exports.customUrlToken); | ||
if (custom !== undefined) | ||
where.push(new Filter(x => x.custom(custom))); | ||
return new AndFilter(...where); | ||
where.push(new Filter(function (x) { return x.custom(custom); })); | ||
return new (AndFilter.bind.apply(AndFilter, tslib_1.__spread([void 0], where)))(); | ||
} | ||
exports.extractWhere = extractWhere; | ||
class CustomFilterBuilder { | ||
constructor(translateFilter) { | ||
var CustomFilterBuilder = /** @class */ (function () { | ||
function CustomFilterBuilder(translateFilter) { | ||
this.translateFilter = translateFilter; | ||
} | ||
build(custom) { | ||
return new Filter(x => x.custom(custom)); | ||
} | ||
} | ||
CustomFilterBuilder.prototype.build = function (custom) { | ||
return new Filter(function (x) { return x.custom(custom); }); | ||
}; | ||
return CustomFilterBuilder; | ||
}()); | ||
exports.CustomFilterBuilder = CustomFilterBuilder; | ||
class customTranslator { | ||
constructor(translateCustom) { | ||
var customTranslator = /** @class */ (function () { | ||
function customTranslator(translateCustom) { | ||
this.translateCustom = translateCustom; | ||
@@ -334,70 +446,98 @@ this.commands = []; | ||
} | ||
applyTo(x) { | ||
this.commands.forEach(y => y(x)); | ||
} | ||
or(orElements) { | ||
let newOrElements; | ||
this.promises.push(Promise.all(orElements.map((element) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let c = new customTranslator(this.translateCustom); | ||
element.__applyToConsumer(c); | ||
yield c.resolve(); | ||
return new Filter(x => c.applyTo(x)); | ||
}))).then(x => { | ||
customTranslator.prototype.applyTo = function (x) { | ||
this.commands.forEach(function (y) { return y(x); }); | ||
}; | ||
customTranslator.prototype.or = function (orElements) { | ||
var _this = this; | ||
var newOrElements; | ||
this.promises.push(Promise.all(orElements.map(function (element) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var c; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
c = new customTranslator(this.translateCustom); | ||
element.__applyToConsumer(c); | ||
return [4 /*yield*/, c.resolve()]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/, new Filter(function (x) { return c.applyTo(x); })]; | ||
} | ||
}); | ||
}); })).then(function (x) { | ||
newOrElements = x; | ||
})); | ||
this.commands.push(x => x.or(newOrElements)); | ||
} | ||
isEqualTo(col, val) { | ||
this.commands.push(x => x.isEqualTo(col, val)); | ||
} | ||
isDifferentFrom(col, val) { | ||
this.commands.push(x => x.isDifferentFrom(col, val)); | ||
} | ||
isNull(col) { | ||
this.commands.push(x => x.isNull(col)); | ||
} | ||
isNotNull(col) { | ||
this.commands.push(x => x.isNotNull(col)); | ||
} | ||
isGreaterOrEqualTo(col, val) { | ||
this.commands.push(x => x.isGreaterOrEqualTo(col, val)); | ||
} | ||
isGreaterThan(col, val) { | ||
this.commands.push(x => x.isGreaterThan(col, val)); | ||
} | ||
isLessOrEqualTo(col, val) { | ||
this.commands.push(x => x.isLessOrEqualTo(col, val)); | ||
} | ||
isLessThan(col, val) { | ||
this.commands.push(x => x.isLessThan(col, val)); | ||
} | ||
containsCaseInsensitive(col, val) { | ||
this.commands.push(x => x.containsCaseInsensitive(col, val)); | ||
} | ||
startsWith(col, val) { | ||
this.commands.push(x => x.startsWith(col, val)); | ||
} | ||
isIn(col, val) { | ||
this.commands.push(x => x.isIn(col, val)); | ||
} | ||
custom(customItem) { | ||
this.promises.push((() => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let r = yield this.translateCustom(customItem); | ||
if (r) | ||
r.__applyToConsumer(this); | ||
}))()); | ||
} | ||
databaseCustom(custom) { | ||
this.commands.push(x => x.databaseCustom(custom)); | ||
} | ||
resolve() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
while (this.promises.length > 0) { | ||
let p = this.promises; | ||
this.promises = []; | ||
yield Promise.all(p); | ||
} | ||
this.commands.push(function (x) { return x.or(newOrElements); }); | ||
}; | ||
customTranslator.prototype.isEqualTo = function (col, val) { | ||
this.commands.push(function (x) { return x.isEqualTo(col, val); }); | ||
}; | ||
customTranslator.prototype.isDifferentFrom = function (col, val) { | ||
this.commands.push(function (x) { return x.isDifferentFrom(col, val); }); | ||
}; | ||
customTranslator.prototype.isNull = function (col) { | ||
this.commands.push(function (x) { return x.isNull(col); }); | ||
}; | ||
customTranslator.prototype.isNotNull = function (col) { | ||
this.commands.push(function (x) { return x.isNotNull(col); }); | ||
}; | ||
customTranslator.prototype.isGreaterOrEqualTo = function (col, val) { | ||
this.commands.push(function (x) { return x.isGreaterOrEqualTo(col, val); }); | ||
}; | ||
customTranslator.prototype.isGreaterThan = function (col, val) { | ||
this.commands.push(function (x) { return x.isGreaterThan(col, val); }); | ||
}; | ||
customTranslator.prototype.isLessOrEqualTo = function (col, val) { | ||
this.commands.push(function (x) { return x.isLessOrEqualTo(col, val); }); | ||
}; | ||
customTranslator.prototype.isLessThan = function (col, val) { | ||
this.commands.push(function (x) { return x.isLessThan(col, val); }); | ||
}; | ||
customTranslator.prototype.containsCaseInsensitive = function (col, val) { | ||
this.commands.push(function (x) { return x.containsCaseInsensitive(col, val); }); | ||
}; | ||
customTranslator.prototype.startsWith = function (col, val) { | ||
this.commands.push(function (x) { return x.startsWith(col, val); }); | ||
}; | ||
customTranslator.prototype.isIn = function (col, val) { | ||
this.commands.push(function (x) { return x.isIn(col, val); }); | ||
}; | ||
customTranslator.prototype.custom = function (customItem) { | ||
var _this = this; | ||
this.promises.push((function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var r; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.translateCustom(customItem)]; | ||
case 1: | ||
r = _a.sent(); | ||
if (r) | ||
r.__applyToConsumer(this); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); })()); | ||
}; | ||
customTranslator.prototype.databaseCustom = function (custom) { | ||
this.commands.push(function (x) { return x.databaseCustom(custom); }); | ||
}; | ||
customTranslator.prototype.resolve = function () { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var p; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(this.promises.length > 0)) return [3 /*break*/, 2]; | ||
p = this.promises; | ||
this.promises = []; | ||
return [4 /*yield*/, Promise.all(p)]; | ||
case 1: | ||
_a.sent(); | ||
return [3 /*break*/, 0]; | ||
case 2: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return customTranslator; | ||
}()); | ||
//# sourceMappingURL=filter-interfaces.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.IdEntity = void 0; | ||
const tslib_1 = require("tslib"); | ||
const uuid_1 = require("uuid"); | ||
const remult3_1 = require("./remult3"); | ||
class IdEntity extends remult3_1.EntityBase { | ||
} | ||
tslib_1.__decorate([ | ||
remult3_1.Field({ | ||
allowApiUpdate: false, | ||
defaultValue: () => uuid_1.v4() | ||
}), | ||
tslib_1.__metadata("design:type", String) | ||
], IdEntity.prototype, "id", void 0); | ||
var tslib_1 = require("tslib"); | ||
var uuid_1 = require("uuid"); | ||
var remult3_1 = require("./remult3"); | ||
var IdEntity = /** @class */ (function (_super) { | ||
tslib_1.__extends(IdEntity, _super); | ||
function IdEntity() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
tslib_1.__decorate([ | ||
remult3_1.Field({ | ||
allowApiUpdate: false, | ||
defaultValue: function () { return uuid_1.v4(); } | ||
}), | ||
tslib_1.__metadata("design:type", String) | ||
], IdEntity.prototype, "id", void 0); | ||
return IdEntity; | ||
}(remult3_1.EntityBase)); | ||
exports.IdEntity = IdEntity; | ||
//# sourceMappingURL=id-entity.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const tslib_1 = require("tslib"); | ||
var tslib_1 = require("tslib"); | ||
tslib_1.__exportStar(require("./remult3"), exports); | ||
tslib_1.__exportStar(require("./RepositoryImplementation"), exports); | ||
//# sourceMappingURL=index.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.prepareReceivedArgs = exports.prepareArgsToSend = exports.ProgressListener = exports.BackendMethod = exports.Controller = exports.serverActionField = exports.actionInfo = exports.myServerAction = exports.Action = void 0; | ||
const tslib_1 = require("tslib"); | ||
var tslib_1 = require("tslib"); | ||
require("reflect-metadata"); | ||
const context_1 = require("./context"); | ||
const sql_database_1 = require("./data-providers/sql-database"); | ||
const filter_interfaces_1 = require("./filter/filter-interfaces"); | ||
const remult3_1 = require("./remult3"); | ||
class Action { | ||
constructor(actionUrl, queue) { | ||
var context_1 = require("./context"); | ||
var sql_database_1 = require("./data-providers/sql-database"); | ||
var filter_interfaces_1 = require("./filter/filter-interfaces"); | ||
var remult3_1 = require("./remult3"); | ||
var Action = /** @class */ (function () { | ||
function Action(actionUrl, queue) { | ||
this.actionUrl = actionUrl; | ||
this.queue = queue; | ||
} | ||
run(pIn) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let r = yield Action.provider.post(context_1.Context.apiBaseUrl + '/' + this.actionUrl, pIn); | ||
let p = r; | ||
if (p && p.queuedJobId) { | ||
let progress = exports.actionInfo.startBusyWithProgress(); | ||
try { | ||
let runningJob; | ||
yield exports.actionInfo.runActionWithoutBlockingUI(() => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
while (!runningJob || !runningJob.done) { | ||
if (runningJob) | ||
yield new Promise(res => setTimeout(() => { | ||
res(undefined); | ||
}, 200)); | ||
runningJob = yield Action.provider.post(context_1.Context.apiBaseUrl + '/' + Action.apiUrlForJobStatus, { queuedJobId: r.queuedJobId }); | ||
if (runningJob.progress) { | ||
progress.progress(runningJob.progress); | ||
} | ||
} | ||
})); | ||
if (runningJob.error) | ||
throw runningJob.error; | ||
progress.progress(1); | ||
return runningJob.result; | ||
Action.prototype.run = function (pIn) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var r, p, progress_1, runningJob_1; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, Action.provider.post(context_1.Context.apiBaseUrl + '/' + this.actionUrl, pIn)]; | ||
case 1: | ||
r = _a.sent(); | ||
p = r; | ||
if (!(p && p.queuedJobId)) return [3 /*break*/, 6]; | ||
progress_1 = exports.actionInfo.startBusyWithProgress(); | ||
_a.label = 2; | ||
case 2: | ||
_a.trys.push([2, , 4, 5]); | ||
return [4 /*yield*/, exports.actionInfo.runActionWithoutBlockingUI(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(!runningJob_1 || !runningJob_1.done)) return [3 /*break*/, 4]; | ||
if (!runningJob_1) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, new Promise(function (res) { return setTimeout(function () { | ||
res(undefined); | ||
}, 200); })]; | ||
case 1: | ||
_a.sent(); | ||
_a.label = 2; | ||
case 2: return [4 /*yield*/, Action.provider.post(context_1.Context.apiBaseUrl + '/' + Action.apiUrlForJobStatus, { queuedJobId: r.queuedJobId })]; | ||
case 3: | ||
runningJob_1 = _a.sent(); | ||
if (runningJob_1.progress) { | ||
progress_1.progress(runningJob_1.progress); | ||
} | ||
return [3 /*break*/, 0]; | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); })]; | ||
case 3: | ||
_a.sent(); | ||
if (runningJob_1.error) | ||
throw runningJob_1.error; | ||
progress_1.progress(1); | ||
return [2 /*return*/, runningJob_1.result]; | ||
case 4: | ||
progress_1.close(); | ||
return [7 /*endfinally*/]; | ||
case 5: return [3 /*break*/, 7]; | ||
case 6: return [2 /*return*/, r]; | ||
case 7: return [2 /*return*/]; | ||
} | ||
finally { | ||
progress.close(); | ||
}); | ||
}); | ||
}; | ||
Action.prototype.__register = function (reg) { | ||
var _this = this; | ||
reg(this.actionUrl, this.queue, function (d, req, res) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var r, err_1; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
_a.trys.push([0, 2, , 3]); | ||
return [4 /*yield*/, this.execute(d, req, res)]; | ||
case 1: | ||
r = _a.sent(); | ||
res.success(r); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
err_1 = _a.sent(); | ||
res.error(err_1); | ||
return [3 /*break*/, 3]; | ||
case 3: return [2 /*return*/]; | ||
} | ||
} | ||
else | ||
return r; | ||
}); | ||
} | ||
__register(reg) { | ||
reg(this.actionUrl, this.queue, (d, req, res) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
try { | ||
var r = yield this.execute(d, req, res); | ||
res.success(r); | ||
} | ||
catch (err) { | ||
res.error(err); | ||
} | ||
})); | ||
} | ||
} | ||
}); | ||
}); }); | ||
}; | ||
Action.apiUrlForJobStatus = 'jobStatusInQueue'; | ||
return Action; | ||
}()); | ||
exports.Action = Action; | ||
Action.apiUrlForJobStatus = 'jobStatusInQueue'; | ||
class myServerAction extends Action { | ||
constructor(name, types, options, originalMethod) { | ||
super(name, options.queue); | ||
this.types = types; | ||
this.options = options; | ||
this.originalMethod = originalMethod; | ||
var myServerAction = /** @class */ (function (_super) { | ||
tslib_1.__extends(myServerAction, _super); | ||
function myServerAction(name, types, options, originalMethod) { | ||
var _this = _super.call(this, name, options.queue) || this; | ||
_this.types = types; | ||
_this.options = options; | ||
_this.originalMethod = originalMethod; | ||
return _this; | ||
} | ||
execute(info, context, res) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let result = { data: {} }; | ||
let ds = context._dataSource; | ||
yield ds.transaction((ds) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
context.setDataProvider(ds); | ||
if (!context.isAllowedForInstance(undefined, this.options.allowed)) | ||
throw 'not allowed'; | ||
info.args = yield prepareReceivedArgs(this.types, info.args, context, ds, res); | ||
try { | ||
result.data = yield this.originalMethod(info.args); | ||
myServerAction.prototype.execute = function (info, context, res) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var result, ds; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
result = { data: {} }; | ||
ds = context._dataSource; | ||
return [4 /*yield*/, ds.transaction(function (ds) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var _a, _b, err_2; | ||
return tslib_1.__generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
context.setDataProvider(ds); | ||
if (!context.isAllowedForInstance(undefined, this.options.allowed)) | ||
throw 'not allowed'; | ||
_a = info; | ||
return [4 /*yield*/, prepareReceivedArgs(this.types, info.args, context, ds, res)]; | ||
case 1: | ||
_a.args = _c.sent(); | ||
_c.label = 2; | ||
case 2: | ||
_c.trys.push([2, 4, , 5]); | ||
_b = result; | ||
return [4 /*yield*/, this.originalMethod(info.args)]; | ||
case 3: | ||
_b.data = _c.sent(); | ||
return [3 /*break*/, 5]; | ||
case 4: | ||
err_2 = _c.sent(); | ||
throw err_2; | ||
case 5: return [2 /*return*/]; | ||
} | ||
}); | ||
}); })]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/, result]; | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
})); | ||
return result; | ||
}); | ||
}); | ||
} | ||
} | ||
}; | ||
return myServerAction; | ||
}(Action)); | ||
exports.myServerAction = myServerAction; | ||
@@ -94,16 +154,16 @@ var isNode = new Function("try {return this===global;}catch(e){return false;}"); | ||
runningOnServer: isNode(), | ||
runActionWithoutBlockingUI: (what) => { return what(); }, | ||
startBusyWithProgress: () => ({ | ||
progress: (percent) => { }, | ||
close: () => { } | ||
}) | ||
runActionWithoutBlockingUI: function (what) { return what(); }, | ||
startBusyWithProgress: function () { return ({ | ||
progress: function (percent) { }, | ||
close: function () { } | ||
}); } | ||
}; | ||
exports.serverActionField = Symbol('serverActionField'); | ||
const methodHelpers = new Map(); | ||
const classOptions = new Map(); | ||
var methodHelpers = new Map(); | ||
var classOptions = new Map(); | ||
function Controller(key) { | ||
return function (target) { | ||
let r = target; | ||
classOptions.set(r, { key }); | ||
context_1.setControllerSettings(target, { key }); | ||
var r = target; | ||
classOptions.set(r, { key: key }); | ||
context_1.setControllerSettings(target, { key: key }); | ||
return target; | ||
@@ -114,3 +174,3 @@ }; | ||
function BackendMethod(options) { | ||
return (target, key, descriptor) => { | ||
return function (target, key, descriptor) { | ||
if (target.prototype !== undefined) { | ||
@@ -120,23 +180,39 @@ var originalMethod = descriptor.value; | ||
// if types are undefined - you've forgot to set: "emitDecoratorMetadata":true | ||
let serverAction = new myServerAction(key, types, options, args => originalMethod.apply(undefined, args)); | ||
descriptor.value = function (...args) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (!exports.actionInfo.runningOnServer) { | ||
args = prepareArgsToSend(types, args); | ||
if (options.blockUser === false) { | ||
return yield exports.actionInfo.runActionWithoutBlockingUI(() => tslib_1.__awaiter(this, void 0, void 0, function* () { return (yield serverAction.run({ args })).data; })); | ||
var serverAction_1 = new myServerAction(key, types, options, function (args) { return originalMethod.apply(undefined, args); }); | ||
descriptor.value = function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!!exports.actionInfo.runningOnServer) return [3 /*break*/, 5]; | ||
args = prepareArgsToSend(types, args); | ||
if (!(options.blockUser === false)) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, exports.actionInfo.runActionWithoutBlockingUI(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, serverAction_1.run({ args: args })]; | ||
case 1: return [2 /*return*/, (_a.sent()).data]; | ||
} | ||
}); }); })]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
case 2: return [4 /*yield*/, serverAction_1.run({ args: args })]; | ||
case 3: return [2 /*return*/, (_a.sent()).data]; | ||
case 4: return [3 /*break*/, 7]; | ||
case 5: return [4 /*yield*/, originalMethod.apply(undefined, args)]; | ||
case 6: return [2 /*return*/, (_a.sent())]; | ||
case 7: return [2 /*return*/]; | ||
} | ||
else | ||
return (yield serverAction.run({ args })).data; | ||
} | ||
else | ||
return (yield originalMethod.apply(undefined, args)); | ||
}); | ||
}); | ||
}; | ||
exports.actionInfo.allActions.push(descriptor.value); | ||
descriptor.value[exports.serverActionField] = serverAction; | ||
descriptor.value[exports.serverActionField] = serverAction_1; | ||
return descriptor; | ||
} | ||
var types = Reflect.getMetadata("design:paramtypes", target, key); | ||
let x = context_1.classHelpers.get(target.constructor); | ||
var x = context_1.classHelpers.get(target.constructor); | ||
if (!x) { | ||
@@ -146,153 +222,254 @@ x = new context_1.ClassHelper(); | ||
} | ||
let mh = new context_1.MethodHelper(); | ||
var mh = new context_1.MethodHelper(); | ||
methodHelpers.set(descriptor, mh); | ||
x.methods.push(mh); | ||
var originalMethod = descriptor.value; | ||
let serverAction = { | ||
__register(reg) { | ||
let c = new context_1.ServerContext(); | ||
for (const constructor of mh.classes.keys()) { | ||
let controllerOptions = mh.classes.get(constructor); | ||
var serverAction = { | ||
__register: function (reg) { | ||
var e_1, _a; | ||
var _this = this; | ||
var c = new context_1.ServerContext(); | ||
var _loop_1 = function (constructor) { | ||
var controllerOptions = mh.classes.get(constructor); | ||
if (!controllerOptions.key) { | ||
controllerOptions.key = c.for(constructor).metadata.key + "_methods"; | ||
} | ||
reg(controllerOptions.key + '/' + key, options ? options.queue : false, (d, req, res) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
d.args = d.args.map(x => isCustomUndefined(x) ? undefined : x); | ||
let allowed = options.allowed; | ||
try { | ||
let context = req; | ||
let ds = context._dataSource; | ||
let r; | ||
yield ds.transaction((ds) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
context.setDataProvider(ds); | ||
d.args = yield prepareReceivedArgs(types, d.args, context, ds, res); | ||
if (context_1.allEntities.includes(constructor)) { | ||
let repo = context.for(constructor); | ||
let y; | ||
if (d.rowInfo.isNewRow) { | ||
y = repo.create(); | ||
let rowHelper = repo.getEntityRef(y); | ||
rowHelper._updateEntityBasedOnApi(d.rowInfo.data); | ||
} | ||
else { | ||
let rows = yield repo.find({ | ||
where: x => { | ||
let where = repo.metadata.idMetadata.getIdFilter(d.rowInfo.id); | ||
if (this.options && this.options.get && this.options.get.where) | ||
where = new filter_interfaces_1.AndFilter(where, this.options.get.where(x)); | ||
return where; | ||
} | ||
}); | ||
if (rows.length != 1) | ||
throw new Error("not found or too many matches"); | ||
y = rows[0]; | ||
repo.getEntityRef(y)._updateEntityBasedOnApi(d.rowInfo.data); | ||
} | ||
if (!context.isAllowedForInstance(y, allowed)) | ||
throw 'not allowed'; | ||
let defs = remult3_1.getEntityRef(y); | ||
yield defs.__validateEntity(); | ||
try { | ||
r = { | ||
result: yield originalMethod.apply(y, d.args), | ||
rowInfo: { | ||
data: yield defs.toApiJson(), | ||
isNewRow: defs.isNew(), | ||
wasChanged: defs.wasChanged(), | ||
id: defs.getOriginalId() | ||
} | ||
}; | ||
} | ||
catch (err) { | ||
throw defs.catchSaveErrors(err); | ||
} | ||
} | ||
else { | ||
let y = new constructor(context, ds); | ||
let controllerRef = remult3_1.getControllerRef(y, context); | ||
controllerRef._updateEntityBasedOnApi(d.fields); | ||
yield Promise.all([...controllerRef.fields].map(x => x.load())); | ||
if (!context.isAllowedForInstance(y, allowed)) | ||
throw 'not allowed'; | ||
yield controllerRef.__validateEntity(); | ||
try { | ||
r = { | ||
result: yield originalMethod.apply(y, d.args), | ||
fields: yield controllerRef.toApiJson() | ||
}; | ||
} | ||
catch (err) { | ||
throw controllerRef.catchSaveErrors(err); | ||
} | ||
} | ||
})); | ||
res.success(r); | ||
} | ||
catch (err) { | ||
res.error(err); | ||
} | ||
})); | ||
reg(controllerOptions.key + '/' + key, options ? options.queue : false, function (d, req, res) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var allowed, context_2, ds, r_1, err_3; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
d.args = d.args.map(function (x) { return isCustomUndefined(x) ? undefined : x; }); | ||
allowed = options.allowed; | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
context_2 = req; | ||
ds = context_2._dataSource; | ||
return [4 /*yield*/, ds.transaction(function (ds) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var _a, repo_1, y, rowHelper, rows, defs, err_4, y, controllerRef, err_5; | ||
var _b, _c, _d; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_e) { | ||
switch (_e.label) { | ||
case 0: | ||
context_2.setDataProvider(ds); | ||
_a = d; | ||
return [4 /*yield*/, prepareReceivedArgs(types, d.args, context_2, ds, res)]; | ||
case 1: | ||
_a.args = _e.sent(); | ||
if (!context_1.allEntities.includes(constructor)) return [3 /*break*/, 11]; | ||
repo_1 = context_2.for(constructor); | ||
y = void 0; | ||
if (!d.rowInfo.isNewRow) return [3 /*break*/, 2]; | ||
y = repo_1.create(); | ||
rowHelper = repo_1.getEntityRef(y); | ||
rowHelper._updateEntityBasedOnApi(d.rowInfo.data); | ||
return [3 /*break*/, 4]; | ||
case 2: return [4 /*yield*/, repo_1.find({ | ||
where: function (x) { | ||
var where = repo_1.metadata.idMetadata.getIdFilter(d.rowInfo.id); | ||
if (_this.options && _this.options.get && _this.options.get.where) | ||
where = new filter_interfaces_1.AndFilter(where, _this.options.get.where(x)); | ||
return where; | ||
} | ||
})]; | ||
case 3: | ||
rows = _e.sent(); | ||
if (rows.length != 1) | ||
throw new Error("not found or too many matches"); | ||
y = rows[0]; | ||
repo_1.getEntityRef(y)._updateEntityBasedOnApi(d.rowInfo.data); | ||
_e.label = 4; | ||
case 4: | ||
if (!context_2.isAllowedForInstance(y, allowed)) | ||
throw 'not allowed'; | ||
defs = remult3_1.getEntityRef(y); | ||
return [4 /*yield*/, defs.__validateEntity()]; | ||
case 5: | ||
_e.sent(); | ||
_e.label = 6; | ||
case 6: | ||
_e.trys.push([6, 9, , 10]); | ||
_b = {}; | ||
return [4 /*yield*/, originalMethod.apply(y, d.args)]; | ||
case 7: | ||
_b.result = _e.sent(); | ||
_c = {}; | ||
return [4 /*yield*/, defs.toApiJson()]; | ||
case 8: | ||
r_1 = (_b.rowInfo = (_c.data = _e.sent(), | ||
_c.isNewRow = defs.isNew(), | ||
_c.wasChanged = defs.wasChanged(), | ||
_c.id = defs.getOriginalId(), | ||
_c), | ||
_b); | ||
return [3 /*break*/, 10]; | ||
case 9: | ||
err_4 = _e.sent(); | ||
throw defs.catchSaveErrors(err_4); | ||
case 10: return [3 /*break*/, 18]; | ||
case 11: | ||
y = new constructor(context_2, ds); | ||
controllerRef = remult3_1.getControllerRef(y, context_2); | ||
controllerRef._updateEntityBasedOnApi(d.fields); | ||
return [4 /*yield*/, Promise.all(tslib_1.__spread(controllerRef.fields).map(function (x) { return x.load(); }))]; | ||
case 12: | ||
_e.sent(); | ||
if (!context_2.isAllowedForInstance(y, allowed)) | ||
throw 'not allowed'; | ||
return [4 /*yield*/, controllerRef.__validateEntity()]; | ||
case 13: | ||
_e.sent(); | ||
_e.label = 14; | ||
case 14: | ||
_e.trys.push([14, 17, , 18]); | ||
_d = {}; | ||
return [4 /*yield*/, originalMethod.apply(y, d.args)]; | ||
case 15: | ||
_d.result = _e.sent(); | ||
return [4 /*yield*/, controllerRef.toApiJson()]; | ||
case 16: | ||
r_1 = (_d.fields = _e.sent(), | ||
_d); | ||
return [3 /*break*/, 18]; | ||
case 17: | ||
err_5 = _e.sent(); | ||
throw controllerRef.catchSaveErrors(err_5); | ||
case 18: return [2 /*return*/]; | ||
} | ||
}); | ||
}); })]; | ||
case 2: | ||
_a.sent(); | ||
res.success(r_1); | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
err_3 = _a.sent(); | ||
res.error(err_3); | ||
return [3 /*break*/, 4]; | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
}; | ||
try { | ||
for (var _b = tslib_1.__values(mh.classes.keys()), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var constructor = _c.value; | ||
_loop_1(constructor); | ||
} | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
} | ||
}; | ||
descriptor.value = function (...args) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (!exports.actionInfo.runningOnServer) { | ||
let self = this; | ||
args = prepareArgsToSend(types, args); | ||
if (context_1.allEntities.includes(target.constructor)) { | ||
let defs = remult3_1.getEntityRef(self); | ||
yield defs.__validateEntity(); | ||
let classOptions = mh.classes.get(self.constructor); | ||
if (!classOptions.key) { | ||
classOptions.key = defs.repository.metadata.key + "_methods"; | ||
} | ||
try { | ||
let r = yield (new class extends Action { | ||
execute(a, b) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
throw ('should get here'); | ||
descriptor.value = function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var self_1, defs, classOptions_1, r, _a, _b, err_6, defs, r, _c, _d, e_2; | ||
var _e, _f, _g; | ||
return tslib_1.__generator(this, function (_h) { | ||
switch (_h.label) { | ||
case 0: | ||
if (!!exports.actionInfo.runningOnServer) return [3 /*break*/, 15]; | ||
self_1 = this; | ||
args = prepareArgsToSend(types, args); | ||
if (!context_1.allEntities.includes(target.constructor)) return [3 /*break*/, 8]; | ||
defs = remult3_1.getEntityRef(self_1); | ||
return [4 /*yield*/, defs.__validateEntity()]; | ||
case 1: | ||
_h.sent(); | ||
classOptions_1 = mh.classes.get(self_1.constructor); | ||
if (!classOptions_1.key) { | ||
classOptions_1.key = defs.repository.metadata.key + "_methods"; | ||
} | ||
_h.label = 2; | ||
case 2: | ||
_h.trys.push([2, 6, , 7]); | ||
_b = (_a = new /** @class */ (function (_super) { | ||
tslib_1.__extends(class_1, _super); | ||
function class_1() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
class_1.prototype.execute = function (a, b) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
throw ('should get here'); | ||
}); | ||
}); | ||
}; | ||
return class_1; | ||
}(Action))(classOptions_1.key + "/" + key, options ? options.queue : false)).run; | ||
_e = { | ||
args: args | ||
}; | ||
_f = {}; | ||
return [4 /*yield*/, defs.toApiJson()]; | ||
case 3: return [4 /*yield*/, (_b.apply(_a, [(_e.rowInfo = (_f.data = _h.sent(), | ||
_f.isNewRow = defs.isNew(), | ||
_f.wasChanged = defs.wasChanged(), | ||
_f.id = defs.getOriginalId(), | ||
_f), | ||
_e)]))]; | ||
case 4: | ||
r = _h.sent(); | ||
return [4 /*yield*/, defs._updateEntityBasedOnApi(r.rowInfo.data)]; | ||
case 5: | ||
_h.sent(); | ||
return [2 /*return*/, r.result]; | ||
case 6: | ||
err_6 = _h.sent(); | ||
defs.catchSaveErrors(err_6); | ||
throw err_6; | ||
case 7: return [3 /*break*/, 14]; | ||
case 8: | ||
defs = remult3_1.getControllerRef(self_1, undefined); | ||
_h.label = 9; | ||
case 9: | ||
_h.trys.push([9, 13, , 14]); | ||
return [4 /*yield*/, defs.__validateEntity()]; | ||
case 10: | ||
_h.sent(); | ||
_d = (_c = new /** @class */ (function (_super) { | ||
tslib_1.__extends(class_2, _super); | ||
function class_2() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
}(classOptions.key + "/" + key, options ? options.queue : false).run({ | ||
args, | ||
rowInfo: { | ||
data: yield defs.toApiJson(), | ||
isNewRow: defs.isNew(), | ||
wasChanged: defs.wasChanged(), | ||
id: defs.getOriginalId() | ||
} | ||
})); | ||
yield defs._updateEntityBasedOnApi(r.rowInfo.data); | ||
return r.result; | ||
} | ||
catch (err) { | ||
defs.catchSaveErrors(err); | ||
throw err; | ||
} | ||
} | ||
else { | ||
let defs = remult3_1.getControllerRef(self, undefined); | ||
try { | ||
yield defs.__validateEntity(); | ||
let r = yield (new class extends Action { | ||
execute(a, b) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
throw ('should get here'); | ||
class_2.prototype.execute = function (a, b) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
throw ('should get here'); | ||
}); | ||
}); | ||
} | ||
}(mh.classes.get(this.constructor).key + "/" + key, options ? options.queue : false).run({ | ||
args, | ||
fields: yield defs.toApiJson() | ||
})); | ||
}; | ||
return class_2; | ||
}(Action))(mh.classes.get(this.constructor).key + "/" + key, options ? options.queue : false)).run; | ||
_g = { | ||
args: args | ||
}; | ||
return [4 /*yield*/, defs.toApiJson()]; | ||
case 11: return [4 /*yield*/, (_d.apply(_c, [(_g.fields = _h.sent(), | ||
_g)]))]; | ||
case 12: | ||
r = _h.sent(); | ||
defs._updateEntityBasedOnApi(r.fields); | ||
return r.result; | ||
} | ||
catch (e) { | ||
throw defs.catchSaveErrors(e); | ||
} | ||
return [2 /*return*/, r.result]; | ||
case 13: | ||
e_2 = _h.sent(); | ||
throw defs.catchSaveErrors(e_2); | ||
case 14: return [3 /*break*/, 17]; | ||
case 15: return [4 /*yield*/, originalMethod.apply(this, args)]; | ||
case 16: return [2 /*return*/, (_h.sent())]; | ||
case 17: return [2 /*return*/]; | ||
} | ||
} | ||
else | ||
return (yield originalMethod.apply(this, args)); | ||
}); | ||
}); | ||
@@ -306,3 +483,3 @@ }; | ||
exports.BackendMethod = BackendMethod; | ||
const customUndefined = { | ||
var customUndefined = { | ||
_isUndefined: true | ||
@@ -313,28 +490,40 @@ }; | ||
} | ||
class ProgressListener { | ||
constructor(res) { | ||
var ProgressListener = /** @class */ (function () { | ||
function ProgressListener(res) { | ||
this.res = res; | ||
} | ||
progress(progress) { | ||
ProgressListener.prototype.progress = function (progress) { | ||
this.res.progress(progress); | ||
} | ||
} | ||
}; | ||
return ProgressListener; | ||
}()); | ||
exports.ProgressListener = ProgressListener; | ||
function prepareArgsToSend(types, args) { | ||
var e_3, _a; | ||
if (types) { | ||
for (let index = 0; index < types.length; index++) { | ||
const paramType = types[index]; | ||
for (const type of [context_1.Context, context_1.ServerContext, sql_database_1.SqlDatabase]) { | ||
if (paramType instanceof type) { | ||
args[index] = undefined; | ||
for (var index = 0; index < types.length; index++) { | ||
var paramType = types[index]; | ||
try { | ||
for (var _b = (e_3 = void 0, tslib_1.__values([context_1.Context, context_1.ServerContext, sql_database_1.SqlDatabase])), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var type = _c.value; | ||
if (paramType instanceof type) { | ||
args[index] = undefined; | ||
} | ||
} | ||
} | ||
catch (e_3_1) { e_3 = { error: e_3_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
} | ||
if (args[index] != undefined) { | ||
let x = { valueType: paramType }; | ||
var x = { valueType: paramType }; | ||
x = remult3_1.decorateColumnSettings(x); | ||
if (x.valueConverter) | ||
args[index] = x.valueConverter.toJson(args[index]); | ||
let eo = remult3_1.getEntitySettings(paramType, false); | ||
var eo = remult3_1.getEntitySettings(paramType, false); | ||
if (eo != null) { | ||
let rh = remult3_1.getEntityRef(args[index]); | ||
var rh = remult3_1.getEntityRef(args[index]); | ||
args[index] = rh.getId(); | ||
@@ -345,39 +534,55 @@ } | ||
} | ||
return args.map(x => x !== undefined ? x : customUndefined); | ||
return args.map(function (x) { return x !== undefined ? x : customUndefined; }); | ||
} | ||
exports.prepareArgsToSend = prepareArgsToSend; | ||
function prepareReceivedArgs(types, args, context, ds, res) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
for (let index = 0; index < args.length; index++) { | ||
const element = args[index]; | ||
if (isCustomUndefined(element)) | ||
args[index] = undefined; | ||
} | ||
if (types) | ||
for (let i = 0; i < types.length; i++) { | ||
if (args.length < i) { | ||
args.push(undefined); | ||
} | ||
if (types[i] == context_1.Context || types[i] == context_1.ServerContext) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var index, element, i, x, eo, _a, _b; | ||
return tslib_1.__generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
for (index = 0; index < args.length; index++) { | ||
element = args[index]; | ||
if (isCustomUndefined(element)) | ||
args[index] = undefined; | ||
} | ||
if (!types) return [3 /*break*/, 7]; | ||
i = 0; | ||
_c.label = 1; | ||
case 1: | ||
if (!(i < types.length)) return [3 /*break*/, 7]; | ||
if (args.length < i) { | ||
args.push(undefined); | ||
} | ||
if (!(types[i] == context_1.Context || types[i] == context_1.ServerContext)) return [3 /*break*/, 2]; | ||
args[i] = context; | ||
} | ||
else if (types[i] == sql_database_1.SqlDatabase && ds) { | ||
return [3 /*break*/, 6]; | ||
case 2: | ||
if (!(types[i] == sql_database_1.SqlDatabase && ds)) return [3 /*break*/, 3]; | ||
args[i] = ds; | ||
} | ||
else if (types[i] == ProgressListener) { | ||
return [3 /*break*/, 6]; | ||
case 3: | ||
if (!(types[i] == ProgressListener)) return [3 /*break*/, 4]; | ||
args[i] = new ProgressListener(res); | ||
} | ||
else { | ||
let x = { valueType: types[i] }; | ||
return [3 /*break*/, 6]; | ||
case 4: | ||
x = { valueType: types[i] }; | ||
x = remult3_1.decorateColumnSettings(x); | ||
if (x.valueConverter) | ||
args[i] = x.valueConverter.fromJson(args[i]); | ||
let eo = remult3_1.getEntitySettings(types[i], false); | ||
if (eo != null) { | ||
if (!(args[i] === null || args[i] === undefined)) | ||
args[i] = yield context.for(types[i]).findId(args[i]); | ||
} | ||
} | ||
eo = remult3_1.getEntitySettings(types[i], false); | ||
if (!(eo != null)) return [3 /*break*/, 6]; | ||
if (!!(args[i] === null || args[i] === undefined)) return [3 /*break*/, 6]; | ||
_a = args; | ||
_b = i; | ||
return [4 /*yield*/, context.for(types[i]).findId(args[i])]; | ||
case 5: | ||
_a[_b] = _c.sent(); | ||
_c.label = 6; | ||
case 6: | ||
i++; | ||
return [3 /*break*/, 1]; | ||
case 7: return [2 /*return*/, args]; | ||
} | ||
return args; | ||
}); | ||
}); | ||
@@ -384,0 +589,0 @@ } |
108
src/sort.js
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Sort = void 0; | ||
const column_1 = require("./column"); | ||
class Sort { | ||
constructor(...segments) { | ||
var tslib_1 = require("tslib"); | ||
var column_1 = require("./column"); | ||
var Sort = /** @class */ (function () { | ||
function Sort() { | ||
var segments = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
segments[_i] = arguments[_i]; | ||
} | ||
this.Segments = segments; | ||
} | ||
reverse() { | ||
let r = new Sort(); | ||
for (const s of this.Segments) { | ||
r.Segments.push({ field: s.field, isDescending: !s.isDescending }); | ||
Sort.prototype.reverse = function () { | ||
var e_1, _a; | ||
var r = new Sort(); | ||
try { | ||
for (var _b = tslib_1.__values(this.Segments), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var s = _c.value; | ||
r.Segments.push({ field: s.field, isDescending: !s.isDescending }); | ||
} | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
return r; | ||
} | ||
static createSortOf(entityDefs) { | ||
let r = {}; | ||
for (const c of entityDefs.fields) { | ||
r[c.key] = new sortHelper(c); | ||
}; | ||
Sort.createSortOf = function (entityDefs) { | ||
var e_2, _a; | ||
var r = {}; | ||
try { | ||
for (var _b = tslib_1.__values(entityDefs.fields), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var c = _c.value; | ||
r[c.key] = new sortHelper(c); | ||
} | ||
} | ||
catch (e_2_1) { e_2 = { error: e_2_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
} | ||
return r; | ||
} | ||
static translateOrderByToSort(entityDefs, orderBy) { | ||
}; | ||
Sort.translateOrderByToSort = function (entityDefs, orderBy) { | ||
if (!orderBy) | ||
return undefined; | ||
let entity = Sort.createSortOf(entityDefs); | ||
let resultOrder = orderBy(entity); // | ||
let sort; | ||
var entity = Sort.createSortOf(entityDefs); | ||
var resultOrder = orderBy(entity); // | ||
var sort; | ||
if (Array.isArray(resultOrder)) | ||
sort = new Sort(...resultOrder); | ||
sort = new (Sort.bind.apply(Sort, tslib_1.__spread([void 0], resultOrder)))(); | ||
else { | ||
@@ -37,32 +64,49 @@ if (!resultOrder) | ||
return sort; | ||
} | ||
static createUniqueSort(entityMetadata, orderBy) { | ||
}; | ||
Sort.createUniqueSort = function (entityMetadata, orderBy) { | ||
var e_3, _a; | ||
if (!orderBy) | ||
orderBy = entityMetadata.options.defaultOrderBy; | ||
if (!orderBy) | ||
orderBy = x => ({ field: entityMetadata.idMetadata.field }); | ||
let sort = Sort.translateOrderByToSort(entityMetadata, orderBy); | ||
orderBy = function (x) { return ({ field: entityMetadata.idMetadata.field }); }; | ||
var sort = Sort.translateOrderByToSort(entityMetadata, orderBy); | ||
if (entityMetadata.idMetadata.field instanceof column_1.CompoundIdField) { | ||
for (const field of entityMetadata.idMetadata.field.fields) { | ||
if (!sort.Segments.find(x => x.field == field)) { | ||
var _loop_1 = function (field) { | ||
if (!sort.Segments.find(function (x) { return x.field == field; })) { | ||
sort.Segments.push({ field: field }); | ||
} | ||
}; | ||
try { | ||
for (var _b = tslib_1.__values(entityMetadata.idMetadata.field.fields), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var field = _c.value; | ||
_loop_1(field); | ||
} | ||
} | ||
catch (e_3_1) { e_3 = { error: e_3_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
} | ||
} | ||
else if (!sort.Segments.find(x => x.field == entityMetadata.idMetadata.field)) { | ||
else if (!sort.Segments.find(function (x) { return x.field == entityMetadata.idMetadata.field; })) { | ||
sort.Segments.push({ field: entityMetadata.idMetadata.field }); | ||
} | ||
return sort; | ||
} | ||
} | ||
}; | ||
return Sort; | ||
}()); | ||
exports.Sort = Sort; | ||
class sortHelper { | ||
constructor(field, isDescending = false) { | ||
var sortHelper = /** @class */ (function () { | ||
function sortHelper(field, isDescending) { | ||
if (isDescending === void 0) { isDescending = false; } | ||
this.field = field; | ||
this.isDescending = isDescending; | ||
} | ||
descending() { | ||
sortHelper.prototype.descending = function () { | ||
return new sortHelper(this.field, !this.isDescending); | ||
} | ||
} | ||
}; | ||
return sortHelper; | ||
}()); | ||
//# sourceMappingURL=sort.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Categories = exports.Products = void 0; | ||
const tslib_1 = require("tslib"); | ||
const remult3_1 = require("../remult3"); | ||
const models_1 = require("./testModel/models"); | ||
let Products = class Products { | ||
}; | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Number) | ||
], Products.prototype, "id", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], Products.prototype, "name", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Number) | ||
], Products.prototype, "price", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Boolean) | ||
], Products.prototype, "archived", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Date) | ||
], Products.prototype, "availableFrom", void 0); | ||
Products = tslib_1.__decorate([ | ||
remult3_1.Entity({ | ||
key: 'Products' | ||
}) | ||
], Products); | ||
var tslib_1 = require("tslib"); | ||
var remult3_1 = require("../remult3"); | ||
var models_1 = require("./testModel/models"); | ||
var Products = /** @class */ (function () { | ||
function Products() { | ||
} | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Number) | ||
], Products.prototype, "id", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], Products.prototype, "name", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Number) | ||
], Products.prototype, "price", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Boolean) | ||
], Products.prototype, "archived", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", Date) | ||
], Products.prototype, "availableFrom", void 0); | ||
Products = tslib_1.__decorate([ | ||
remult3_1.Entity({ | ||
key: 'Products' | ||
}) | ||
], Products); | ||
return Products; | ||
}()); | ||
exports.Products = Products; | ||
let r; | ||
let Categories = class Categories extends remult3_1.EntityBase { | ||
constructor() { | ||
super(...arguments); | ||
this.id = 0; | ||
var r; | ||
var Categories = /** @class */ (function (_super) { | ||
tslib_1.__extends(Categories, _super); | ||
function Categories() { | ||
var _this = _super !== null && _super.apply(this, arguments) || this; | ||
_this.id = 0; | ||
return _this; | ||
} | ||
}; | ||
tslib_1.__decorate([ | ||
remult3_1.Field({ | ||
dbName: 'CategoryID' | ||
}), | ||
tslib_1.__metadata("design:type", Number) | ||
], Categories.prototype, "id", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], Categories.prototype, "categoryName", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], Categories.prototype, "description", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field({ | ||
serverExpression: c => c.categoryName ? c.categoryName.length : undefined | ||
}), | ||
tslib_1.__metadata("design:type", Number) | ||
], Categories.prototype, "categoryNameLength", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field({ | ||
serverExpression: (c) => Promise.resolve(c.categoryName ? c.categoryName.length : undefined) | ||
}), | ||
tslib_1.__metadata("design:type", Number) | ||
], Categories.prototype, "categoryNameLengthAsync", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", models_1.Status) | ||
], Categories.prototype, "status", void 0); | ||
Categories = tslib_1.__decorate([ | ||
remult3_1.Entity({ | ||
key: 'Categories', | ||
allowApiCrud: true | ||
}) | ||
], Categories); | ||
tslib_1.__decorate([ | ||
remult3_1.Field({ | ||
dbName: 'CategoryID' | ||
}), | ||
tslib_1.__metadata("design:type", Number) | ||
], Categories.prototype, "id", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], Categories.prototype, "categoryName", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", String) | ||
], Categories.prototype, "description", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field({ | ||
serverExpression: function (c) { return c.categoryName ? c.categoryName.length : undefined; } | ||
}), | ||
tslib_1.__metadata("design:type", Number) | ||
], Categories.prototype, "categoryNameLength", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field({ | ||
serverExpression: function (c) { return Promise.resolve(c.categoryName ? c.categoryName.length : undefined); } | ||
}), | ||
tslib_1.__metadata("design:type", Number) | ||
], Categories.prototype, "categoryNameLengthAsync", void 0); | ||
tslib_1.__decorate([ | ||
remult3_1.Field(), | ||
tslib_1.__metadata("design:type", models_1.Status) | ||
], Categories.prototype, "status", void 0); | ||
Categories = tslib_1.__decorate([ | ||
remult3_1.Entity({ | ||
key: 'Categories', | ||
allowApiCrud: true | ||
}) | ||
], Categories); | ||
return Categories; | ||
}(remult3_1.EntityBase)); | ||
exports.Categories = Categories; | ||
//# sourceMappingURL=remult-3-entities.js.map |
"use strict"; | ||
var Status_1; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.TestStatus = exports.Status = void 0; | ||
const tslib_1 = require("tslib"); | ||
const remult3_1 = require("../../remult3"); | ||
let Status = Status_1 = class Status { | ||
constructor(id, name) { | ||
var tslib_1 = require("tslib"); | ||
var remult3_1 = require("../../remult3"); | ||
var Status = /** @class */ (function () { | ||
function Status(id, name) { | ||
this.id = id; | ||
this.name = name; | ||
} | ||
toString() { | ||
Status_1 = Status; | ||
Status.prototype.toString = function () { | ||
return this.name; | ||
} | ||
}; | ||
Status.open = new Status_1(0, "open"); | ||
Status.closed = new Status_1(1, "closed"); | ||
Status.hold = new Status_1(2, "hold"); | ||
Status = Status_1 = tslib_1.__decorate([ | ||
remult3_1.ValueListFieldType(Status_1), | ||
tslib_1.__metadata("design:paramtypes", [Number, String]) | ||
], Status); | ||
}; | ||
var Status_1; | ||
Status.open = new Status_1(0, "open"); | ||
Status.closed = new Status_1(1, "closed"); | ||
Status.hold = new Status_1(2, "hold"); | ||
Status = Status_1 = tslib_1.__decorate([ | ||
remult3_1.ValueListFieldType(Status_1), | ||
tslib_1.__metadata("design:paramtypes", [Number, String]) | ||
], Status); | ||
return Status; | ||
}()); | ||
exports.Status = Status; | ||
class TestStatus { | ||
constructor(id, caption) { | ||
var TestStatus = /** @class */ (function () { | ||
function TestStatus(id, caption) { | ||
this.id = id; | ||
this.caption = caption; | ||
} | ||
} | ||
TestStatus.open = new TestStatus(); | ||
TestStatus.closed = new TestStatus('cc'); | ||
TestStatus.hold = new TestStatus(undefined, 'hh'); | ||
return TestStatus; | ||
}()); | ||
exports.TestStatus = TestStatus; | ||
TestStatus.open = new TestStatus(); | ||
TestStatus.closed = new TestStatus('cc'); | ||
TestStatus.hold = new TestStatus(undefined, 'hh'); | ||
//# sourceMappingURL=models.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Validators = void 0; | ||
const tslib_1 = require("tslib"); | ||
class Validators { | ||
} | ||
exports.Validators = Validators; | ||
Validators.required = Object.assign((entity, col, message = 'Should not be empty') => { | ||
if (!col.value || col.value.trim().length == 0) | ||
col.error = message; | ||
}, { | ||
withMessage: (message) => { | ||
return (entity, col) => Validators.required(entity, col, message); | ||
var tslib_1 = require("tslib"); | ||
var Validators = /** @class */ (function () { | ||
function Validators() { | ||
} | ||
}); | ||
Validators.unique = Object.assign((entity, col, message = 'already exists') => tslib_1.__awaiter(void 0, void 0, void 0, function* () { | ||
if (!col.entityRef) | ||
throw "unique validation may only work on columns that are attached to an entity"; | ||
if (col.entityRef.isNew() || col.wasChanged()) { | ||
if (yield col.entityRef.repository.count(e => e[col.metadata.key].isEqualTo(col.value))) | ||
Validators.required = Object.assign(function (entity, col, message) { | ||
if (message === void 0) { message = 'Should not be empty'; } | ||
if (!col.value || col.value.trim().length == 0) | ||
col.error = message; | ||
} | ||
}), { | ||
withMessage: (message) => { | ||
return (entity, col) => Validators.unique(entity, col, message); | ||
} | ||
}); | ||
}, { | ||
withMessage: function (message) { | ||
return function (entity, col) { return Validators.required(entity, col, message); }; | ||
} | ||
}); | ||
Validators.unique = Object.assign(function (entity, col, message) { | ||
if (message === void 0) { message = 'already exists'; } | ||
return tslib_1.__awaiter(void 0, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!col.entityRef) | ||
throw "unique validation may only work on columns that are attached to an entity"; | ||
if (!(col.entityRef.isNew() || col.wasChanged())) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, col.entityRef.repository.count(function (e) { return e[col.metadata.key].isEqualTo(col.value); })]; | ||
case 1: | ||
if (_a.sent()) | ||
col.error = message; | ||
_a.label = 2; | ||
case 2: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}, { | ||
withMessage: function (message) { | ||
return function (entity, col) { return Validators.unique(entity, col, message); }; | ||
} | ||
}); | ||
return Validators; | ||
}()); | ||
exports.Validators = Validators; | ||
//# sourceMappingURL=validators.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.UrlBuilder = void 0; | ||
class UrlBuilder { | ||
constructor(url) { | ||
var UrlBuilder = /** @class */ (function () { | ||
function UrlBuilder(url) { | ||
this.url = url; | ||
} | ||
add(key, value) { | ||
UrlBuilder.prototype.add = function (key, value) { | ||
if (this.url.indexOf('?') >= 0) | ||
@@ -14,12 +14,14 @@ this.url += '&'; | ||
this.url += encodeURIComponent(key) + '=' + encodeURIComponent(value); | ||
} | ||
addObject(object, suffix = '') { | ||
}; | ||
UrlBuilder.prototype.addObject = function (object, suffix) { | ||
if (suffix === void 0) { suffix = ''; } | ||
if (object != undefined) | ||
for (var key in object) { | ||
let val = object[key]; | ||
var val = object[key]; | ||
this.add(key + suffix, val); | ||
} | ||
} | ||
} | ||
}; | ||
return UrlBuilder; | ||
}()); | ||
exports.UrlBuilder = UrlBuilder; | ||
//# sourceMappingURL=urlBuilder.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ValueListValueConverter = exports.DefaultValueConverter = exports.IntegerValueConverter = exports.NumberValueConverter = exports.BoolValueConverter = exports.CharDateValueConverter = exports.DateOnlyValueConverter = exports.DateValueConverter = void 0; | ||
const inputTypes_1 = require("./inputTypes"); | ||
const column_1 = require("./src/column"); | ||
var tslib_1 = require("tslib"); | ||
var inputTypes_1 = require("./inputTypes"); | ||
var column_1 = require("./src/column"); | ||
exports.DateValueConverter = { | ||
toJson: (val) => { | ||
toJson: function (val) { | ||
if (!val) | ||
@@ -18,3 +19,3 @@ return ''; | ||
}, | ||
fromJson: (val) => { | ||
fromJson: function (val) { | ||
if (val == undefined) | ||
@@ -28,7 +29,7 @@ return undefined; | ||
}, | ||
toDb: x => x, | ||
fromDb: x => x, | ||
fromInput: x => exports.DateValueConverter.fromJson(x), | ||
toInput: x => exports.DateValueConverter.toJson(x), | ||
displayValue: (val) => { | ||
toDb: function (x) { return x; }, | ||
fromDb: function (x) { return x; }, | ||
fromInput: function (x) { return exports.DateValueConverter.fromJson(x); }, | ||
toInput: function (x) { return exports.DateValueConverter.toJson(x); }, | ||
displayValue: function (val) { | ||
if (!val) | ||
@@ -40,5 +41,5 @@ return ''; | ||
exports.DateOnlyValueConverter = { | ||
fromInput: x => exports.DateOnlyValueConverter.fromJson(x), | ||
toInput: x => exports.DateOnlyValueConverter.toJson(x), | ||
toJson: (val) => { | ||
fromInput: function (x) { return exports.DateOnlyValueConverter.fromJson(x); }, | ||
toInput: function (x) { return exports.DateOnlyValueConverter.toJson(x); }, | ||
toJson: function (val) { | ||
var d = val; | ||
@@ -49,3 +50,3 @@ if (!d) | ||
}, | ||
fromJson: (value) => { | ||
fromJson: function (value) { | ||
if (!value || value == '' || value == '0000-00-00') | ||
@@ -56,3 +57,3 @@ return undefined; | ||
inputType: inputTypes_1.InputTypes.date, | ||
toDb: (val) => { | ||
toDb: function (val) { | ||
if (!val) | ||
@@ -63,3 +64,3 @@ return undefined; | ||
, | ||
fromDb: (val) => { | ||
fromDb: function (val) { | ||
var d = val; | ||
@@ -71,3 +72,3 @@ if (!d) | ||
fieldTypeInDb: 'date', | ||
displayValue: (value) => { | ||
displayValue: function (value) { | ||
if (!value) | ||
@@ -78,8 +79,8 @@ return ''; | ||
}; | ||
exports.CharDateValueConverter = Object.assign(Object.assign({}, exports.DateOnlyValueConverter), { toDb: (d) => { | ||
let val = exports.DateOnlyValueConverter.toJson(d); | ||
exports.CharDateValueConverter = tslib_1.__assign(tslib_1.__assign({}, exports.DateOnlyValueConverter), { toDb: function (d) { | ||
var val = exports.DateOnlyValueConverter.toJson(d); | ||
if (!val) | ||
return undefined; | ||
return val.replace(/-/g, ''); | ||
}, fromDb: (val) => { | ||
}, fromDb: function (val) { | ||
if (!val) | ||
@@ -90,8 +91,8 @@ return undefined; | ||
exports.BoolValueConverter = { | ||
toDb: (val) => val, | ||
toDb: function (val) { return val; }, | ||
inputType: inputTypes_1.InputTypes.checkbox, | ||
fromDb: (value) => { | ||
fromDb: function (value) { | ||
return exports.BoolValueConverter.fromJson(value); | ||
}, | ||
fromJson: value => { | ||
fromJson: function (value) { | ||
if (typeof value === "boolean") | ||
@@ -104,8 +105,8 @@ return value; | ||
}, | ||
toJson: x => x, | ||
fromInput: x => exports.BoolValueConverter.fromJson(x), | ||
toInput: x => exports.BoolValueConverter.toJson(x) | ||
toJson: function (x) { return x; }, | ||
fromInput: function (x) { return exports.BoolValueConverter.fromJson(x); }, | ||
toInput: function (x) { return exports.BoolValueConverter.toJson(x); } | ||
}; | ||
exports.NumberValueConverter = { | ||
fromDb: value => { | ||
fromDb: function (value) { | ||
if (value !== undefined) | ||
@@ -115,7 +116,7 @@ return +value; | ||
}, | ||
toDb: value => value, | ||
fromJson: value => exports.NumberValueConverter.fromDb(value), | ||
toJson: value => exports.NumberValueConverter.toDb(value), | ||
fromInput: (x, type) => { | ||
let r = +x; | ||
toDb: function (value) { return value; }, | ||
fromJson: function (value) { return exports.NumberValueConverter.fromDb(value); }, | ||
toJson: function (value) { return exports.NumberValueConverter.toDb(value); }, | ||
fromInput: function (x, type) { | ||
var r = +x; | ||
if (!x) | ||
@@ -125,3 +126,3 @@ return undefined; | ||
}, | ||
toInput: (x, type) => { | ||
toInput: function (x, type) { | ||
return x === null || x === void 0 ? void 0 : x.toString(); | ||
@@ -131,18 +132,18 @@ }, | ||
}; | ||
exports.IntegerValueConverter = Object.assign(Object.assign({}, exports.NumberValueConverter), { toJson: value => { | ||
let val = exports.NumberValueConverter.toDb(value); | ||
exports.IntegerValueConverter = tslib_1.__assign(tslib_1.__assign({}, exports.NumberValueConverter), { toJson: function (value) { | ||
var val = exports.NumberValueConverter.toDb(value); | ||
if (!val) | ||
return val; | ||
return +(+val).toFixed(0); | ||
}, toDb: value => exports.IntegerValueConverter.toJson(value), fieldTypeInDb: 'integer' }); | ||
}, toDb: function (value) { return exports.IntegerValueConverter.toJson(value); }, fieldTypeInDb: 'integer' }); | ||
exports.DefaultValueConverter = { | ||
fromJson: x => x, | ||
toJson: x => x, | ||
fromDb: x => x == null ? null : x ? JSON.parse(exports.DefaultValueConverter.fromJson(x)) : undefined, | ||
toDb: x => x != undefined ? JSON.stringify(exports.DefaultValueConverter.toJson(x)) : undefined, | ||
fromInput: x => exports.DefaultValueConverter.fromJson(x), | ||
toInput: x => exports.DefaultValueConverter.toJson(x) | ||
fromJson: function (x) { return x; }, | ||
toJson: function (x) { return x; }, | ||
fromDb: function (x) { return x == null ? null : x ? JSON.parse(exports.DefaultValueConverter.fromJson(x)) : undefined; }, | ||
toDb: function (x) { return x != undefined ? JSON.stringify(exports.DefaultValueConverter.toJson(x)) : undefined; }, | ||
fromInput: function (x) { return exports.DefaultValueConverter.fromJson(x); }, | ||
toInput: function (x) { return exports.DefaultValueConverter.toJson(x); } | ||
}; | ||
class ValueListValueConverter { | ||
constructor(type) { | ||
var ValueListValueConverter = /** @class */ (function () { | ||
function ValueListValueConverter(type) { | ||
this.type = type; | ||
@@ -154,31 +155,31 @@ this.info = ValueListInfo.get(this.type); | ||
} | ||
fromJson(val) { | ||
ValueListValueConverter.prototype.fromJson = function (val) { | ||
return this.byId(val); | ||
} | ||
toJson(val) { | ||
}; | ||
ValueListValueConverter.prototype.toJson = function (val) { | ||
if (!val) | ||
return undefined; | ||
return val.id; | ||
} | ||
fromDb(val) { | ||
}; | ||
ValueListValueConverter.prototype.fromDb = function (val) { | ||
return this.fromJson(val); | ||
} | ||
toDb(val) { | ||
}; | ||
ValueListValueConverter.prototype.toDb = function (val) { | ||
return this.toJson(val); | ||
} | ||
toInput(val, inputType) { | ||
}; | ||
ValueListValueConverter.prototype.toInput = function (val, inputType) { | ||
return this.toJson(val); | ||
} | ||
fromInput(val, inputType) { | ||
}; | ||
ValueListValueConverter.prototype.fromInput = function (val, inputType) { | ||
return this.fromJson(val); | ||
} | ||
displayValue(val) { | ||
}; | ||
ValueListValueConverter.prototype.displayValue = function (val) { | ||
if (!val) | ||
return ''; | ||
return val.caption; | ||
} | ||
getOptions() { | ||
}; | ||
ValueListValueConverter.prototype.getOptions = function () { | ||
return this.info.getOptions(); | ||
} | ||
byId(key) { | ||
}; | ||
ValueListValueConverter.prototype.byId = function (key) { | ||
if (key === undefined) | ||
@@ -189,7 +190,8 @@ return undefined; | ||
return this.info.byId(key); | ||
} | ||
} | ||
}; | ||
return ValueListValueConverter; | ||
}()); | ||
exports.ValueListValueConverter = ValueListValueConverter; | ||
class ValueListInfo { | ||
constructor(valueListType) { | ||
var ValueListInfo = /** @class */ (function () { | ||
function ValueListInfo(valueListType) { | ||
this.valueListType = valueListType; | ||
@@ -199,4 +201,4 @@ this.byIdMap = new Map(); | ||
this.isNumeric = false; | ||
for (let member in this.valueListType) { | ||
let s = this.valueListType[member]; | ||
for (var member in this.valueListType) { | ||
var s = this.valueListType[member]; | ||
if (s instanceof this.valueListType) { | ||
@@ -214,4 +216,4 @@ if (s.id === undefined) | ||
} | ||
static get(type) { | ||
let r = typeCache.get(type); | ||
ValueListInfo.get = function (type) { | ||
var r = typeCache.get(type); | ||
if (!r) | ||
@@ -221,13 +223,14 @@ r = new ValueListInfo(type); | ||
return r; | ||
} | ||
getOptions() { | ||
}; | ||
ValueListInfo.prototype.getOptions = function () { | ||
return this.values; | ||
} | ||
byId(key) { | ||
}; | ||
ValueListInfo.prototype.byId = function (key) { | ||
if (this.isNumeric) | ||
key = +key; | ||
return this.byIdMap.get(key); | ||
} | ||
} | ||
const typeCache = new Map(); | ||
}; | ||
return ValueListInfo; | ||
}()); | ||
var typeCache = new Map(); | ||
//# sourceMappingURL=valueConverters.js.map |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
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
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
573950
8716