Comparing version 0.1.14 to 0.1.15
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.InputTypes = void 0; | ||
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; | ||
}()); | ||
class 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.14", | ||
"version": "0.1.15", | ||
"description": "remult core lib", | ||
@@ -5,0 +5,0 @@ "homepage": "https://remult.github.io/", |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
const 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; | ||
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) { | ||
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) { | ||
this.pool = pool; | ||
} | ||
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*/]; | ||
}); | ||
entityIsUsedForTheFirstTime(entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
}); | ||
}; | ||
PostgresDataProvider.prototype.getLimitSqlSyntax = function (limit, offset) { | ||
} | ||
getLimitSqlSyntax(limit, offset) { | ||
return ' limit ' + limit + ' offset ' + offset; | ||
}; | ||
PostgresDataProvider.prototype.createCommand = function () { | ||
} | ||
createCommand() { | ||
return new PostgresBridgeToSQLCommand(this.pool); | ||
}; | ||
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]; | ||
} | ||
}); | ||
} | ||
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.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*/]; | ||
} | ||
}); | ||
} | ||
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(); | ||
} | ||
}); | ||
}; | ||
return PostgresDataProvider; | ||
}()); | ||
} | ||
} | ||
exports.PostgresDataProvider = PostgresDataProvider; | ||
var PostgresBridgeToSQLCommand = /** @class */ (function () { | ||
function PostgresBridgeToSQLCommand(source) { | ||
class PostgresBridgeToSQLCommand { | ||
constructor(source) { | ||
this.source = source; | ||
this.values = []; | ||
} | ||
PostgresBridgeToSQLCommand.prototype.addParameterAndReturnSqlToken = function (val) { | ||
addParameterAndReturnSqlToken(val) { | ||
this.values.push(val); | ||
return '$' + this.values.length; | ||
}; | ||
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) { | ||
} | ||
execute(sql) { | ||
return this.source.query(sql, this.values).then(r => new PostgresBridgeToSQLQueryResult(r)); | ||
} | ||
} | ||
class PostgresBridgeToSQLQueryResult { | ||
constructor(r) { | ||
this.r = r; | ||
this.rows = r.rows; | ||
} | ||
PostgresBridgeToSQLQueryResult.prototype.getColumnKeyInResultForIndexInSelect = function (index) { | ||
getColumnKeyInResultForIndexInSelect(index) { | ||
return this.r.fields[index].name; | ||
}; | ||
return PostgresBridgeToSQLQueryResult; | ||
}()); | ||
} | ||
} | ||
function verifyStructureOfAllEntities(db) { | ||
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()]; | ||
} | ||
}); | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield new PostgresSchemaBuilder(db).verifyStructureOfAllEntities(); | ||
}); | ||
} | ||
exports.verifyStructureOfAllEntities = verifyStructureOfAllEntities; | ||
var PostgresSchemaBuilder = /** @class */ (function () { | ||
function PostgresSchemaBuilder(pool, schema) { | ||
class PostgresSchemaBuilder { | ||
constructor(pool, schema) { | ||
this.pool = pool; | ||
@@ -136,148 +91,49 @@ this.additionalWhere = ''; | ||
} | ||
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*/]; | ||
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); | ||
} | ||
} | ||
}); | ||
catch (err) { | ||
console.log("failed verify structore of " + (yield metadata.getDbName()) + " ", err); | ||
} | ||
} | ||
}); | ||
}; | ||
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*/]; | ||
} | ||
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.addColumnSqlSyntax = function (x, dbName) { | ||
var result = dbName; | ||
} | ||
addColumnSqlSyntax(x, dbName) { | ||
let result = dbName; | ||
if (x.valueConverter.fieldTypeInDb) { | ||
@@ -308,141 +164,55 @@ if (x.valueType == Number && !x.valueConverter.fieldTypeInDb) | ||
return result; | ||
}; | ||
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*/]; | ||
} | ||
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); | ||
} | ||
}); | ||
} | ||
catch (err) { | ||
console.log(err); | ||
} | ||
}); | ||
}; | ||
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); | ||
} | ||
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); | ||
} | ||
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 () { | ||
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))]; | ||
} | ||
}); | ||
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)); | ||
}); | ||
@@ -449,0 +219,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.JobsInQueueEntity = exports.EntityQueueStorage = exports.ExpressRequestBridgeToDataApiRequest = exports.SiteArea = exports.ExpressBridge = exports.initExpress = void 0; | ||
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"); | ||
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"); | ||
function initExpress(app, options) { | ||
@@ -20,3 +20,3 @@ if (!options) { | ||
if (!options.getUserFromRequest) { | ||
options.getUserFromRequest = function (x) { return x['user']; }; | ||
options.getUserFromRequest = x => x['user']; | ||
} | ||
@@ -31,15 +31,15 @@ if (options.bodySizeLimit === undefined) { | ||
app.use(bodyParser.urlencoded({ extended: true, limit: options.bodySizeLimit })); | ||
var builder; | ||
let builder; | ||
if (options.dataProvider) { | ||
var dataProvider_1 = options.dataProvider; | ||
if (typeof dataProvider_1 === 'function') | ||
builder = dataProvider_1; | ||
let dataProvider = options.dataProvider; | ||
if (typeof dataProvider === 'function') | ||
builder = dataProvider; | ||
else | ||
builder = function () { return dataProvider_1; }; | ||
builder = () => dataProvider; | ||
} | ||
else { | ||
builder = function () { return new json_data_provider_1.JsonDataProvider(new JsonEntityFileStorage_1.JsonEntityFileStorage('./db')); }; | ||
builder = () => new json_data_provider_1.JsonDataProvider(new JsonEntityFileStorage_1.JsonEntityFileStorage('./db')); | ||
} | ||
var result = new ExpressBridge(app, options.getUserFromRequest, new inProcessQueueHandler(options.queueStorage), options.initRequest, builder); | ||
var apiArea = result.addArea('/' + __1.Context.apiBaseUrl); | ||
let result = new ExpressBridge(app, options.getUserFromRequest, new inProcessQueueHandler(options.queueStorage), options.initRequest, builder); | ||
let apiArea = result.addArea('/' + __1.Context.apiBaseUrl); | ||
if (!options.disableAutoApi) { | ||
@@ -52,4 +52,4 @@ register_actions_on_server_1.registerActionsOnServer(apiArea); | ||
exports.initExpress = initExpress; | ||
var ExpressBridge = /** @class */ (function () { | ||
function ExpressBridge(app, getUserFromRequest, queue, initRequest, _dataProviderFactory) { | ||
class ExpressBridge { | ||
constructor(app, getUserFromRequest, queue, initRequest, _dataProviderFactory) { | ||
this.app = app; | ||
@@ -62,3 +62,3 @@ this.getUserFromRequest = getUserFromRequest; | ||
} | ||
ExpressBridge.prototype.addArea = function (rootUrl, isUserValidForArea) { | ||
addArea(rootUrl, isUserValidForArea) { | ||
var r = new SiteArea(this, this.app, rootUrl, this.logApiEndPoints, isUserValidForArea); | ||
@@ -69,15 +69,12 @@ if (!this.firstArea) { | ||
return r; | ||
}; | ||
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)]; | ||
}); | ||
} | ||
getValidContext(req) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return this.firstArea.getValidContext(req); | ||
}); | ||
}; | ||
return ExpressBridge; | ||
}()); | ||
} | ||
} | ||
exports.ExpressBridge = ExpressBridge; | ||
var SiteArea = /** @class */ (function () { | ||
function SiteArea(bridge, app, rootUrl, logApiEndpoints, isUserValidForArea) { | ||
class SiteArea { | ||
constructor(bridge, app, rootUrl, logApiEndpoints, isUserValidForArea) { | ||
this.bridge = bridge; | ||
@@ -89,9 +86,8 @@ this.app = app; | ||
} | ||
SiteArea.prototype.add = function (entityOrDataApiFactory) { | ||
var _this = this; | ||
var api; | ||
add(entityOrDataApiFactory) { | ||
let api; | ||
api = entityOrDataApiFactory; | ||
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(); | ||
let contextForRouteExtraction = new context_1.ServerContext(); | ||
contextForRouteExtraction.setReq({ clientIp: 'onServer', user: undefined, get: (r) => '', getHeader: (x) => "", getBaseUrl: () => '' }); | ||
let myRoute = api(contextForRouteExtraction).getRoute(); | ||
myRoute = this.rootUrl + '/' + myRoute; | ||
@@ -101,3 +97,3 @@ if (this.logApiEndpoints) | ||
this.app.route(myRoute) | ||
.get(this.process(function (c, req, res) { | ||
.get(this.process((c, req, res) => { | ||
if (req.get("__action") == "count") { | ||
@@ -108,150 +104,93 @@ return api(c).count(res, req); | ||
return api(c).getArray(res, req); | ||
})).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*/]; | ||
}); | ||
}); })); | ||
})).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); | ||
} | ||
}))); | ||
this.app.route(myRoute + '/:id') | ||
//@ts-ignore | ||
.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)]; | ||
}); }); })) | ||
.get(this.process((c, req, res, orig) => tslib_1.__awaiter(this, void 0, void 0, function* () { return api(c).get(res, orig.params.id); }))) | ||
//@ts-ignore | ||
.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)]; | ||
}); }); })) | ||
.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); }))) | ||
//@ts-ignore | ||
.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*/]; | ||
} | ||
}); | ||
}); }; | ||
}; | ||
.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); | ||
}); | ||
} | ||
; | ||
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]; | ||
} | ||
}); | ||
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.initQueue = function () { | ||
var _this = this; | ||
} | ||
initQueue() { | ||
this.addAction({ | ||
__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*/]; | ||
} | ||
}); | ||
}); }); | ||
__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); | ||
})); | ||
} | ||
}); | ||
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) | ||
this.initQueue = () => { }; | ||
} | ||
addAction(action) { | ||
action.__register((url, queue, what) => { | ||
let 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(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*/]; | ||
} | ||
}); | ||
}); })); | ||
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); | ||
}))); | ||
}); | ||
}; | ||
return SiteArea; | ||
}()); | ||
} | ||
} | ||
exports.SiteArea = SiteArea; | ||
var ExpressRequestBridgeToDataApiRequest = /** @class */ (function () { | ||
function ExpressRequestBridgeToDataApiRequest(r) { | ||
class ExpressRequestBridgeToDataApiRequest { | ||
constructor(r) { | ||
this.r = r; | ||
@@ -261,285 +200,210 @@ this.user = undefined; | ||
} | ||
ExpressRequestBridgeToDataApiRequest.prototype.get = function (key) { | ||
get(key) { | ||
return this.r.query[key]; | ||
}; | ||
ExpressRequestBridgeToDataApiRequest.prototype.getBaseUrl = function () { | ||
} | ||
getBaseUrl() { | ||
if (this.r.originalUrl) | ||
return this.r.originalUrl; | ||
return this.r.path; | ||
}; | ||
ExpressRequestBridgeToDataApiRequest.prototype.getHeader = function (key) { return this.r.headers[key]; }; | ||
} | ||
getHeader(key) { return this.r.headers[key]; } | ||
; | ||
return ExpressRequestBridgeToDataApiRequest; | ||
}()); | ||
} | ||
exports.ExpressRequestBridgeToDataApiRequest = ExpressRequestBridgeToDataApiRequest; | ||
var ExpressResponseBridgeToDataApiResponse = /** @class */ (function () { | ||
function ExpressResponseBridgeToDataApiResponse(r) { | ||
class ExpressResponseBridgeToDataApiResponse { | ||
constructor(r) { | ||
this.r = r; | ||
} | ||
ExpressResponseBridgeToDataApiResponse.prototype.forbidden = function () { | ||
forbidden() { | ||
this.r.sendStatus(403); | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.progress = function (progress) { | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.success = function (data) { | ||
} | ||
progress(progress) { | ||
} | ||
success(data) { | ||
this.r.json(data); | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.created = function (data) { | ||
} | ||
created(data) { | ||
this.r.statusCode = 201; | ||
this.r.json(data); | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.deleted = function () { | ||
} | ||
deleted() { | ||
this.r.sendStatus(204); | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.notFound = function () { | ||
} | ||
notFound() { | ||
this.r.sendStatus(404); | ||
}; | ||
ExpressResponseBridgeToDataApiResponse.prototype.error = function (data) { | ||
} | ||
error(data) { | ||
data = data_api_1.serializeError(data); | ||
this.r.status(400).json(data); | ||
}; | ||
return ExpressResponseBridgeToDataApiResponse; | ||
}()); | ||
} | ||
} | ||
function throwError() { | ||
throw "Invalid"; | ||
} | ||
var inProcessQueueHandler = /** @class */ (function () { | ||
function inProcessQueueHandler(storage) { | ||
class inProcessQueueHandler { | ||
constructor(storage) { | ||
this.storage = storage; | ||
this.actions = new Map(); | ||
} | ||
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]; | ||
} | ||
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) | ||
}); | ||
return id; | ||
}); | ||
}; | ||
inProcessQueueHandler.prototype.mapQueuedAction = function (url, what) { | ||
} | ||
mapQueuedAction(url, what) { | ||
this.actions.set(url, what); | ||
}; | ||
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()]; | ||
} | ||
}); | ||
} | ||
getJobInfo(queuedJobId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield this.storage.getJobInfo(queuedJobId); | ||
}); | ||
}; | ||
return inProcessQueueHandler; | ||
}()); | ||
var InMemoryQueueStorage = /** @class */ (function () { | ||
function InMemoryQueueStorage() { | ||
} | ||
} | ||
class InMemoryQueueStorage { | ||
constructor() { | ||
this.jobs = new Map(); | ||
} | ||
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)]; | ||
}); | ||
getJobInfo(queuedJobId) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return this.jobs.get(queuedJobId); | ||
}); | ||
}; | ||
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]; | ||
} | ||
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; | ||
} | ||
}); | ||
return id; | ||
}); | ||
}; | ||
return InMemoryQueueStorage; | ||
}()); | ||
var test = 0; | ||
var EntityQueueStorage = /** @class */ (function () { | ||
function EntityQueueStorage(context) { | ||
} | ||
} | ||
let test = 0; | ||
class EntityQueueStorage { | ||
constructor(context) { | ||
this.context = context; | ||
this.sync = Promise.resolve(); | ||
} | ||
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*/]; | ||
} | ||
}); | ||
}); } | ||
}]; | ||
} | ||
}); | ||
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.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]; | ||
} | ||
}); | ||
} | ||
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; | ||
}); | ||
}; | ||
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; | ||
} | ||
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)); | ||
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); | ||
exports.JobsInQueueEntity = JobsInQueueEntity; | ||
//# sourceMappingURL=expressBridge.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.JsonEntityFileStorage = void 0; | ||
var path = require("path"); | ||
var fs = require("fs"); | ||
var JsonEntityFileStorage = /** @class */ (function () { | ||
function JsonEntityFileStorage(folderPath) { | ||
const path = require("path"); | ||
const fs = require("fs"); | ||
class JsonEntityFileStorage { | ||
constructor(folderPath) { | ||
this.folderPath = folderPath; | ||
} | ||
JsonEntityFileStorage.prototype.getItem = function (entityDbName) { | ||
var fn = path.join(this.folderPath, entityDbName) + '.json'; | ||
getItem(entityDbName) { | ||
let fn = path.join(this.folderPath, entityDbName) + '.json'; | ||
if (fs.existsSync(fn)) { | ||
@@ -16,4 +16,4 @@ return fs.readFileSync(fn).toString(); | ||
return undefined; | ||
}; | ||
JsonEntityFileStorage.prototype.setItem = function (entityDbName, json) { | ||
} | ||
setItem(entityDbName, json) { | ||
if (!fs.existsSync(this.folderPath)) { | ||
@@ -23,6 +23,5 @@ 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; | ||
var server_action_1 = require("../src/server-action"); | ||
const server_action_1 = require("../src/server-action"); | ||
function registerActionsOnServer(area) { | ||
var addAction = function (a) { | ||
var x = a[server_action_1.serverActionField]; | ||
var addAction = (a) => { | ||
let 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(function (a) { | ||
server_action_1.actionInfo.allActions.forEach((a) => { | ||
addAction(a); | ||
@@ -17,0 +17,0 @@ }); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.registerEntitiesOnServer = void 0; | ||
var remult3_1 = require("../src/remult3"); | ||
var context_1 = require("../src/context"); | ||
var data_api_1 = require("../src/data-api"); | ||
const remult3_1 = require("../src/remult3"); | ||
const context_1 = require("../src/context"); | ||
const data_api_1 = require("../src/data-api"); | ||
function registerEntitiesOnServer(area) { | ||
var errors = ''; | ||
let errors = ''; | ||
//add Api Entries | ||
context_1.allEntities.forEach(function (e) { | ||
context_1.allEntities.forEach(e => { | ||
if (!(remult3_1.getEntitySettings(e).includeInApi === false)) | ||
area.add(function (c) { | ||
area.add(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') { | ||
var x = f; | ||
let 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; | ||
var tslib_1 = require("tslib"); | ||
var set_1 = require("../set"); | ||
var filter_interfaces_1 = require("./filter/filter-interfaces"); | ||
var remult3_1 = require("./remult3"); | ||
const tslib_1 = require("tslib"); | ||
const set_1 = require("../set"); | ||
const filter_interfaces_1 = require("./filter/filter-interfaces"); | ||
const remult3_1 = require("./remult3"); | ||
function makeTitle(name) { | ||
@@ -12,19 +12,15 @@ // insert a space before all caps | ||
// uppercase the first character | ||
.replace(/^./, function (str) { return str.toUpperCase(); }).replace('Email', 'eMail').replace(" I D", " ID"); | ||
.replace(/^./, (str) => str.toUpperCase()).replace('Email', 'eMail').replace(" I D", " ID"); | ||
} | ||
exports.makeTitle = makeTitle; | ||
var CompoundIdField = /** @class */ (function () { | ||
function CompoundIdField() { | ||
var columns = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
columns[_i] = arguments[_i]; | ||
} | ||
class CompoundIdField { | ||
constructor(...columns) { | ||
this.fields = columns; | ||
} | ||
CompoundIdField.prototype.getDbName = function () { | ||
getDbName() { | ||
return Promise.resolve(""); | ||
}; | ||
CompoundIdField.prototype.getId = function (instance) { | ||
var r = ""; | ||
this.fields.forEach(function (c) { | ||
} | ||
getId(instance) { | ||
let r = ""; | ||
this.fields.forEach(c => { | ||
if (r.length > 0) | ||
@@ -35,28 +31,22 @@ r += ','; | ||
return r; | ||
}; | ||
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) { | ||
} | ||
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) => { | ||
add.isEqualTo(c, id[i]); | ||
}); | ||
}); | ||
}; | ||
CompoundIdField.prototype.resultIdFilter = function (id, data) { | ||
var _this = this; | ||
return new filter_interfaces_1.Filter(function (add) { | ||
var idParts = []; | ||
} | ||
resultIdFilter(id, data) { | ||
return new filter_interfaces_1.Filter(add => { | ||
let idParts = []; | ||
if (id != undefined) | ||
idParts = id.split(','); | ||
_this.fields.forEach(function (c, i) { | ||
var val = undefined; | ||
this.fields.forEach((c, i) => { | ||
let val = undefined; | ||
if (i < idParts.length) | ||
@@ -69,27 +59,26 @@ val = idParts[i]; | ||
}); | ||
}; | ||
return CompoundIdField; | ||
}()); | ||
} | ||
} | ||
exports.CompoundIdField = CompoundIdField; | ||
var LookupColumn = /** @class */ (function () { | ||
function LookupColumn(repository, id) { | ||
class LookupColumn { | ||
constructor(repository, id) { | ||
this.repository = repository; | ||
this.id = id; | ||
} | ||
LookupColumn.prototype.setId = function (val) { | ||
setId(val) { | ||
if (this.repository.metadata.idMetadata.field.valueType == Number) | ||
val = +val; | ||
this.id = val; | ||
}; | ||
LookupColumn.prototype.waitLoadOf = function (id) { | ||
} | ||
waitLoadOf(id) { | ||
if (id === undefined || id === null) | ||
return null; | ||
return this.repository.getCachedByIdAsync(id); | ||
}; | ||
LookupColumn.prototype.get = function (id) { | ||
} | ||
get(id) { | ||
if (id === undefined || id === null) | ||
return null; | ||
return this.repository.getCachedById(id); | ||
}; | ||
LookupColumn.prototype.set = function (item) { | ||
} | ||
set(item) { | ||
if (item) { | ||
@@ -99,3 +88,3 @@ if (typeof item === "string" || typeof item === "number") | ||
else { | ||
var eo = remult3_1.getEntityRef(item, false); | ||
let eo = remult3_1.getEntityRef(item, false); | ||
if (eo) { | ||
@@ -113,23 +102,16 @@ this.repository.addToCache(item); | ||
} | ||
}; | ||
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)]; | ||
}); | ||
} | ||
get item() { | ||
return this.get(this.id); | ||
} | ||
waitLoad() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return this.waitLoadOf(this.id); | ||
}); | ||
}; | ||
return LookupColumn; | ||
}()); | ||
} | ||
} | ||
exports.LookupColumn = LookupColumn; | ||
9000; | ||
var OneToMany = /** @class */ (function () { | ||
function OneToMany(provider, settings) { | ||
class OneToMany { | ||
constructor(provider, settings) { | ||
this.provider = provider; | ||
@@ -140,63 +122,42 @@ this.settings = settings; | ||
} | ||
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; | ||
})]; | ||
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; | ||
}); | ||
}); | ||
}; | ||
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()]; | ||
}); | ||
} | ||
reload() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
this._currentPromise = undefined; | ||
return this.load(); | ||
}); | ||
}; | ||
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)]; | ||
}); | ||
} | ||
find() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return this.provider.find(this.settings); | ||
}); | ||
}; | ||
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]; | ||
} | ||
}); | ||
} | ||
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; | ||
}); | ||
}; | ||
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; | ||
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) { | ||
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) { | ||
this.http = http; | ||
} | ||
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()]; | ||
} | ||
}); | ||
post(url, data) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield retry(() => toPromise(this.http.post(url, data))); | ||
}); | ||
}; | ||
HttpProviderBridgeToRestDataProviderHttpProvider.prototype.delete = function (url) { | ||
} | ||
delete(url) { | ||
return toPromise(this.http.delete(url)); | ||
}; | ||
HttpProviderBridgeToRestDataProviderHttpProvider.prototype.put = function (url, data) { | ||
} | ||
put(url, data) { | ||
return toPromise(this.http.put(url, data)); | ||
}; | ||
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()]; | ||
} | ||
}); | ||
} | ||
get(url) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield retry(() => toPromise(this.http.get(url))); | ||
}); | ||
}; | ||
return HttpProviderBridgeToRestDataProviderHttpProvider; | ||
}()); | ||
} | ||
} | ||
function retry(what) { | ||
var _a; | ||
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*/]; | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
while (true) { | ||
try { | ||
return yield what(); | ||
} | ||
}); | ||
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) { | ||
var _this = this; | ||
var r; | ||
let r; | ||
if (p["toPromise"] !== undefined) { | ||
@@ -82,33 +58,27 @@ r = p["toPromise"](); | ||
r = p; | ||
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; | ||
} | ||
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 | ||
}); | ||
}); }); | ||
throw result; | ||
})); | ||
} | ||
exports.toPromise = toPromise; | ||
var Context = /** @class */ (function () { | ||
function Context(http) { | ||
class Context { | ||
constructor(http) { | ||
this._backend = server_action_1.actionInfo.runningOnServer; | ||
this._userChangeEvent = new EventSource(); | ||
this.repCache = new Map(); | ||
var provider; | ||
let provider; | ||
if (http) { | ||
@@ -124,15 +94,15 @@ provider = new HttpProviderBridgeToRestDataProviderHttpProvider(http); | ||
} | ||
Context.prototype.clearAllCache = function () { | ||
clearAllCache() { | ||
this.repCache.clear(); | ||
}; | ||
Context.prototype.authenticated = function () { | ||
} | ||
authenticated() { | ||
return this.user.id !== undefined; | ||
}; | ||
Context.prototype.getCookie = function (name) { | ||
} | ||
getCookie(name) { | ||
return ''; | ||
}; | ||
Context.prototype.getHost = function () { | ||
} | ||
getHost() { | ||
return ''; | ||
}; | ||
Context.prototype.getPathInUrl = function () { | ||
} | ||
getPathInUrl() { | ||
if (this.req) | ||
@@ -143,69 +113,38 @@ return this.req.getBaseUrl(); | ||
return undefined; | ||
}; | ||
Context.prototype.getOrigin = function () { | ||
} | ||
getOrigin() { | ||
return ''; | ||
}; | ||
Context.prototype.setDataProvider = function (dataProvider) { | ||
} | ||
setDataProvider(dataProvider) { | ||
this._dataSource = dataProvider; | ||
}; | ||
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*/]; | ||
} | ||
}); | ||
} | ||
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(); | ||
}); | ||
}; | ||
Context.prototype.isAllowedForInstance = function (instance, x) { | ||
var e_1, _a; | ||
} | ||
isAllowedForInstance(instance, x) { | ||
if (Array.isArray(x)) { | ||
{ | ||
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; | ||
} | ||
for (const item of x) { | ||
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; } | ||
} | ||
} | ||
@@ -218,23 +157,12 @@ } | ||
return this.isAllowed(x); | ||
}; | ||
Context.prototype.isAllowed = function (roles) { | ||
var e_2, _a; | ||
} | ||
isAllowed(roles) { | ||
if (roles == undefined) | ||
return undefined; | ||
if (roles instanceof Array) { | ||
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; | ||
} | ||
for (const role of roles) { | ||
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; | ||
@@ -253,10 +181,10 @@ } | ||
return false; | ||
}; | ||
Context.prototype.for = function (entity, dataProvider) { | ||
} | ||
for(entity, dataProvider) { | ||
if (dataProvider === undefined) | ||
dataProvider = this._dataSource; | ||
var dpCache = this.repCache.get(dataProvider); | ||
let dpCache = this.repCache.get(dataProvider); | ||
if (!dpCache) | ||
this.repCache.set(dataProvider, dpCache = new Map()); | ||
var r = dpCache.get(entity); | ||
let r = dpCache.get(entity); | ||
if (!r) { | ||
@@ -266,99 +194,71 @@ dpCache.set(entity, r = new RepositoryImplementation_1.RepositoryImplementation(entity, this, dataProvider)); | ||
return r; | ||
}; | ||
Context.prototype.setReq = function (req) { | ||
} | ||
setReq(req) { | ||
this.req = req; | ||
this._user = req.user ? req.user : undefined; | ||
}; | ||
Context.apiBaseUrl = 'api'; | ||
return Context; | ||
}()); | ||
} | ||
} | ||
exports.Context = Context; | ||
var ServerContext = /** @class */ (function (_super) { | ||
tslib_1.__extends(ServerContext, _super); | ||
function ServerContext(dp) { | ||
var _this = _super.call(this) || this; | ||
_this._backend = true; | ||
Context.apiBaseUrl = 'api'; | ||
class ServerContext extends Context { | ||
constructor(dp) { | ||
super(); | ||
this._backend = true; | ||
if (dp) | ||
_this.setDataProvider(dp); | ||
return _this; | ||
this.setDataProvider(dp); | ||
} | ||
ServerContext.prototype.getHost = function () { | ||
getHost() { | ||
if (!this.req) | ||
return undefined; | ||
return this.req.getHeader('host'); | ||
}; | ||
ServerContext.prototype.getPathInUrl = function () { | ||
} | ||
getPathInUrl() { | ||
if (!this.req) | ||
return undefined; | ||
return this.req.getBaseUrl(); | ||
}; | ||
ServerContext.prototype.getCookie = function (name) { | ||
var e_3, _a; | ||
} | ||
getCookie(name) { | ||
if (this.req) { | ||
var cookie = this.req.getHeader('cookie'); | ||
let cookie = this.req.getHeader('cookie'); | ||
if (cookie) | ||
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]; | ||
} | ||
for (const iterator of cookie.split(';')) { | ||
let 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; | ||
}; | ||
ServerContext.prototype.getOrigin = function () { | ||
} | ||
getOrigin() { | ||
if (!this.req) | ||
return undefined; | ||
return this.req.getHeader('origin'); | ||
}; | ||
return ServerContext; | ||
}(Context)); | ||
} | ||
} | ||
exports.ServerContext = ServerContext; | ||
exports.allEntities = []; | ||
exports.classHelpers = new Map(); | ||
var ClassHelper = /** @class */ (function () { | ||
function ClassHelper() { | ||
class ClassHelper { | ||
constructor() { | ||
this.methods = []; | ||
} | ||
return ClassHelper; | ||
}()); | ||
} | ||
exports.ClassHelper = ClassHelper; | ||
var MethodHelper = /** @class */ (function () { | ||
function MethodHelper() { | ||
class MethodHelper { | ||
constructor() { | ||
this.classes = new Map(); | ||
} | ||
return MethodHelper; | ||
}()); | ||
} | ||
exports.MethodHelper = MethodHelper; | ||
function setControllerSettings(target, options) { | ||
var e_4, _a; | ||
var r = target; | ||
let r = target; | ||
while (true) { | ||
var helper = exports.classHelpers.get(r); | ||
let helper = exports.classHelpers.get(r); | ||
if (helper) { | ||
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); | ||
} | ||
for (const m of helper.methods) { | ||
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; } | ||
} | ||
} | ||
var p = Object.getPrototypeOf(r.prototype); | ||
let p = Object.getPrototypeOf(r.prototype); | ||
if (p == null) | ||
@@ -370,74 +270,32 @@ break; | ||
exports.setControllerSettings = setControllerSettings; | ||
var Allow = /** @class */ (function () { | ||
function Allow() { | ||
} | ||
Allow.everyone = function () { return true; }; | ||
Allow.authenticated = function (context) { return context.authenticated(); }; | ||
return Allow; | ||
}()); | ||
class Allow { | ||
} | ||
exports.Allow = Allow; | ||
Allow.everyone = () => true; | ||
Allow.authenticated = (context) => context.authenticated(); | ||
exports.iterateConfig = { | ||
pageSize: 200 | ||
}; | ||
var EventSource = /** @class */ (function () { | ||
function EventSource() { | ||
var _this = this; | ||
class EventSource { | ||
constructor() { | ||
this.listeners = []; | ||
this.dispatcher = { | ||
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; }); | ||
}]; | ||
} | ||
}); | ||
}); } | ||
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); | ||
}; | ||
}) | ||
}; | ||
} | ||
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*/]; | ||
} | ||
}); | ||
fire() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
for (const l of this.listeners) { | ||
yield l(); | ||
} | ||
}); | ||
}; | ||
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; | ||
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) { | ||
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) { | ||
this.repository = repository; | ||
@@ -13,245 +13,143 @@ this.context = context; | ||
} | ||
DataApi.prototype.getRoute = function () { | ||
getRoute() { | ||
return this.options.name; | ||
}; | ||
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*/]; | ||
} | ||
}); | ||
} | ||
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.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*/]; | ||
} | ||
}); | ||
} | ||
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.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*/]; | ||
} | ||
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); | ||
} | ||
}); | ||
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); | ||
} | ||
}); | ||
}; | ||
DataApi.prototype.buildWhere = function (entity, request, filterBody) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
} | ||
buildWhere(entity, request, filterBody) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
var 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]; | ||
} | ||
}); | ||
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; | ||
}); | ||
}; | ||
DataApi.prototype.doOnId = function (response, id, what) { | ||
} | ||
doOnId(response, id, what) { | ||
var _a, _b; | ||
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*/]; | ||
} | ||
}); | ||
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); | ||
} | ||
}); | ||
}; | ||
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*/]; | ||
} | ||
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; | ||
} | ||
}); | ||
yield this.repository.getEntityRef(row).save(); | ||
response.success(this.repository.getEntityRef(row).toApiJson()); | ||
})); | ||
}); | ||
}; | ||
DataApi.prototype._getApiSettings = function () { | ||
var _this = this; | ||
var options = this.repository.metadata.options; | ||
} | ||
_getApiSettings() { | ||
let options = this.repository.metadata.options; | ||
if (options.allowApiCrud !== undefined) { | ||
@@ -270,10 +168,10 @@ if (options.allowApiDelete === undefined) | ||
allowRead: this.context.isAllowed(options.allowApiRead), | ||
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); }, | ||
allowUpdate: (e) => this.context.isAllowedForInstance(e, options.allowApiUpdate), | ||
allowDelete: (e) => this.context.isAllowedForInstance(e, options.allowApiDelete), | ||
allowInsert: (e) => this.context.isAllowedForInstance(e, options.allowApiInsert), | ||
requireId: this.context.isAllowed(options.apiRequireId), | ||
get: { | ||
where: function (x) { | ||
where: x => { | ||
if (options.apiDataFilter) { | ||
return options.apiDataFilter(x, _this.context); | ||
return options.apiDataFilter(x, this.context); | ||
} | ||
@@ -284,68 +182,41 @@ return undefined; | ||
}; | ||
}; | ||
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*/]; | ||
} | ||
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; | ||
} | ||
}); | ||
yield this.repository.getEntityRef(row).delete(); | ||
response.deleted(); | ||
})); | ||
}); | ||
}; | ||
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*/]; | ||
} | ||
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; | ||
} | ||
}); | ||
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) { | ||
var dirItems = []; | ||
let dirItems = []; | ||
if (dirUrlParam) | ||
dirItems = dirUrlParam.split(','); | ||
return function (x) { | ||
return sortUrlParm.split(',').map(function (name, i) { | ||
var r = x[name.trim()]; | ||
return x => { | ||
return sortUrlParm.split(',').map((name, i) => { | ||
let r = x[name.trim()]; | ||
if (i < dirItems.length && dirItems[i].toLowerCase().trim().startsWith("d")) | ||
@@ -362,3 +233,3 @@ return { field: r.field, isDescending: true }; | ||
} | ||
var x = JSON.parse(JSON.stringify(data)); | ||
let x = JSON.parse(JSON.stringify(data)); | ||
if (!x.message && !x.modelState) | ||
@@ -365,0 +236,0 @@ data = { message: data.message, stack: data.stack }; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.extractSort = void 0; | ||
var sort_1 = require("./sort"); | ||
const sort_1 = require("./sort"); | ||
function extractSort(sort) { | ||
@@ -9,7 +9,7 @@ if (sort instanceof sort_1.Sort) | ||
if (sort instanceof Array) { | ||
var r_1 = new sort_1.Sort(); | ||
sort.forEach(function (i) { | ||
r_1.Segments.push(i); | ||
let r = new sort_1.Sort(); | ||
sort.forEach(i => { | ||
r.Segments.push(i); | ||
}); | ||
return r_1; | ||
return r; | ||
} | ||
@@ -16,0 +16,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ArrayEntityDataProvider = void 0; | ||
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) { | ||
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) { | ||
this.entity = entity; | ||
@@ -15,119 +15,88 @@ this.rows = rows; | ||
} | ||
ArrayEntityDataProvider.customFilter = function (filter) { | ||
return new filter_interfaces_1.Filter(function (x) { return x.databaseCustom({ | ||
static customFilter(filter) { | ||
return new filter_interfaces_1.Filter(x => x.databaseCustom({ | ||
arrayFilter: filter | ||
}); }); | ||
}; | ||
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) { | ||
})); | ||
} | ||
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) | ||
j++; | ||
} | ||
else { | ||
x = new FilterConsumerBridgeToObject(rows[i]); | ||
where.__applyToConsumer(x); | ||
if (x.ok) | ||
j++; | ||
} | ||
} | ||
return [2 /*return*/, j]; | ||
}); | ||
} | ||
return j; | ||
}); | ||
}; | ||
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; | ||
} | ||
} | ||
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; | ||
} | ||
return r; | ||
}); | ||
} | ||
rows = pageArray(rows, options); | ||
} | ||
return r; | ||
}); | ||
} | ||
if (rows) | ||
return [2 /*return*/, rows.map(function (i) { | ||
return _this.translateFromJson(i); | ||
})]; | ||
return [2 /*return*/]; | ||
}); | ||
rows = pageArray(rows, options); | ||
} | ||
if (rows) | ||
return rows.map(i => { | ||
return this.translateFromJson(i); | ||
}); | ||
}); | ||
}; | ||
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]); | ||
} | ||
} | ||
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; | ||
}; | ||
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]); | ||
} | ||
} | ||
translateToJson(row) { | ||
let result = {}; | ||
for (const col of this.entity.fields) { | ||
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; | ||
}; | ||
ArrayEntityDataProvider.prototype.idMatches = function (id) { | ||
var _this = this; | ||
return function (item) { | ||
var x = new FilterConsumerBridgeToObject(item); | ||
_this.entity.idMetadata.getIdFilter(id).__applyToConsumer(x); | ||
} | ||
idMatches(id) { | ||
return item => { | ||
let x = new FilterConsumerBridgeToObject(item); | ||
this.entity.idMetadata.getIdFilter(id).__applyToConsumer(x); | ||
return x.ok; | ||
}; | ||
}; | ||
ArrayEntityDataProvider.prototype.update = function (id, data) { | ||
var idMatches = this.idMatches(id); | ||
for (var i = 0; i < this.rows.length; i++) { | ||
} | ||
update(id, data) { | ||
let idMatches = this.idMatches(id); | ||
for (let i = 0; i < this.rows.length; i++) { | ||
if (idMatches(this.rows[i])) { | ||
@@ -139,6 +108,6 @@ this.rows[i] = Object.assign({}, this.rows[i], this.translateToJson(data)); | ||
throw new Error("couldn't find id to update: " + id); | ||
}; | ||
ArrayEntityDataProvider.prototype.delete = function (id) { | ||
var idMatches = this.idMatches(id); | ||
for (var i = 0; i < this.rows.length; i++) { | ||
} | ||
delete(id) { | ||
let idMatches = this.idMatches(id); | ||
for (let i = 0; i < this.rows.length; i++) { | ||
if (idMatches(this.rows[i])) { | ||
@@ -150,37 +119,26 @@ this.rows.splice(i, 1); | ||
throw new Error("couldn't find id to delete: " + id); | ||
}; | ||
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))]; | ||
} | ||
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; | ||
} | ||
}); | ||
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; | ||
@@ -192,3 +150,3 @@ function pageArray(rows, options) { | ||
return rows; | ||
var page = 1; | ||
let page = 1; | ||
if (options.page) | ||
@@ -198,16 +156,16 @@ page = options.page; | ||
page = 1; | ||
var x = 0; | ||
return rows.filter(function (i) { | ||
let x = 0; | ||
return rows.filter(i => { | ||
x++; | ||
var max = page * options.limit; | ||
var min = max - options.limit; | ||
let max = page * options.limit; | ||
let min = max - options.limit; | ||
return x > min && x <= max; | ||
}); | ||
} | ||
var FilterConsumerBridgeToObject = /** @class */ (function () { | ||
function FilterConsumerBridgeToObject(row) { | ||
class FilterConsumerBridgeToObject { | ||
constructor(row) { | ||
this.row = row; | ||
this.ok = true; | ||
} | ||
FilterConsumerBridgeToObject.prototype.databaseCustom = function (databaseCustom) { | ||
databaseCustom(databaseCustom) { | ||
if (databaseCustom && databaseCustom.arrayFilter) { | ||
@@ -217,80 +175,58 @@ if (!databaseCustom.arrayFilter(this.row)) | ||
} | ||
}; | ||
FilterConsumerBridgeToObject.prototype.custom = function (customItem) { | ||
} | ||
custom(customItem) { | ||
throw new Error('Custom Filter should be translated before it gets here'); | ||
}; | ||
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; | ||
} | ||
} | ||
or(orElements) { | ||
for (const element of orElements) { | ||
let 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; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isNull = function (col) { | ||
} | ||
isNull(col) { | ||
if (this.row[col.key] != null) | ||
this.ok = false; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isNotNull = function (col) { | ||
} | ||
isNotNull(col) { | ||
if (this.row[col.key] == null) | ||
this.ok = false; | ||
}; | ||
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; | ||
} | ||
} | ||
isIn(col, val) { | ||
for (const v of val) { | ||
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; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isEqualTo = function (col, val) { | ||
} | ||
isEqualTo(col, val) { | ||
if (this.row[col.key] != col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isDifferentFrom = function (col, val) { | ||
} | ||
isDifferentFrom(col, val) { | ||
if (this.row[col.key] == col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isGreaterOrEqualTo = function (col, val) { | ||
} | ||
isGreaterOrEqualTo(col, val) { | ||
if (this.row[col.key] < col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isGreaterThan = function (col, val) { | ||
} | ||
isGreaterThan(col, val) { | ||
if (this.row[col.key] <= col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isLessOrEqualTo = function (col, val) { | ||
} | ||
isLessOrEqualTo(col, val) { | ||
if (this.row[col.key] > col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.isLessThan = function (col, val) { | ||
} | ||
isLessThan(col, val) { | ||
if (this.row[col.key] >= col.valueConverter.toJson(val)) | ||
this.ok = false; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.containsCaseInsensitive = function (col, val) { | ||
var v = this.row[col.key]; | ||
} | ||
containsCaseInsensitive(col, val) { | ||
let v = this.row[col.key]; | ||
if (!v) { | ||
@@ -300,3 +236,3 @@ this.ok = false; | ||
} | ||
var s = '' + v; | ||
let s = '' + v; | ||
if (val) | ||
@@ -308,5 +244,5 @@ val = col.valueConverter.toJson(val); | ||
this.ok = false; | ||
}; | ||
FilterConsumerBridgeToObject.prototype.startsWith = function (col, val) { | ||
var v = this.row[col.key]; | ||
} | ||
startsWith(col, val) { | ||
let v = this.row[col.key]; | ||
if (!v) { | ||
@@ -316,8 +252,7 @@ this.ok = false; | ||
} | ||
var s = '' + v; | ||
let 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; | ||
var tslib_1 = require("tslib"); | ||
var array_entity_data_provider_1 = require("./array-entity-data-provider"); | ||
var InMemoryDataProvider = /** @class */ (function () { | ||
function InMemoryDataProvider() { | ||
const tslib_1 = require("tslib"); | ||
const array_entity_data_provider_1 = require("./array-entity-data-provider"); | ||
class InMemoryDataProvider { | ||
constructor() { | ||
this.rows = {}; | ||
} | ||
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*/]; | ||
} | ||
}); | ||
transaction(action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield action(this); | ||
}); | ||
}; | ||
InMemoryDataProvider.prototype.getEntityDataProvider = function (entity) { | ||
var name = entity.key; | ||
} | ||
getEntityDataProvider(entity) { | ||
let name = entity.key; | ||
if (!this.rows[name]) | ||
this.rows[name] = []; | ||
return new array_entity_data_provider_1.ArrayEntityDataProvider(entity, this.rows[name]); | ||
}; | ||
InMemoryDataProvider.prototype.toString = function () { return "InMemoryDataProvider"; }; | ||
return InMemoryDataProvider; | ||
}()); | ||
} | ||
toString() { return "InMemoryDataProvider"; } | ||
} | ||
exports.InMemoryDataProvider = InMemoryDataProvider; | ||
//# sourceMappingURL=in-memory-database.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.JsonDataProvider = void 0; | ||
var tslib_1 = require("tslib"); | ||
var array_entity_data_provider_1 = require("./array-entity-data-provider"); | ||
var JsonDataProvider = /** @class */ (function () { | ||
function JsonDataProvider(storage) { | ||
const tslib_1 = require("tslib"); | ||
const array_entity_data_provider_1 = require("./array-entity-data-provider"); | ||
class JsonDataProvider { | ||
constructor(storage) { | ||
this.storage = storage; | ||
} | ||
JsonDataProvider.prototype.getEntityDataProvider = function (entity) { | ||
getEntityDataProvider(entity) { | ||
return new JsonEntityDataProvider(entity, this.storage); | ||
}; | ||
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*/]; | ||
} | ||
}); | ||
} | ||
transaction(action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield action(this); | ||
}); | ||
}; | ||
return JsonDataProvider; | ||
}()); | ||
} | ||
} | ||
exports.JsonDataProvider = JsonDataProvider; | ||
var JsonEntityDataProvider = /** @class */ (function () { | ||
function JsonEntityDataProvider(entity, helper) { | ||
class JsonEntityDataProvider { | ||
constructor(entity, helper) { | ||
this.entity = entity; | ||
@@ -34,57 +26,40 @@ this.helper = helper; | ||
} | ||
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)); })]; | ||
} | ||
}); | ||
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.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) { | ||
} | ||
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 => { | ||
save(); | ||
return 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) { | ||
}))); | ||
} | ||
delete(id) { | ||
return this.p = this.p.then(() => this.loadEntityData((dp, save) => dp.delete(id).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; | ||
}); }); })]; | ||
}); | ||
}))); | ||
} | ||
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; | ||
}))); | ||
}); | ||
}; | ||
return JsonEntityDataProvider; | ||
}()); | ||
} | ||
} | ||
//# sourceMappingURL=json-data-provider.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.addFilterToUrlAndReturnTrueIfSuccessful = exports.RestDataProviderHttpProviderUsingFetch = exports.RestDataProvider = void 0; | ||
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) { | ||
const tslib_1 = require("tslib"); | ||
const urlBuilder_1 = require("../../urlBuilder"); | ||
const filter_interfaces_1 = require("../filter/filter-interfaces"); | ||
class RestDataProvider { | ||
constructor(url, http) { | ||
this.url = url; | ||
@@ -13,17 +13,14 @@ this.http = http; | ||
} | ||
RestDataProvider.prototype.getEntityDataProvider = function (entity) { | ||
getEntityDataProvider(entity) { | ||
return new RestEntityDataProvider(this.url + '/' + entity.key, this.http, entity); | ||
}; | ||
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."); | ||
}); | ||
} | ||
transaction(action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
throw new Error("Method not implemented."); | ||
}); | ||
}; | ||
return RestDataProvider; | ||
}()); | ||
} | ||
} | ||
exports.RestDataProvider = RestDataProvider; | ||
var RestEntityDataProvider = /** @class */ (function () { | ||
function RestEntityDataProvider(url, http, entity) { | ||
class RestEntityDataProvider { | ||
constructor(url, http, entity) { | ||
this.url = url; | ||
@@ -33,61 +30,35 @@ this.http = http; | ||
} | ||
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]); | ||
} | ||
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]); | ||
} | ||
return result; | ||
}; | ||
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]); | ||
} | ||
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; | ||
} | ||
} | ||
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; | ||
}; | ||
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*/]; | ||
}); | ||
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.find = function (options) { | ||
var _this = this; | ||
var url = new urlBuilder_1.UrlBuilder(this.url); | ||
var filterObject; | ||
} | ||
find(options) { | ||
let url = new urlBuilder_1.UrlBuilder(this.url); | ||
let filterObject; | ||
if (options) { | ||
@@ -100,14 +71,14 @@ if (options.where) { | ||
if (options.orderBy && options.orderBy.Segments) { | ||
var sort_1 = ''; | ||
var order_1 = ''; | ||
options.orderBy.Segments.forEach(function (c) { | ||
if (sort_1.length > 0) { | ||
sort_1 += ","; | ||
order_1 += ","; | ||
let sort = ''; | ||
let order = ''; | ||
options.orderBy.Segments.forEach(c => { | ||
if (sort.length > 0) { | ||
sort += ","; | ||
order += ","; | ||
} | ||
sort_1 += c.field.key; | ||
order_1 += c.isDescending ? "desc" : "asc"; | ||
sort += c.field.key; | ||
order += c.isDescending ? "desc" : "asc"; | ||
}); | ||
url.add('_sort', sort_1); | ||
url.add('_order', order_1); | ||
url.add('_sort', sort); | ||
url.add('_order', order); | ||
} | ||
@@ -123,36 +94,33 @@ if (options.limit) | ||
url.add("__action", "get"); | ||
return this.http.post(url.url, filterObject).then(function (x) { return x.map(function (y) { return _this.translateFromJson(y); }); }); | ||
return this.http.post(url.url, filterObject).then(x => x.map(y => this.translateFromJson(y))); | ||
} | ||
else | ||
return this.http.get(url.url).then(function (x) { return x.map(function (y) { return _this.translateFromJson(y); }); }); | ||
return this.http.get(url.url).then(x => x.map(y => this.translateFromJson(y))); | ||
; | ||
}; | ||
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) { | ||
} | ||
update(id, data) { | ||
return this.http.put(this.url + '/' + encodeURIComponent(id), this.translateToJson(data)).then(y => this.translateFromJson(y)); | ||
} | ||
delete(id) { | ||
return this.http.delete(this.url + '/' + encodeURIComponent(id)); | ||
}; | ||
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; | ||
}()); | ||
} | ||
insert(data) { | ||
return this.http.post(this.url, this.translateToJson(data)).then(y => this.translateFromJson(y)); | ||
} | ||
} | ||
function JsonContent(add) { | ||
add('Content-type', "application/json"); | ||
} | ||
var RestDataProviderHttpProviderUsingFetch = /** @class */ (function () { | ||
function RestDataProviderHttpProviderUsingFetch(addRequestHeader) { | ||
class RestDataProviderHttpProviderUsingFetch { | ||
constructor(addRequestHeader) { | ||
this.addRequestHeader = addRequestHeader; | ||
if (!addRequestHeader) | ||
this.addRequestHeader = function () { }; | ||
this.addRequestHeader = () => { }; | ||
} | ||
RestDataProviderHttpProviderUsingFetch.prototype.get = function (url) { | ||
return myFetch(url, undefined, this.addRequestHeader).then(function (r) { | ||
get(url) { | ||
return myFetch(url, undefined, this.addRequestHeader).then(r => { | ||
return r; | ||
}); | ||
}; | ||
RestDataProviderHttpProviderUsingFetch.prototype.put = function (url, data) { | ||
} | ||
put(url, data) { | ||
return myFetch(url, { | ||
@@ -162,9 +130,9 @@ method: 'put', | ||
}, this.addRequestHeader, JsonContent); | ||
}; | ||
RestDataProviderHttpProviderUsingFetch.prototype.delete = function (url) { | ||
var h = new Headers(); | ||
this.addRequestHeader(function (name, value) { return h.append(name, value); }); | ||
} | ||
delete(url) { | ||
let h = new Headers(); | ||
this.addRequestHeader((name, value) => h.append(name, value)); | ||
return fetch(url, { method: 'delete', credentials: 'include' }).then(onSuccess, onError); | ||
}; | ||
RestDataProviderHttpProviderUsingFetch.prototype.post = function (url, data) { | ||
} | ||
post(url, data) { | ||
return myFetch(url, { | ||
@@ -174,12 +142,6 @@ 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]; | ||
} | ||
function myFetch(url, init, ...addRequestHeader) { | ||
if (!init) | ||
@@ -190,18 +152,11 @@ init = {}; | ||
var h = init.headers; | ||
addRequestHeader.forEach(function (x) { return x(function (n, v) { return h.append(n, v); }); }); | ||
addRequestHeader.forEach(x => x((n, v) => h.append(n, v))); | ||
init.credentials = 'include'; | ||
return fetch(url, init).then(function (response) { | ||
return fetch(url, init).then(response => { | ||
return onSuccess(response); | ||
}).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; | ||
} | ||
}); | ||
}); }); | ||
}).catch((error) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let r = yield error; | ||
console.log(r); | ||
throw r; | ||
})); | ||
} | ||
@@ -214,7 +169,7 @@ function onSuccess(response) { | ||
else { | ||
throw response.json().then(function (x) { | ||
throw response.json().then(x => { | ||
if (!x.message) | ||
x.message = response.statusText; | ||
return x; | ||
}).catch(function () { | ||
}).catch(() => { | ||
throw { | ||
@@ -232,5 +187,5 @@ message: response.statusText, | ||
function addFilterToUrlAndReturnTrueIfSuccessful(filter, url) { | ||
for (var key in filter) { | ||
for (const key in filter) { | ||
if (Object.prototype.hasOwnProperty.call(filter, key)) { | ||
var element = filter[key]; | ||
const element = filter[key]; | ||
if (Array.isArray(element)) { | ||
@@ -244,5 +199,5 @@ if (element.length > 0 && typeof element[0] === 'object') | ||
} | ||
var _loop_1 = function (key) { | ||
for (const key in filter) { | ||
if (Object.prototype.hasOwnProperty.call(filter, key)) { | ||
var element = filter[key]; | ||
const element = filter[key]; | ||
if (Array.isArray(element)) { | ||
@@ -252,3 +207,3 @@ if (key.endsWith("_in")) | ||
else | ||
element.forEach(function (e) { return url.add(key, e); }); | ||
element.forEach(e => url.add(key, e)); | ||
} | ||
@@ -260,5 +215,2 @@ else if (key == filter_interfaces_1.customUrlToken) | ||
} | ||
}; | ||
for (var key in filter) { | ||
_loop_1(key); | ||
} | ||
@@ -265,0 +217,0 @@ return true; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isDbReadonly = exports.SqlDatabase = void 0; | ||
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"); | ||
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"); | ||
// @dynamic | ||
var SqlDatabase = /** @class */ (function () { | ||
function SqlDatabase(sql) { | ||
class SqlDatabase { | ||
constructor(sql) { | ||
this.sql = sql; | ||
this.createdEntities = []; | ||
} | ||
SqlDatabase.prototype.createCommand = function () { | ||
createCommand() { | ||
return new LogSQLCommand(this.sql.createCommand(), SqlDatabase.LogToConsole); | ||
}; | ||
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()]; | ||
} | ||
}); | ||
} | ||
execute(sql) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield this.createCommand().execute(sql); | ||
}); | ||
}; | ||
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({ | ||
} | ||
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({ | ||
buildSql: build | ||
}); }); | ||
}; | ||
SqlDatabase.LogToConsole = false; | ||
SqlDatabase.durationThreshold = 0; | ||
return SqlDatabase; | ||
}()); | ||
})); | ||
} | ||
} | ||
exports.SqlDatabase = SqlDatabase; | ||
var LogSQLCommand = /** @class */ (function () { | ||
function LogSQLCommand(origin, allQueries) { | ||
SqlDatabase.LogToConsole = false; | ||
SqlDatabase.durationThreshold = 0; | ||
class LogSQLCommand { | ||
constructor(origin, allQueries) { | ||
this.origin = origin; | ||
@@ -110,42 +73,33 @@ this.allQueries = allQueries; | ||
} | ||
LogSQLCommand.prototype.addParameterAndReturnSqlToken = function (val) { | ||
var r = this.origin.addParameterAndReturnSqlToken(val); | ||
addParameterAndReturnSqlToken(val) { | ||
let r = this.origin.addParameterAndReturnSqlToken(val); | ||
this.args[r] = val; | ||
return r; | ||
}; | ||
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*/]; | ||
} | ||
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); | ||
} | ||
} | ||
}); | ||
return r; | ||
} | ||
catch (err) { | ||
console.error('Error:', err); | ||
console.error('Query:', sql); | ||
console.error("Arguments", this.args); | ||
throw err; | ||
} | ||
}); | ||
}; | ||
return LogSQLCommand; | ||
}()); | ||
var ActualSQLServerDataProvider = /** @class */ (function () { | ||
function ActualSQLServerDataProvider(entity, sql, iAmUsed, strategy) { | ||
} | ||
} | ||
class ActualSQLServerDataProvider { | ||
constructor(entity, sql, iAmUsed, strategy) { | ||
this.entity = entity; | ||
@@ -156,125 +110,54 @@ this.sql = sql; | ||
} | ||
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; | ||
})]; | ||
} | ||
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.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); | ||
} | ||
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 }))); | ||
} | ||
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; | ||
else | ||
segs.push(s); | ||
} | ||
for (const c of segs) { | ||
if (first) { | ||
@@ -286,91 +169,52 @@ select += ' Order By '; | ||
select += ', '; | ||
_j = select; | ||
return [4 /*yield*/, c.field.getDbName()]; | ||
case 16: | ||
select = _j + _o.sent(); | ||
select += yield c.field.getDbName(); | ||
if (c.isDescending) | ||
select += ' desc'; | ||
_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: | ||
} | ||
} | ||
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]; | ||
try { | ||
if (segs_1_1 && !segs_1_1.done && (_m = segs_1.return)) _m.call(segs_1); | ||
result[col.key] = col.valueConverter.fromDb(y[r.getColumnKeyInResultForIndexInSelect(index)]); | ||
} | ||
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); | ||
catch (err) { | ||
throw new Error("Failed to load from db:" + col.key + "\r\n" + err); | ||
} | ||
_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; | ||
}); | ||
})]; | ||
} | ||
} | ||
return result; | ||
}); | ||
}); | ||
}); | ||
}; | ||
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]; | ||
} | ||
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) { | ||
if (!added) | ||
@@ -380,91 +224,41 @@ added = true; | ||
statement += ', '; | ||
_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 x.getDbName()) + ' = ' + r.addParameterAndReturnSqlToken(v); | ||
} | ||
} | ||
} | ||
statement += yield f.resolveWhere(); | ||
return r.execute(statement).then(() => { | ||
return this.find({ where: resultFilter }).then(y => y[0]); | ||
}); | ||
}); | ||
}; | ||
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 () { })]; | ||
} | ||
}); | ||
} | ||
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.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]; | ||
} | ||
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) { | ||
if (!added) | ||
@@ -476,62 +270,24 @@ added = true; | ||
} | ||
_c = cols; | ||
return [4 /*yield*/, x.getDbName()]; | ||
case 6: | ||
cols = _c + _f.sent(); | ||
cols += yield x.getDbName(); | ||
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; | ||
return ActualSQLServerDataProvider; | ||
}()); | ||
} | ||
} | ||
ActualSQLServerDataProvider.LogToConsole = false; | ||
function isDbReadonly(x) { | ||
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)]; | ||
} | ||
}); | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return (x.dbReadOnly || x.isServerExpression || (yield x.getDbName()) != x.options.dbName); | ||
}); | ||
@@ -538,0 +294,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.WebSqlDataProvider = void 0; | ||
var tslib_1 = require("tslib"); | ||
var sql_database_1 = require("./sql-database"); | ||
const tslib_1 = require("tslib"); | ||
const sql_database_1 = require("./sql-database"); | ||
//SqlDatabase.LogToConsole = true; | ||
var WebSqlDataProvider = /** @class */ (function () { | ||
function WebSqlDataProvider(databaseName) { | ||
class WebSqlDataProvider { | ||
constructor(databaseName) { | ||
this.databaseName = databaseName; | ||
@@ -13,125 +13,56 @@ //@ts-ignore | ||
} | ||
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]; | ||
} | ||
}); | ||
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.getLimitSqlSyntax = function (limit, offset) { | ||
} | ||
getLimitSqlSyntax(limit, offset) { | ||
return ' limit ' + limit + ' offset ' + offset; | ||
}; | ||
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*/]; | ||
} | ||
}); | ||
} | ||
entityIsUsedForTheFirstTime(entity) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.createTable(entity); | ||
}); | ||
}; | ||
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*/]; | ||
} | ||
}); | ||
} | ||
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.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*/]; | ||
} | ||
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"; | ||
} | ||
} | ||
}); | ||
} | ||
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); | ||
}); | ||
}; | ||
WebSqlDataProvider.prototype.createCommand = function () { | ||
} | ||
createCommand() { | ||
return new WebSqlBridgeToSQLCommand(this.db); | ||
}; | ||
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."); | ||
}); | ||
} | ||
transaction(action) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
throw new Error("Method not implemented."); | ||
}); | ||
}; | ||
WebSqlDataProvider.prototype.addColumnSqlSyntax = function (x, dbName) { | ||
var result = dbName; | ||
} | ||
addColumnSqlSyntax(x, dbName) { | ||
let result = dbName; | ||
if (x.valueType == Date) | ||
@@ -150,52 +81,47 @@ result += " integer"; | ||
return result; | ||
}; | ||
WebSqlDataProvider.prototype.toString = function () { return "WebSqlDataProvider"; }; | ||
return WebSqlDataProvider; | ||
}()); | ||
} | ||
toString() { return "WebSqlDataProvider"; } | ||
} | ||
exports.WebSqlDataProvider = WebSqlDataProvider; | ||
var WebSqlBridgeToSQLCommand = /** @class */ (function () { | ||
class WebSqlBridgeToSQLCommand { | ||
//@ts-ignore | ||
function WebSqlBridgeToSQLCommand(source) { | ||
constructor(source) { | ||
this.source = source; | ||
this.values = []; | ||
} | ||
WebSqlBridgeToSQLCommand.prototype.addParameterAndReturnSqlToken = function (val) { | ||
addParameterAndReturnSqlToken(val) { | ||
this.values.push(val); | ||
return '~' + this.values.length + '~'; | ||
}; | ||
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; | ||
} | ||
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]); | ||
}); | ||
t.executeSql(s, v, (t1, r) => resolve(new WebSqlBridgeToSQLQueryResult(r)), (t2, err) => { | ||
reject(err.message); | ||
return undefined; | ||
}); | ||
}); | ||
}; | ||
return WebSqlBridgeToSQLCommand; | ||
}()); | ||
var WebSqlBridgeToSQLQueryResult = /** @class */ (function () { | ||
})); | ||
} | ||
} | ||
class WebSqlBridgeToSQLQueryResult { | ||
//@ts-ignore | ||
function WebSqlBridgeToSQLQueryResult(r) { | ||
constructor(r) { | ||
this.r = r; | ||
this.rows = []; | ||
for (var i = 0; i < r.rows.length; i++) { | ||
for (let i = 0; i < r.rows.length; i++) { | ||
this.rows.push(r.rows.item(i)); | ||
} | ||
} | ||
WebSqlBridgeToSQLQueryResult.prototype.getColumnKeyInResultForIndexInSelect = function (index) { | ||
getColumnKeyInResultForIndexInSelect(index) { | ||
if (this.rows.length == 0) | ||
return undefined; | ||
var i = 0; | ||
for (var m in this.rows[0]) { | ||
let i = 0; | ||
for (let m in this.rows[0]) { | ||
if (i++ == index) | ||
@@ -205,5 +131,4 @@ 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; | ||
var tslib_1 = require("tslib"); | ||
var FilterConsumerBridgeToSqlRequest = /** @class */ (function () { | ||
function FilterConsumerBridgeToSqlRequest(r) { | ||
const tslib_1 = require("tslib"); | ||
class FilterConsumerBridgeToSqlRequest { | ||
constructor(r) { | ||
this.r = r; | ||
@@ -12,198 +12,86 @@ this.where = ""; | ||
} | ||
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]; | ||
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; | ||
} | ||
}); | ||
} | ||
return this.where; | ||
}); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.custom = function (customItem) { | ||
} | ||
custom(customItem) { | ||
throw new Error("Custom filter should be translated before it gets here"); | ||
}; | ||
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*/]; | ||
} | ||
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.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'])]; | ||
} | ||
}); }); })()); | ||
}; | ||
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.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) { | ||
this.add(col, val, "="); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isDifferentFrom = function (col, val) { | ||
} | ||
isDifferentFrom(col, val) { | ||
this.add(col, val, "<>"); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isGreaterOrEqualTo = function (col, val) { | ||
} | ||
isGreaterOrEqualTo(col, val) { | ||
this.add(col, val, ">="); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isGreaterThan = function (col, val) { | ||
} | ||
isGreaterThan(col, val) { | ||
this.add(col, val, ">"); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isLessOrEqualTo = function (col, val) { | ||
} | ||
isLessOrEqualTo(col, val) { | ||
this.add(col, val, "<="); | ||
}; | ||
FilterConsumerBridgeToSqlRequest.prototype.isLessThan = function (col, val) { | ||
} | ||
isLessThan(col, val) { | ||
this.add(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) { | ||
} | ||
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) { | ||
this.add(col, val + '%', 'like'); | ||
}; | ||
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) { | ||
} | ||
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) { | ||
if (this.where.length == 0) { | ||
@@ -216,40 +104,28 @@ if (this._addWhere) | ||
this.where += x; | ||
}; | ||
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*/]; | ||
} | ||
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 + ")"); | ||
} | ||
}); | ||
}); })()); | ||
}; | ||
return FilterConsumerBridgeToSqlRequest; | ||
}()); | ||
} | ||
}))()); | ||
} | ||
} | ||
exports.FilterConsumerBridgeToSqlRequest = FilterConsumerBridgeToSqlRequest; | ||
var CustomSqlFilterBuilder = /** @class */ (function () { | ||
function CustomSqlFilterBuilder(r) { | ||
class CustomSqlFilterBuilder { | ||
constructor(r) { | ||
this.r = r; | ||
this.sql = ''; | ||
} | ||
CustomSqlFilterBuilder.prototype.addParameterAndReturnSqlToken = function (val, field) { | ||
addParameterAndReturnSqlToken(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; | ||
var tslib_1 = require("tslib"); | ||
var remult3_1 = require("../remult3"); | ||
var Filter = /** @class */ (function () { | ||
function Filter(apply) { | ||
const tslib_1 = require("tslib"); | ||
const remult3_1 = require("../remult3"); | ||
class Filter { | ||
constructor(apply) { | ||
this.apply = apply; | ||
if (!this.apply) { | ||
this.apply = function () { }; | ||
this.apply = () => { }; | ||
} | ||
} | ||
Filter.prototype.__applyToConsumer = function (add) { | ||
__applyToConsumer(add) { | ||
this.apply(add); | ||
}; | ||
Filter.prototype.and = function (filter) { | ||
} | ||
and(filter) { | ||
return new AndFilter(this, filter); | ||
}; | ||
Filter.prototype.or = function (filter) { | ||
} | ||
or(filter) { | ||
return new OrFilter(this, filter); | ||
}; | ||
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); | ||
} | ||
} | ||
static createFilterFactories(entityDefs) { | ||
let r = {}; | ||
for (const c of entityDefs.fields) { | ||
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); | ||
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)))); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
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*/]; | ||
} | ||
}); | ||
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.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 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.packToRawWhere = function (w) { | ||
var r = new FilterSerializer(); | ||
} | ||
static packToRawWhere(w) { | ||
let r = new FilterSerializer(); | ||
if (w) | ||
w.__applyToConsumer(r); | ||
return r.result; | ||
}; | ||
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]; | ||
} | ||
}); | ||
} | ||
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; | ||
}); | ||
}; | ||
return Filter; | ||
}()); | ||
} | ||
} | ||
exports.Filter = Filter; | ||
var filterHelper = /** @class */ (function () { | ||
function filterHelper(metadata) { | ||
class filterHelper { | ||
constructor(metadata) { | ||
this.metadata = metadata; | ||
} | ||
filterHelper.prototype.processVal = function (val) { | ||
var ei = remult3_1.getEntitySettings(this.metadata.valueType, false); | ||
processVal(val) { | ||
let ei = remult3_1.getEntitySettings(this.metadata.valueType, false); | ||
if (ei) { | ||
@@ -153,110 +96,65 @@ if (!val) | ||
return val; | ||
}; | ||
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); | ||
} | ||
} | ||
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); | ||
} | ||
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; } | ||
} | ||
}); | ||
}; | ||
filterHelper.prototype.isDifferentFrom = function (val) { | ||
var _this = this; | ||
} | ||
isDifferentFrom(val) { | ||
val = this.processVal(val); | ||
if (val === null && this.metadata.allowNull) | ||
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; | ||
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) { | ||
val = this.processVal(val); | ||
if (val === null && this.metadata.allowNull) | ||
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; | ||
}()); | ||
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)); | ||
} | ||
} | ||
exports.filterHelper = filterHelper; | ||
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); | ||
} | ||
class AndFilter extends Filter { | ||
constructor(...filters) { | ||
super(add => { | ||
for (const iterator of this.filters) { | ||
if (iterator) | ||
iterator.__applyToConsumer(add); | ||
} | ||
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; | ||
}); | ||
this.filters = filters; | ||
} | ||
AndFilter.prototype.add = function (filter) { | ||
add(filter) { | ||
this.filters.push(filter); | ||
}; | ||
return AndFilter; | ||
}(Filter)); | ||
} | ||
} | ||
exports.AndFilter = AndFilter; | ||
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; }); | ||
class OrFilter extends Filter { | ||
constructor(...filters) { | ||
super(add => { | ||
let f = this.filters.filter(x => x !== undefined); | ||
if (f.length > 1) { | ||
@@ -267,25 +165,23 @@ add.or(f); | ||
f[0].__applyToConsumer(add); | ||
}) || this; | ||
_this.filters = filters; | ||
return _this; | ||
}); | ||
this.filters = filters; | ||
} | ||
return OrFilter; | ||
}(Filter)); | ||
} | ||
exports.OrFilter = OrFilter; | ||
exports.customUrlToken = "_$custom"; | ||
var FilterSerializer = /** @class */ (function () { | ||
function FilterSerializer() { | ||
class FilterSerializer { | ||
constructor() { | ||
this.result = {}; | ||
this.hasUndefined = false; | ||
} | ||
FilterSerializer.prototype.databaseCustom = function (databaseCustom) { | ||
databaseCustom(databaseCustom) { | ||
throw new Error("database custom is not allowed with rest calls."); | ||
}; | ||
FilterSerializer.prototype.custom = function (customItem) { | ||
} | ||
custom(customItem) { | ||
this.add(exports.customUrlToken, customItem); | ||
}; | ||
FilterSerializer.prototype.add = function (key, val) { | ||
} | ||
add(key, val) { | ||
if (val === undefined) | ||
this.hasUndefined = true; | ||
var r = this.result; | ||
let r = this.result; | ||
if (!r[key]) { | ||
@@ -295,3 +191,3 @@ r[key] = val; | ||
} | ||
var v = r[key]; | ||
let v = r[key]; | ||
if (v instanceof Array) { | ||
@@ -303,62 +199,59 @@ v.push(val); | ||
r[key] = v; | ||
}; | ||
FilterSerializer.prototype.or = function (orElements) { | ||
this.add("OR", orElements.map(function (x) { | ||
var f = new FilterSerializer(); | ||
} | ||
or(orElements) { | ||
this.add("OR", orElements.map(x => { | ||
let f = new FilterSerializer(); | ||
x.__applyToConsumer(f); | ||
return f.result; | ||
})); | ||
}; | ||
FilterSerializer.prototype.isNull = function (col) { | ||
} | ||
isNull(col) { | ||
this.add(col.key + "_null", true); | ||
}; | ||
FilterSerializer.prototype.isNotNull = function (col) { | ||
} | ||
isNotNull(col) { | ||
this.add(col.key + "_null", false); | ||
}; | ||
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) { | ||
} | ||
isIn(col, val) { | ||
this.add(col.key + "_in", val.map(x => col.valueConverter.toJson(x))); | ||
} | ||
isEqualTo(col, val) { | ||
this.add(col.key, col.valueConverter.toJson(val)); | ||
}; | ||
FilterSerializer.prototype.isDifferentFrom = function (col, val) { | ||
} | ||
isDifferentFrom(col, val) { | ||
this.add(col.key + '_ne', col.valueConverter.toJson(val)); | ||
}; | ||
FilterSerializer.prototype.isGreaterOrEqualTo = function (col, val) { | ||
} | ||
isGreaterOrEqualTo(col, val) { | ||
this.add(col.key + '_gte', col.valueConverter.toJson(val)); | ||
}; | ||
FilterSerializer.prototype.isGreaterThan = function (col, val) { | ||
} | ||
isGreaterThan(col, val) { | ||
this.add(col.key + '_gt', col.valueConverter.toJson(val)); | ||
}; | ||
FilterSerializer.prototype.isLessOrEqualTo = function (col, val) { | ||
} | ||
isLessOrEqualTo(col, val) { | ||
this.add(col.key + '_lte', col.valueConverter.toJson(val)); | ||
}; | ||
FilterSerializer.prototype.isLessThan = function (col, val) { | ||
} | ||
isLessThan(col, val) { | ||
this.add(col.key + '_lt', col.valueConverter.toJson(val)); | ||
}; | ||
FilterSerializer.prototype.containsCaseInsensitive = function (col, val) { | ||
} | ||
containsCaseInsensitive(col, val) { | ||
this.add(col.key + "_contains", val); | ||
}; | ||
FilterSerializer.prototype.startsWith = function (col, val) { | ||
} | ||
startsWith(col, val) { | ||
this.add(col.key + "_st", col.valueConverter.toJson(val)); | ||
}; | ||
return FilterSerializer; | ||
}()); | ||
} | ||
} | ||
exports.FilterSerializer = FilterSerializer; | ||
function unpackWhere(columns, packed) { | ||
return extractWhere(columns, { get: function (key) { return packed[key]; } }); | ||
return extractWhere(columns, { get: (key) => packed[key] }); | ||
} | ||
exports.unpackWhere = unpackWhere; | ||
function extractWhere(columns, filterInfo) { | ||
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); | ||
let where = []; | ||
columns.forEach(col => { | ||
function addFilter(operation, theFilter, jsonArray = false, asString = false) { | ||
let val = filterInfo.get(col.key + operation); | ||
if (val !== undefined) { | ||
var addFilter_1 = function (val) { | ||
var theVal = val; | ||
let addFilter = (val) => { | ||
let theVal = val; | ||
if (jsonArray) { | ||
var arr = void 0; | ||
let arr; | ||
if (typeof val === 'string') | ||
@@ -368,3 +261,3 @@ arr = JSON.parse(val); | ||
arr = val; | ||
theVal = arr.map(function (x) { return asString ? x : col.valueConverter.fromJson(x); }); | ||
theVal = arr.map(x => asString ? x : col.valueConverter.fromJson(x)); | ||
} | ||
@@ -374,3 +267,3 @@ else { | ||
} | ||
var f = theFilter(theVal); | ||
let f = theFilter(theVal); | ||
if (f) { | ||
@@ -381,21 +274,19 @@ where.push(f); | ||
if (!jsonArray && val instanceof Array) { | ||
val.forEach(function (v) { | ||
addFilter_1(v); | ||
val.forEach(v => { | ||
addFilter(v); | ||
}); | ||
} | ||
else | ||
addFilter_1(val); | ||
addFilter(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) { | ||
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 => { | ||
val = val.toString().trim().toLowerCase(); | ||
@@ -411,32 +302,29 @@ switch (val) { | ||
}); | ||
addFilter('_contains', function (val) { | ||
addFilter('_contains', val => { | ||
return c.contains(val); | ||
}, false, true); | ||
addFilter('_st', function (val) { | ||
addFilter('_st', val => { | ||
return c.startsWith(val); | ||
}); | ||
}); | ||
var val = filterInfo.get('OR'); | ||
let val = filterInfo.get('OR'); | ||
if (val) | ||
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); | ||
where.push(new OrFilter(...val.map(x => unpackWhere(columns, x)))); | ||
let custom = filterInfo.get(exports.customUrlToken); | ||
if (custom !== undefined) | ||
where.push(new Filter(function (x) { return x.custom(custom); })); | ||
return new (AndFilter.bind.apply(AndFilter, tslib_1.__spread([void 0], where)))(); | ||
where.push(new Filter(x => x.custom(custom))); | ||
return new AndFilter(...where); | ||
} | ||
exports.extractWhere = extractWhere; | ||
var CustomFilterBuilder = /** @class */ (function () { | ||
function CustomFilterBuilder(translateFilter) { | ||
class CustomFilterBuilder { | ||
constructor(translateFilter) { | ||
this.translateFilter = translateFilter; | ||
} | ||
CustomFilterBuilder.prototype.build = function (custom) { | ||
return new Filter(function (x) { return x.custom(custom); }); | ||
}; | ||
return CustomFilterBuilder; | ||
}()); | ||
build(custom) { | ||
return new Filter(x => x.custom(custom)); | ||
} | ||
} | ||
exports.CustomFilterBuilder = CustomFilterBuilder; | ||
var customTranslator = /** @class */ (function () { | ||
function customTranslator(translateCustom) { | ||
class customTranslator { | ||
constructor(translateCustom) { | ||
this.translateCustom = translateCustom; | ||
@@ -446,98 +334,70 @@ this.commands = []; | ||
} | ||
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) { | ||
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 => { | ||
newOrElements = x; | ||
})); | ||
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*/]; | ||
} | ||
}); | ||
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); | ||
} | ||
}); | ||
}; | ||
return customTranslator; | ||
}()); | ||
} | ||
} | ||
//# sourceMappingURL=filter-interfaces.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.IdEntity = 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)); | ||
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); | ||
exports.IdEntity = IdEntity; | ||
//# sourceMappingURL=id-entity.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
const 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; | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
require("reflect-metadata"); | ||
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) { | ||
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) { | ||
this.actionUrl = actionUrl; | ||
this.queue = queue; | ||
} | ||
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*/]; | ||
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; | ||
} | ||
}); | ||
finally { | ||
progress.close(); | ||
} | ||
} | ||
else | ||
return r; | ||
}); | ||
}; | ||
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*/]; | ||
} | ||
}); | ||
}); }); | ||
}; | ||
Action.apiUrlForJobStatus = 'jobStatusInQueue'; | ||
return Action; | ||
}()); | ||
} | ||
__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); | ||
} | ||
})); | ||
} | ||
} | ||
exports.Action = Action; | ||
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; | ||
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; | ||
} | ||
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]; | ||
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); | ||
} | ||
}); | ||
catch (err) { | ||
throw err; | ||
} | ||
})); | ||
return result; | ||
}); | ||
}; | ||
return myServerAction; | ||
}(Action)); | ||
} | ||
} | ||
exports.myServerAction = myServerAction; | ||
@@ -154,16 +94,16 @@ var isNode = new Function("try {return this===global;}catch(e){return false;}"); | ||
runningOnServer: isNode(), | ||
runActionWithoutBlockingUI: function (what) { return what(); }, | ||
startBusyWithProgress: function () { return ({ | ||
progress: function (percent) { }, | ||
close: function () { } | ||
}); } | ||
runActionWithoutBlockingUI: (what) => { return what(); }, | ||
startBusyWithProgress: () => ({ | ||
progress: (percent) => { }, | ||
close: () => { } | ||
}) | ||
}; | ||
exports.serverActionField = Symbol('serverActionField'); | ||
var methodHelpers = new Map(); | ||
var classOptions = new Map(); | ||
const methodHelpers = new Map(); | ||
const classOptions = new Map(); | ||
function Controller(key) { | ||
return function (target) { | ||
var r = target; | ||
classOptions.set(r, { key: key }); | ||
context_1.setControllerSettings(target, { key: key }); | ||
let r = target; | ||
classOptions.set(r, { key }); | ||
context_1.setControllerSettings(target, { key }); | ||
return target; | ||
@@ -174,3 +114,3 @@ }; | ||
function BackendMethod(options) { | ||
return function (target, key, descriptor) { | ||
return (target, key, descriptor) => { | ||
if (target.prototype !== undefined) { | ||
@@ -180,39 +120,23 @@ var originalMethod = descriptor.value; | ||
// if types are undefined - you've forgot to set: "emitDecoratorMetadata":true | ||
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*/]; | ||
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; })); | ||
} | ||
}); | ||
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_1; | ||
descriptor.value[exports.serverActionField] = serverAction; | ||
return descriptor; | ||
} | ||
var types = Reflect.getMetadata("design:paramtypes", target, key); | ||
var x = context_1.classHelpers.get(target.constructor); | ||
let x = context_1.classHelpers.get(target.constructor); | ||
if (!x) { | ||
@@ -222,254 +146,153 @@ x = new context_1.ClassHelper(); | ||
} | ||
var mh = new context_1.MethodHelper(); | ||
let mh = new context_1.MethodHelper(); | ||
methodHelpers.set(descriptor, mh); | ||
x.methods.push(mh); | ||
var originalMethod = descriptor.value; | ||
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); | ||
let serverAction = { | ||
__register(reg) { | ||
let c = new context_1.ServerContext(); | ||
for (const constructor of mh.classes.keys()) { | ||
let controllerOptions = mh.classes.get(constructor); | ||
if (!controllerOptions.key) { | ||
controllerOptions.key = c.for(constructor).metadata.key + "_methods"; | ||
} | ||
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); | ||
} | ||
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); | ||
} | ||
})); | ||
} | ||
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 () { | ||
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; | ||
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'); | ||
}); | ||
} | ||
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'); | ||
}); | ||
}(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'); | ||
}); | ||
}; | ||
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; | ||
} | ||
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'); | ||
}); | ||
}); | ||
}; | ||
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(); | ||
}(mh.classes.get(this.constructor).key + "/" + key, options ? options.queue : false).run({ | ||
args, | ||
fields: yield defs.toApiJson() | ||
})); | ||
defs._updateEntityBasedOnApi(r.fields); | ||
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*/]; | ||
return r.result; | ||
} | ||
catch (e) { | ||
throw defs.catchSaveErrors(e); | ||
} | ||
} | ||
}); | ||
} | ||
else | ||
return (yield originalMethod.apply(this, args)); | ||
}); | ||
@@ -483,3 +306,3 @@ }; | ||
exports.BackendMethod = BackendMethod; | ||
var customUndefined = { | ||
const customUndefined = { | ||
_isUndefined: true | ||
@@ -490,40 +313,28 @@ }; | ||
} | ||
var ProgressListener = /** @class */ (function () { | ||
function ProgressListener(res) { | ||
class ProgressListener { | ||
constructor(res) { | ||
this.res = res; | ||
} | ||
ProgressListener.prototype.progress = function (progress) { | ||
progress(progress) { | ||
this.res.progress(progress); | ||
}; | ||
return ProgressListener; | ||
}()); | ||
} | ||
} | ||
exports.ProgressListener = ProgressListener; | ||
function prepareArgsToSend(types, args) { | ||
var e_3, _a; | ||
if (types) { | ||
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; | ||
} | ||
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; | ||
} | ||
} | ||
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) { | ||
var x = { valueType: paramType }; | ||
let x = { valueType: paramType }; | ||
x = remult3_1.decorateColumnSettings(x); | ||
if (x.valueConverter) | ||
args[index] = x.valueConverter.toJson(args[index]); | ||
var eo = remult3_1.getEntitySettings(paramType, false); | ||
let eo = remult3_1.getEntitySettings(paramType, false); | ||
if (eo != null) { | ||
var rh = remult3_1.getEntityRef(args[index]); | ||
let rh = remult3_1.getEntityRef(args[index]); | ||
args[index] = rh.getId(); | ||
@@ -534,55 +345,39 @@ } | ||
} | ||
return args.map(function (x) { return x !== undefined ? x : customUndefined; }); | ||
return args.map(x => x !== undefined ? x : customUndefined); | ||
} | ||
exports.prepareArgsToSend = prepareArgsToSend; | ||
function prepareReceivedArgs(types, args, context, ds, res) { | ||
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]; | ||
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) { | ||
args[i] = context; | ||
return [3 /*break*/, 6]; | ||
case 2: | ||
if (!(types[i] == sql_database_1.SqlDatabase && ds)) return [3 /*break*/, 3]; | ||
} | ||
else if (types[i] == sql_database_1.SqlDatabase && ds) { | ||
args[i] = ds; | ||
return [3 /*break*/, 6]; | ||
case 3: | ||
if (!(types[i] == ProgressListener)) return [3 /*break*/, 4]; | ||
} | ||
else if (types[i] == ProgressListener) { | ||
args[i] = new ProgressListener(res); | ||
return [3 /*break*/, 6]; | ||
case 4: | ||
x = { valueType: types[i] }; | ||
} | ||
else { | ||
let x = { valueType: types[i] }; | ||
x = remult3_1.decorateColumnSettings(x); | ||
if (x.valueConverter) | ||
args[i] = x.valueConverter.fromJson(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]; | ||
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]); | ||
} | ||
} | ||
} | ||
}); | ||
return args; | ||
}); | ||
@@ -589,0 +384,0 @@ } |
108
src/sort.js
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Sort = void 0; | ||
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]; | ||
} | ||
const column_1 = require("./column"); | ||
class Sort { | ||
constructor(...segments) { | ||
this.Segments = segments; | ||
} | ||
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 }); | ||
} | ||
reverse() { | ||
let r = new Sort(); | ||
for (const s of this.Segments) { | ||
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; | ||
}; | ||
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); | ||
} | ||
} | ||
static createSortOf(entityDefs) { | ||
let r = {}; | ||
for (const c of entityDefs.fields) { | ||
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; | ||
}; | ||
Sort.translateOrderByToSort = function (entityDefs, orderBy) { | ||
} | ||
static translateOrderByToSort(entityDefs, orderBy) { | ||
if (!orderBy) | ||
return undefined; | ||
var entity = Sort.createSortOf(entityDefs); | ||
var resultOrder = orderBy(entity); // | ||
var sort; | ||
let entity = Sort.createSortOf(entityDefs); | ||
let resultOrder = orderBy(entity); // | ||
let sort; | ||
if (Array.isArray(resultOrder)) | ||
sort = new (Sort.bind.apply(Sort, tslib_1.__spread([void 0], resultOrder)))(); | ||
sort = new Sort(...resultOrder); | ||
else { | ||
@@ -64,49 +37,32 @@ if (!resultOrder) | ||
return sort; | ||
}; | ||
Sort.createUniqueSort = function (entityMetadata, orderBy) { | ||
var e_3, _a; | ||
} | ||
static createUniqueSort(entityMetadata, orderBy) { | ||
if (!orderBy) | ||
orderBy = entityMetadata.options.defaultOrderBy; | ||
if (!orderBy) | ||
orderBy = function (x) { return ({ field: entityMetadata.idMetadata.field }); }; | ||
var sort = Sort.translateOrderByToSort(entityMetadata, orderBy); | ||
orderBy = x => ({ field: entityMetadata.idMetadata.field }); | ||
let sort = Sort.translateOrderByToSort(entityMetadata, orderBy); | ||
if (entityMetadata.idMetadata.field instanceof column_1.CompoundIdField) { | ||
var _loop_1 = function (field) { | ||
if (!sort.Segments.find(function (x) { return x.field == field; })) { | ||
for (const field of entityMetadata.idMetadata.field.fields) { | ||
if (!sort.Segments.find(x => 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(function (x) { return x.field == entityMetadata.idMetadata.field; })) { | ||
else if (!sort.Segments.find(x => x.field == entityMetadata.idMetadata.field)) { | ||
sort.Segments.push({ field: entityMetadata.idMetadata.field }); | ||
} | ||
return sort; | ||
}; | ||
return Sort; | ||
}()); | ||
} | ||
} | ||
exports.Sort = Sort; | ||
var sortHelper = /** @class */ (function () { | ||
function sortHelper(field, isDescending) { | ||
if (isDescending === void 0) { isDescending = false; } | ||
class sortHelper { | ||
constructor(field, isDescending = false) { | ||
this.field = field; | ||
this.isDescending = isDescending; | ||
} | ||
sortHelper.prototype.descending = function () { | ||
descending() { | ||
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; | ||
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; | ||
}()); | ||
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); | ||
exports.Products = Products; | ||
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; | ||
let r; | ||
let Categories = class Categories extends remult3_1.EntityBase { | ||
constructor() { | ||
super(...arguments); | ||
this.id = 0; | ||
} | ||
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)); | ||
}; | ||
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); | ||
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; | ||
var tslib_1 = require("tslib"); | ||
var remult3_1 = require("../../remult3"); | ||
var Status = /** @class */ (function () { | ||
function Status(id, name) { | ||
const tslib_1 = require("tslib"); | ||
const remult3_1 = require("../../remult3"); | ||
let Status = Status_1 = class Status { | ||
constructor(id, name) { | ||
this.id = id; | ||
this.name = name; | ||
} | ||
Status_1 = Status; | ||
Status.prototype.toString = function () { | ||
toString() { | ||
return this.name; | ||
}; | ||
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; | ||
}()); | ||
} | ||
}; | ||
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); | ||
exports.Status = Status; | ||
var TestStatus = /** @class */ (function () { | ||
function TestStatus(id, caption) { | ||
class TestStatus { | ||
constructor(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; | ||
var tslib_1 = require("tslib"); | ||
var Validators = /** @class */ (function () { | ||
function Validators() { | ||
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); | ||
} | ||
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) | ||
}); | ||
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))) | ||
col.error = 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; | ||
} | ||
}), { | ||
withMessage: (message) => { | ||
return (entity, col) => Validators.unique(entity, col, message); | ||
} | ||
}); | ||
//# sourceMappingURL=validators.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.UrlBuilder = void 0; | ||
var UrlBuilder = /** @class */ (function () { | ||
function UrlBuilder(url) { | ||
class UrlBuilder { | ||
constructor(url) { | ||
this.url = url; | ||
} | ||
UrlBuilder.prototype.add = function (key, value) { | ||
add(key, value) { | ||
if (this.url.indexOf('?') >= 0) | ||
@@ -14,14 +14,12 @@ this.url += '&'; | ||
this.url += encodeURIComponent(key) + '=' + encodeURIComponent(value); | ||
}; | ||
UrlBuilder.prototype.addObject = function (object, suffix) { | ||
if (suffix === void 0) { suffix = ''; } | ||
} | ||
addObject(object, suffix = '') { | ||
if (object != undefined) | ||
for (var key in object) { | ||
var val = object[key]; | ||
let 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; | ||
var tslib_1 = require("tslib"); | ||
var inputTypes_1 = require("./inputTypes"); | ||
var column_1 = require("./src/column"); | ||
const inputTypes_1 = require("./inputTypes"); | ||
const column_1 = require("./src/column"); | ||
exports.DateValueConverter = { | ||
toJson: function (val) { | ||
toJson: (val) => { | ||
if (!val) | ||
@@ -19,3 +18,3 @@ return ''; | ||
}, | ||
fromJson: function (val) { | ||
fromJson: (val) => { | ||
if (val == undefined) | ||
@@ -29,7 +28,7 @@ return undefined; | ||
}, | ||
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) { | ||
toDb: x => x, | ||
fromDb: x => x, | ||
fromInput: x => exports.DateValueConverter.fromJson(x), | ||
toInput: x => exports.DateValueConverter.toJson(x), | ||
displayValue: (val) => { | ||
if (!val) | ||
@@ -41,5 +40,5 @@ return ''; | ||
exports.DateOnlyValueConverter = { | ||
fromInput: function (x) { return exports.DateOnlyValueConverter.fromJson(x); }, | ||
toInput: function (x) { return exports.DateOnlyValueConverter.toJson(x); }, | ||
toJson: function (val) { | ||
fromInput: x => exports.DateOnlyValueConverter.fromJson(x), | ||
toInput: x => exports.DateOnlyValueConverter.toJson(x), | ||
toJson: (val) => { | ||
var d = val; | ||
@@ -50,3 +49,3 @@ if (!d) | ||
}, | ||
fromJson: function (value) { | ||
fromJson: (value) => { | ||
if (!value || value == '' || value == '0000-00-00') | ||
@@ -57,3 +56,3 @@ return undefined; | ||
inputType: inputTypes_1.InputTypes.date, | ||
toDb: function (val) { | ||
toDb: (val) => { | ||
if (!val) | ||
@@ -64,3 +63,3 @@ return undefined; | ||
, | ||
fromDb: function (val) { | ||
fromDb: (val) => { | ||
var d = val; | ||
@@ -72,3 +71,3 @@ if (!d) | ||
fieldTypeInDb: 'date', | ||
displayValue: function (value) { | ||
displayValue: (value) => { | ||
if (!value) | ||
@@ -79,8 +78,8 @@ return ''; | ||
}; | ||
exports.CharDateValueConverter = tslib_1.__assign(tslib_1.__assign({}, exports.DateOnlyValueConverter), { toDb: function (d) { | ||
var val = exports.DateOnlyValueConverter.toJson(d); | ||
exports.CharDateValueConverter = Object.assign(Object.assign({}, exports.DateOnlyValueConverter), { toDb: (d) => { | ||
let val = exports.DateOnlyValueConverter.toJson(d); | ||
if (!val) | ||
return undefined; | ||
return val.replace(/-/g, ''); | ||
}, fromDb: function (val) { | ||
}, fromDb: (val) => { | ||
if (!val) | ||
@@ -91,8 +90,8 @@ return undefined; | ||
exports.BoolValueConverter = { | ||
toDb: function (val) { return val; }, | ||
toDb: (val) => val, | ||
inputType: inputTypes_1.InputTypes.checkbox, | ||
fromDb: function (value) { | ||
fromDb: (value) => { | ||
return exports.BoolValueConverter.fromJson(value); | ||
}, | ||
fromJson: function (value) { | ||
fromJson: value => { | ||
if (typeof value === "boolean") | ||
@@ -105,8 +104,8 @@ return value; | ||
}, | ||
toJson: function (x) { return x; }, | ||
fromInput: function (x) { return exports.BoolValueConverter.fromJson(x); }, | ||
toInput: function (x) { return exports.BoolValueConverter.toJson(x); } | ||
toJson: x => x, | ||
fromInput: x => exports.BoolValueConverter.fromJson(x), | ||
toInput: x => exports.BoolValueConverter.toJson(x) | ||
}; | ||
exports.NumberValueConverter = { | ||
fromDb: function (value) { | ||
fromDb: value => { | ||
if (value !== undefined) | ||
@@ -116,7 +115,7 @@ return +value; | ||
}, | ||
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; | ||
toDb: value => value, | ||
fromJson: value => exports.NumberValueConverter.fromDb(value), | ||
toJson: value => exports.NumberValueConverter.toDb(value), | ||
fromInput: (x, type) => { | ||
let r = +x; | ||
if (!x) | ||
@@ -126,3 +125,3 @@ return undefined; | ||
}, | ||
toInput: function (x, type) { | ||
toInput: (x, type) => { | ||
return x === null || x === void 0 ? void 0 : x.toString(); | ||
@@ -132,18 +131,18 @@ }, | ||
}; | ||
exports.IntegerValueConverter = tslib_1.__assign(tslib_1.__assign({}, exports.NumberValueConverter), { toJson: function (value) { | ||
var val = exports.NumberValueConverter.toDb(value); | ||
exports.IntegerValueConverter = Object.assign(Object.assign({}, exports.NumberValueConverter), { toJson: value => { | ||
let val = exports.NumberValueConverter.toDb(value); | ||
if (!val) | ||
return val; | ||
return +(+val).toFixed(0); | ||
}, toDb: function (value) { return exports.IntegerValueConverter.toJson(value); }, fieldTypeInDb: 'integer' }); | ||
}, toDb: value => exports.IntegerValueConverter.toJson(value), fieldTypeInDb: 'integer' }); | ||
exports.DefaultValueConverter = { | ||
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); } | ||
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) | ||
}; | ||
var ValueListValueConverter = /** @class */ (function () { | ||
function ValueListValueConverter(type) { | ||
class ValueListValueConverter { | ||
constructor(type) { | ||
this.type = type; | ||
@@ -155,31 +154,31 @@ this.info = ValueListInfo.get(this.type); | ||
} | ||
ValueListValueConverter.prototype.fromJson = function (val) { | ||
fromJson(val) { | ||
return this.byId(val); | ||
}; | ||
ValueListValueConverter.prototype.toJson = function (val) { | ||
} | ||
toJson(val) { | ||
if (!val) | ||
return undefined; | ||
return val.id; | ||
}; | ||
ValueListValueConverter.prototype.fromDb = function (val) { | ||
} | ||
fromDb(val) { | ||
return this.fromJson(val); | ||
}; | ||
ValueListValueConverter.prototype.toDb = function (val) { | ||
} | ||
toDb(val) { | ||
return this.toJson(val); | ||
}; | ||
ValueListValueConverter.prototype.toInput = function (val, inputType) { | ||
} | ||
toInput(val, inputType) { | ||
return this.toJson(val); | ||
}; | ||
ValueListValueConverter.prototype.fromInput = function (val, inputType) { | ||
} | ||
fromInput(val, inputType) { | ||
return this.fromJson(val); | ||
}; | ||
ValueListValueConverter.prototype.displayValue = function (val) { | ||
} | ||
displayValue(val) { | ||
if (!val) | ||
return ''; | ||
return val.caption; | ||
}; | ||
ValueListValueConverter.prototype.getOptions = function () { | ||
} | ||
getOptions() { | ||
return this.info.getOptions(); | ||
}; | ||
ValueListValueConverter.prototype.byId = function (key) { | ||
} | ||
byId(key) { | ||
if (key === undefined) | ||
@@ -190,8 +189,7 @@ return undefined; | ||
return this.info.byId(key); | ||
}; | ||
return ValueListValueConverter; | ||
}()); | ||
} | ||
} | ||
exports.ValueListValueConverter = ValueListValueConverter; | ||
var ValueListInfo = /** @class */ (function () { | ||
function ValueListInfo(valueListType) { | ||
class ValueListInfo { | ||
constructor(valueListType) { | ||
this.valueListType = valueListType; | ||
@@ -201,4 +199,4 @@ this.byIdMap = new Map(); | ||
this.isNumeric = false; | ||
for (var member in this.valueListType) { | ||
var s = this.valueListType[member]; | ||
for (let member in this.valueListType) { | ||
let s = this.valueListType[member]; | ||
if (s instanceof this.valueListType) { | ||
@@ -216,4 +214,4 @@ if (s.id === undefined) | ||
} | ||
ValueListInfo.get = function (type) { | ||
var r = typeCache.get(type); | ||
static get(type) { | ||
let r = typeCache.get(type); | ||
if (!r) | ||
@@ -223,14 +221,13 @@ r = new ValueListInfo(type); | ||
return r; | ||
}; | ||
ValueListInfo.prototype.getOptions = function () { | ||
} | ||
getOptions() { | ||
return this.values; | ||
}; | ||
ValueListInfo.prototype.byId = function (key) { | ||
} | ||
byId(key) { | ||
if (this.isNumeric) | ||
key = +key; | ||
return this.byIdMap.get(key); | ||
}; | ||
return ValueListInfo; | ||
}()); | ||
var typeCache = new Map(); | ||
} | ||
} | ||
const 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
421745
6331