remult 0.25.8-exp.1 → 0.25.8-exp.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/esm/graphql.js +2 -2
  2. package/esm/migrations/compare-migration-snapshots.js +1 -1
  3. package/esm/migrations/generate-migrations.js +12 -0
  4. package/esm/migrations/migrate.js +10 -0
  5. package/esm/migrations/update-migrations-ts-file.js +1 -1
  6. package/esm/postgres/postgres-data-provider.js +2 -2
  7. package/esm/remult-better-sqlite3.js +48 -0
  8. package/esm/remult-knex/index.js +7 -5
  9. package/esm/remult-mongo.js +2 -2
  10. package/esm/remult-sql-js.js +3 -83
  11. package/esm/remult-sqlite-core.js +105 -0
  12. package/esm/server/expressBridge.js +130 -29
  13. package/esm/server/initAsyncHooks.js +75 -1
  14. package/esm/src/CompoundIdField.js +8 -2
  15. package/esm/src/context.js +6 -16
  16. package/esm/src/data-api.js +56 -25
  17. package/esm/src/data-providers/rest-data-provider.js +17 -15
  18. package/esm/src/data-providers/sql-database.js +5 -3
  19. package/esm/src/filter/filter-interfaces.js +31 -0
  20. package/esm/src/isOfType.js +1 -1
  21. package/esm/src/remult3/Fields.js +70 -18
  22. package/esm/src/remult3/RepositoryImplementation.js +14 -9
  23. package/esm/src/remult3/addValidator.js +15 -0
  24. package/esm/src/remult3/remult3.js +15 -69
  25. package/esm/src/server-action.js +2 -2
  26. package/esm/src/validators.js +6 -3
  27. package/esm/src/valueConverters.js +1 -1
  28. package/graphql.js +2 -4
  29. package/migrations/compare-migration-snapshots.js +8 -9
  30. package/migrations/generate-migrations.d.ts +12 -0
  31. package/migrations/generate-migrations.js +12 -0
  32. package/migrations/migrate.d.ts +10 -0
  33. package/migrations/migrate.js +10 -0
  34. package/migrations/migration-types.d.ts +20 -0
  35. package/migrations/update-migrations-ts-file.js +25 -25
  36. package/package.json +11 -1
  37. package/postgres/postgres-data-provider.d.ts +2 -2
  38. package/postgres/postgres-data-provider.js +2 -2
  39. package/remult-better-sqlite3.d.ts +12 -0
  40. package/remult-better-sqlite3.js +70 -0
  41. package/remult-knex/index.d.ts +1 -1
  42. package/remult-knex/index.js +7 -5
  43. package/remult-mongo.d.ts +2 -2
  44. package/remult-mongo.js +2 -2
  45. package/remult-sql-js.d.ts +2 -17
  46. package/remult-sql-js.js +11 -166
  47. package/remult-sqlite-core.d.ts +21 -0
  48. package/remult-sqlite-core.js +219 -0
  49. package/server/expressBridge.d.ts +21 -0
  50. package/server/expressBridge.js +140 -32
  51. package/server/initAsyncHooks.d.ts +16 -0
  52. package/server/initAsyncHooks.js +128 -2
  53. package/src/CompoundIdField.js +8 -2
  54. package/src/column-interfaces.d.ts +9 -3
  55. package/src/context.d.ts +7 -5
  56. package/src/context.js +11 -28
  57. package/src/data-api.d.ts +12 -8
  58. package/src/data-api.js +115 -75
  59. package/src/data-providers/rest-data-provider.js +26 -15
  60. package/src/data-providers/sql-database.d.ts +1 -2
  61. package/src/data-providers/sql-database.js +5 -3
  62. package/src/filter/filter-interfaces.js +64 -12
  63. package/src/isOfType.js +1 -1
  64. package/src/remult3/Fields.d.ts +36 -0
  65. package/src/remult3/Fields.js +81 -19
  66. package/src/remult3/RepositoryImplementation.d.ts +9 -13
  67. package/src/remult3/RepositoryImplementation.js +64 -54
  68. package/src/remult3/addValidator.d.ts +2 -0
  69. package/src/remult3/addValidator.js +20 -0
  70. package/src/remult3/remult3.d.ts +10 -16
  71. package/src/remult3/remult3.js +15 -69
  72. package/src/server-action.js +2 -2
  73. package/src/validators.d.ts +1 -0
  74. package/src/validators.js +10 -4
  75. package/src/valueConverters.js +1 -1
package/esm/graphql.js CHANGED
@@ -904,7 +904,7 @@ export function translateWhereToRestBody(fields, { where }) {
904
904
  }
905
905
  }
906
906
  if (where.OR) {
907
- result.OR = where.OR.map((where) => translateWhereToRestBody(fields, { where }));
907
+ result.OR = where.OR.map((where) => translateWhereToRestBody(fields, { where }).where);
908
908
  }
909
- return result;
909
+ return { where: result };
910
910
  }
@@ -28,8 +28,8 @@ export async function compareMigrationSnapshot({ entities, snapshot, migrationBu
28
28
  }
29
29
  }
30
30
  }
31
- return snapshot;
32
31
  }
32
+ return snapshot;
33
33
  }
34
34
  export function emptySnapshot() {
35
35
  return {
@@ -5,6 +5,18 @@ import { updateMigrationsFile } from './update-migrations-ts-file.js';
5
5
  import { DefaultMigrationBuilder, } from './migration-types.js';
6
6
  import { isOfType } from '../src/isOfType.js';
7
7
  import { initDataProvider } from '../server/initDataProvider.js';
8
+ /**
9
+ * Generates migration scripts based on changes in entities.
10
+ *
11
+ * @param options - Configuration options for generating migrations.
12
+ * @param options.entities - An array of entity classes to be included in the migration.
13
+ * @param options.dataProvider - The data provider instance or a function returning a promise of the data provider.
14
+ * @param options.migrationsFolder - (Optional) The path to the folder where migration scripts will be stored. Default is 'src/server/migrations'.
15
+ * @param options.snapshotFile - (Optional) The path to the file where the snapshot of the last known state will be stored. Default is 'migrations-snapshot.json' in the `migrationsFolder`.
16
+ * @param options.migrationsTSFile - (Optional) The path to the TypeScript file where the generated migrations will be written. Default is 'migrations.ts' in the `migrationsFolder`.
17
+ * @param options.endConnection - (Optional) Determines whether to close the database connection after generating migrations. Default is true.
18
+ * @see [Migrations](http://remult.dev/docs/migrations.html)
19
+ */
8
20
  export async function generateMigrations(options) {
9
21
  const migrationDir = options.migrationsFolder ||
10
22
  path.join(process.cwd(), 'src/server/migrations');
@@ -3,6 +3,16 @@ import { Entity, IdEntity, Fields, remult, Remult, } from '../index.js';
3
3
  import { initDataProvider } from '../server/initDataProvider.js';
4
4
  import { doTransaction } from '../src/context.js';
5
5
  import { cast, isOfType } from '../src/isOfType.js';
6
+ /**
7
+ * Applies migration scripts to update the database schema.
8
+ *
9
+ * @param options - Configuration options for applying migrations.
10
+ * @param options.migrations - An object containing the migration scripts, each keyed by a unique identifier.
11
+ * @param options.dataProvider - The data provider instance or a function returning a promise of the data provider.
12
+ * @param options.migrationsTable - (Optional) The name of the table that tracks applied migrations. Default is '__remult_migrations_version'.
13
+ * @param options.endConnection - (Optional) Determines whether to close the database connection after applying migrations. Default is true.
14
+ * @see [Migrations](http://remult.dev/docs/migrations.html)
15
+ */
6
16
  export async function migrate(options) {
7
17
  let migrationTableName = options.migrationsTable || '__remult_migrations_version';
8
18
  const dataProvider = await initDataProvider(options.dataProvider);
@@ -1,5 +1,5 @@
1
1
  // consider replacing with https://www.npmjs.com/package/ts-morph
2
- import * as ts from 'typescript';
2
+ import ts from 'typescript';
3
3
  import * as fs from 'fs';
4
4
  export async function updateMigrationsFile(filePath, steps) {
5
5
  let maxStep = -1;
@@ -8,8 +8,8 @@ export class PostgresDataProvider {
8
8
  pool;
9
9
  options;
10
10
  supportsJsonColumnType = true;
11
- static getDb(remult) {
12
- const r = (remult || defaultRemult).dataProvider;
11
+ static getDb(dataProvider) {
12
+ const r = (dataProvider || defaultRemult.dataProvider);
13
13
  if (!r._getSourceSql)
14
14
  throw 'the data provider is not an SqlDatabase';
15
15
  const me = r._getSourceSql();
@@ -0,0 +1,48 @@
1
+ import { SqliteCoreDataProvider } from './remult-sqlite-core.js';
2
+ export class BetterSqlite3DataProvider extends SqliteCoreDataProvider {
3
+ constructor(db) {
4
+ super(() => new BetterSqlite3Command(db), async () => { db.close(); });
5
+ }
6
+ }
7
+ class BetterSqlite3Command {
8
+ db;
9
+ values = {};
10
+ i = 0;
11
+ constructor(db) {
12
+ this.db = db;
13
+ }
14
+ async execute(sql) {
15
+ const s = this.db.prepare(sql);
16
+ if (s.reader) {
17
+ return new BetterSqlite3SqlResult(s.all(this.values));
18
+ }
19
+ else {
20
+ const result = s.run(this.values);
21
+ return new BetterSqlite3SqlResult([]);
22
+ }
23
+ }
24
+ addParameterAndReturnSqlToken(val) {
25
+ return this.param(val);
26
+ }
27
+ param(val) {
28
+ if (val instanceof Date)
29
+ val = val.valueOf();
30
+ if (typeof val === "boolean")
31
+ val = val ? 1 : 0;
32
+ const key = ':' + (this.i++);
33
+ this.values[key.substring(1)] = (val);
34
+ return key;
35
+ }
36
+ }
37
+ export class BetterSqlite3SqlResult {
38
+ result;
39
+ constructor(result) {
40
+ this.result = result;
41
+ this.rows =
42
+ result.map((row) => Object.keys(row).reduce((prev, curr) => ({ ...prev, [curr]: row[curr] }), {}));
43
+ }
44
+ rows;
45
+ getColumnKeyInResultForIndexInSelect(index) {
46
+ return Object.keys(this.result[0])[index];
47
+ }
48
+ }
@@ -41,8 +41,8 @@ export class KnexDataProvider {
41
41
  execute(sql) {
42
42
  return this.createCommand().execute(sql);
43
43
  }
44
- static getDb(remult) {
45
- const r = (remult || remultContext).dataProvider;
44
+ static getDb(dataProvider) {
45
+ const r = (dataProvider || remultContext.dataProvider);
46
46
  if (!r.knex)
47
47
  throw 'the data provider is not an KnexDataProvider';
48
48
  return r.knex;
@@ -539,15 +539,17 @@ class KnexBridgeToSQLCommand {
539
539
  constructor(source) {
540
540
  this.source = source;
541
541
  }
542
- values = [];
542
+ values = {};
543
+ i = 0;
543
544
  addParameterAndReturnSqlToken(val) {
544
545
  return this.param(val);
545
546
  }
546
547
  param(val) {
547
548
  if (Array.isArray(val))
548
549
  val = JSON.stringify(val);
549
- this.values.push(val);
550
- return '?';
550
+ const key = ':' + (this.i++);
551
+ this.values[key.substring(1)] = val;
552
+ return key;
551
553
  }
552
554
  async execute(sql) {
553
555
  return await this.source.raw(sql, this.values).then((r) => {
@@ -16,8 +16,8 @@ export class MongoDataProvider {
16
16
  }
17
17
  session;
18
18
  disableTransactions = false;
19
- static getDb(remult) {
20
- const r = (remult || remultContext).dataProvider;
19
+ static getDb(dataProvider) {
20
+ const r = (dataProvider || remultContext.dataProvider);
21
21
  if (!r.db)
22
22
  throw 'the data provider is not a MongoDataProvider';
23
23
  return { db: r.db, session: r.session };
@@ -1,87 +1,7 @@
1
- import { SqlDatabase } from './src/data-providers/sql-database.js';
2
- import { dbNamesOf, shouldNotCreateField, } from './src/filter/filter-consumer-bridge-to-sql-request.js';
3
- import { isAutoIncrement } from './src/remult3/RepositoryImplementation.js';
4
- export class SqlJsDataProvider {
5
- db;
1
+ import { SqliteCoreDataProvider } from './remult-sqlite-core.js';
2
+ export class SqlJsDataProvider extends SqliteCoreDataProvider {
6
3
  constructor(db) {
7
- this.db = db;
8
- }
9
- orderByNullsFirst;
10
- async end() {
11
- ;
12
- (await this.db).close();
13
- }
14
- getLimitSqlSyntax(limit, offset) {
15
- return ' limit ' + limit + ' offset ' + offset;
16
- }
17
- afterMutation;
18
- createCommand() {
19
- return new SqlJsCommand(this.db);
20
- }
21
- transaction(action) {
22
- throw new Error('Method not implemented.');
23
- }
24
- async entityIsUsedForTheFirstTime(entity) {
25
- await this.createTable(entity);
26
- }
27
- async ensureSchema(entities) {
28
- for (const entity of entities) {
29
- await this.createTable(entity);
30
- }
31
- }
32
- async dropTable(entity) {
33
- let e = await dbNamesOf(entity);
34
- let sql = 'drop table if exists ' + e.$entityName;
35
- if (SqlDatabase.LogToConsole)
36
- console.info(sql);
37
- await this.createCommand().execute(sql);
38
- }
39
- addColumnSqlSyntax(x, dbName) {
40
- let result = dbName;
41
- const nullNumber = x.allowNull ? '' : ' default 0 not null';
42
- if (x.valueType == Date)
43
- result += ' integer';
44
- else if (x.valueType == Boolean)
45
- result += ' integer ' + nullNumber;
46
- else if (x.valueType == Number) {
47
- if (!x.valueConverter.fieldTypeInDb)
48
- result += ' real ' + nullNumber;
49
- else
50
- result += ' ' + x.valueConverter.fieldTypeInDb + ' ' + nullNumber;
51
- }
52
- else
53
- result += ' text' + (x.allowNull ? ' ' : " default '' not null ");
54
- return result;
55
- }
56
- async createTable(entity) {
57
- let result = '';
58
- let e = await dbNamesOf(entity);
59
- for (const x of entity.fields) {
60
- if (!shouldNotCreateField(x, e) || isAutoIncrement(x)) {
61
- if (result.length != 0)
62
- result += ',';
63
- result += '\r\n ';
64
- if (isAutoIncrement(x)) {
65
- if (x.key != entity.idMetadata.field.key)
66
- throw 'in web sql, autoincrement is only allowed for primary key';
67
- result += e.$dbNameOf(x) + ' integer primary key autoincrement';
68
- }
69
- else {
70
- result += this.addColumnSqlSyntax(x, e.$dbNameOf(x));
71
- if (x.key == entity.idMetadata.field.key) {
72
- result += ' primary key';
73
- }
74
- }
75
- }
76
- }
77
- let sql = 'create table if not exists ' + e.$entityName + ' (' + result + '\r\n)';
78
- if (SqlDatabase.LogToConsole)
79
- console.log(sql);
80
- await this.createCommand().execute(sql);
81
- }
82
- supportsJsonColumnType;
83
- wrapIdentifier(name) {
84
- return name;
4
+ super(() => new SqlJsCommand(db), async () => (await db).close());
85
5
  }
86
6
  }
87
7
  class SqlJsCommand {
@@ -0,0 +1,105 @@
1
+ import { SqlDatabase } from './src/data-providers/sql-database.js';
2
+ import { dbNamesOf, shouldNotCreateField, } from './src/filter/filter-consumer-bridge-to-sql-request.js';
3
+ import { isAutoIncrement } from './src/remult3/RepositoryImplementation.js';
4
+ export class SqliteCoreDataProvider {
5
+ createCommand;
6
+ end;
7
+ constructor(createCommand, end) {
8
+ this.createCommand = createCommand;
9
+ this.end = end;
10
+ }
11
+ orderByNullsFirst;
12
+ getLimitSqlSyntax(limit, offset) {
13
+ return ' limit ' + limit + ' offset ' + offset;
14
+ }
15
+ afterMutation;
16
+ provideMigrationBuilder(builder) {
17
+ let self = this;
18
+ return {
19
+ createTable: async (entity) => {
20
+ builder.addSql(await self.getCreateTableSql(entity));
21
+ },
22
+ addColumn: async (entity, field) => {
23
+ let e = await dbNamesOf(entity);
24
+ let sql = `alter table ${e.$entityName} add column ${self.addColumnSqlSyntax(field, e.$dbNameOf(field))}`;
25
+ builder.addSql(sql);
26
+ }
27
+ };
28
+ }
29
+ async transaction(action) {
30
+ this.createCommand().execute("Begin Transaction");
31
+ try {
32
+ await action(this);
33
+ this.createCommand().execute("Commit");
34
+ }
35
+ catch (err) {
36
+ this.createCommand().execute("Rollback");
37
+ throw err;
38
+ }
39
+ }
40
+ async entityIsUsedForTheFirstTime(entity) {
41
+ }
42
+ async ensureSchema(entities) {
43
+ for (const entity of entities) {
44
+ await this.createTable(entity);
45
+ }
46
+ }
47
+ async dropTable(entity) {
48
+ let e = await dbNamesOf(entity);
49
+ let sql = 'drop table if exists ' + e.$entityName;
50
+ if (SqlDatabase.LogToConsole)
51
+ console.info(sql);
52
+ await this.createCommand().execute(sql);
53
+ }
54
+ addColumnSqlSyntax(x, dbName) {
55
+ let result = dbName;
56
+ const nullNumber = x.allowNull ? '' : ' default 0 not null';
57
+ if (x.valueType == Date)
58
+ result += ' integer';
59
+ else if (x.valueType == Boolean)
60
+ result += ' integer ' + nullNumber;
61
+ else if (x.valueType == Number) {
62
+ if (!x.valueConverter.fieldTypeInDb)
63
+ result += ' numeric ' + nullNumber;
64
+ else
65
+ result += ' ' + x.valueConverter.fieldTypeInDb + ' ' + nullNumber;
66
+ }
67
+ else
68
+ result += ' text' + (x.allowNull ? ' ' : " default '' not null ");
69
+ return result;
70
+ }
71
+ async createTable(entity) {
72
+ let sql = await this.getCreateTableSql(entity);
73
+ if (SqlDatabase.LogToConsole)
74
+ console.log(sql);
75
+ await this.createCommand().execute(sql);
76
+ }
77
+ supportsJsonColumnType;
78
+ async getCreateTableSql(entity) {
79
+ let result = '';
80
+ let e = await dbNamesOf(entity);
81
+ for (const x of entity.fields) {
82
+ if (!shouldNotCreateField(x, e) || isAutoIncrement(x)) {
83
+ if (result.length != 0)
84
+ result += ',';
85
+ result += '\r\n ';
86
+ if (isAutoIncrement(x)) {
87
+ if (x.key != entity.idMetadata.field.key)
88
+ throw 'in web sql, autoincrement is only allowed for primary key';
89
+ result += e.$dbNameOf(x) + ' integer primary key autoincrement';
90
+ }
91
+ else {
92
+ result += this.addColumnSqlSyntax(x, e.$dbNameOf(x));
93
+ if (x.key == entity.idMetadata.field.key) {
94
+ result += ' primary key';
95
+ }
96
+ }
97
+ }
98
+ }
99
+ let sql = 'create table if not exists ' + e.$entityName + ' (' + result + '\r\n)';
100
+ return sql;
101
+ }
102
+ wrapIdentifier(name) {
103
+ return name;
104
+ }
105
+ }
@@ -13,6 +13,7 @@ import { serverActionField } from '../src/server-action-info.js';
13
13
  import { initDataProvider } from './initDataProvider.js';
14
14
  import { remultStatic } from '../src/remult-static.js';
15
15
  import remultAdminHtml from './remult-admin.js';
16
+ import { isOfType } from '../src/isOfType.js';
16
17
  export function createRemultServerCore(options, serverCoreOptions) {
17
18
  if (!options) {
18
19
  options = {};
@@ -249,8 +250,8 @@ export class RemultServerImplementation {
249
250
  console.info('[remult] ' + myRoute);
250
251
  r.route(myRoute)
251
252
  .get(this.process((c, req, res, orig) => dataApiFactory(c).httpGet(res, req, () => this.serializeContext(c))))
252
- .put(this.process(async (c, req, res, _, __, orig) => dataApiFactory(c).put(res, '', await this.coreOptions.getRequestBody(orig))))
253
- .delete(this.process(async (c, req, res, orig) => dataApiFactory(c).delete(res, '')))
253
+ .put(this.process(async (c, req, res, _, __, orig) => dataApiFactory(c).updateMany(res, req, await this.coreOptions.getRequestBody(orig))))
254
+ .delete(this.process(async (c, req, res, _, __, orig) => dataApiFactory(c).deleteMany(res, req, undefined)))
254
255
  .post(this.process(async (c, req, res, _, __, orig) => dataApiFactory(c).httpPost(res, req, await this.coreOptions.getRequestBody(orig), () => this.serializeContext(c))));
255
256
  r.route(myRoute + '/:id')
256
257
  //@ts-ignore
@@ -285,7 +286,7 @@ export class RemultServerImplementation {
285
286
  genReq.params = req['_tempParams'];
286
287
  }
287
288
  let myReq = new ExpressRequestBridgeToDataApiRequest(genReq);
288
- let myRes = new ExpressResponseBridgeToDataApiResponse(origRes, req);
289
+ let myRes = new ExpressResponseBridgeToDataApiResponse(origRes, req, this.options.error);
289
290
  try {
290
291
  await this.runWithRemult(async (remult) => {
291
292
  if (req) {
@@ -315,7 +316,7 @@ export class RemultServerImplementation {
315
316
  });
316
317
  }
317
318
  catch (err) {
318
- myRes.error(serializeError(err));
319
+ myRes.error(err, undefined);
319
320
  }
320
321
  };
321
322
  }
@@ -466,6 +467,17 @@ export class RemultServerImplementation {
466
467
  return secureBase(condition, def, item);
467
468
  };
468
469
  let apiPath = (spec.paths[this.options.rootPath + '/' + key] = {});
470
+ let itemInBody = {
471
+ requestBody: {
472
+ content: {
473
+ 'application/json': {
474
+ schema: {
475
+ $ref: '#/components/schemas/' + mutationKey,
476
+ },
477
+ },
478
+ },
479
+ },
480
+ };
469
481
  let apiPathWithId = (spec.paths[this.options.rootPath + '/' + key + '/{id}'] = {});
470
482
  //https://github.com/2fd/open-api.d.ts
471
483
  apiPath.get = secure(meta.options.allowApiRead, true, {
@@ -518,6 +530,73 @@ export class RemultServerImplementation {
518
530
  },
519
531
  },
520
532
  });
533
+ apiPath.delete = secure(meta.options.allowApiDelete, true, {
534
+ description: 'deletes row of ' +
535
+ key +
536
+ '. supports filter operators. For more info on filtering [see this article](https://remult.dev/docs/rest-api.html#filter)',
537
+ parameters: [...parameters],
538
+ responses: {
539
+ '400': {
540
+ description: 'Error: Bad Request',
541
+ content: {
542
+ 'application/json': {
543
+ schema: {
544
+ $ref: '#/components/schemas/InvalidResponse',
545
+ },
546
+ },
547
+ },
548
+ },
549
+ '200': {
550
+ description: 'returns the number of deleted rows ' + key,
551
+ content: {
552
+ 'application/json': {
553
+ schema: {
554
+ type: 'object',
555
+ properties: {
556
+ deleted: {
557
+ type: 'number',
558
+ },
559
+ },
560
+ },
561
+ },
562
+ },
563
+ },
564
+ },
565
+ });
566
+ apiPath.put = secure(meta.options.allowApiDelete, true, {
567
+ description: 'updates row of ' +
568
+ key +
569
+ '. supports filter operators. For more info on filtering [see this article](https://remult.dev/docs/rest-api.html#filter)',
570
+ parameters: [...parameters],
571
+ ...itemInBody,
572
+ responses: {
573
+ '400': {
574
+ description: 'Error: Bad Request',
575
+ content: {
576
+ 'application/json': {
577
+ schema: {
578
+ $ref: '#/components/schemas/InvalidResponse',
579
+ },
580
+ },
581
+ },
582
+ },
583
+ '200': {
584
+ description: 'returns the number of updated rows ' + key,
585
+ content: {
586
+ 'application/json': {
587
+ schema: {
588
+ type: 'object',
589
+ properties: {
590
+ updated: {
591
+ type: 'number',
592
+ },
593
+ },
594
+ },
595
+ },
596
+ },
597
+ },
598
+ },
599
+ });
521
600
  let idParameter = {
522
601
  name: 'id',
523
602
  in: 'path',
@@ -525,17 +604,6 @@ export class RemultServerImplementation {
525
604
  required: true,
526
605
  schema: { type: 'string' },
527
606
  };
528
- let itemInBody = {
529
- requestBody: {
530
- content: {
531
- 'application/json': {
532
- schema: {
533
- $ref: '#/components/schemas/' + mutationKey,
534
- },
535
- },
536
- },
537
- },
538
- };
539
607
  apiPath.post = secure(meta.options.allowApiInsert, false, {
540
608
  //"summary": "insert a " + key,
541
609
  //"description": "insert a " + key,
@@ -673,15 +741,17 @@ class ExpressRequestBridgeToDataApiRequest {
673
741
  class ExpressResponseBridgeToDataApiResponse {
674
742
  r;
675
743
  req;
744
+ handleError;
676
745
  forbidden() {
677
- this.setStatus(403).end();
746
+ this.error({ message: 'Forbidden' }, undefined, 403);
678
747
  }
679
748
  setStatus(status) {
680
749
  return this.r.status(status);
681
750
  }
682
- constructor(r, req) {
751
+ constructor(r, req, handleError) {
683
752
  this.r = r;
684
753
  this.req = req;
754
+ this.handleError = handleError;
685
755
  }
686
756
  progress(progress) { }
687
757
  success(data) {
@@ -694,22 +764,53 @@ class ExpressResponseBridgeToDataApiResponse {
694
764
  this.setStatus(204).end();
695
765
  }
696
766
  notFound() {
697
- this.setStatus(404).end();
767
+ this.error({ message: 'Forbidden' }, undefined, 404);
698
768
  }
699
- error(data) {
700
- data = serializeError(data);
701
- console.error({
702
- message: data.message,
703
- stack: data.stack?.split('\n'),
704
- url: this.req?.url,
705
- method: this.req?.method,
769
+ async error(exception, entity, httpStatusCode) {
770
+ let data = serializeError(exception);
771
+ if (!httpStatusCode) {
772
+ if (data.httpStatusCode) {
773
+ httpStatusCode = data.httpStatusCode;
774
+ }
775
+ else if (isOfType(exception, 'isForbiddenError') &&
776
+ exception.isForbiddenError) {
777
+ httpStatusCode = 403;
778
+ }
779
+ else if (data.modelState) {
780
+ httpStatusCode = 400;
781
+ }
782
+ else {
783
+ httpStatusCode = 500;
784
+ }
785
+ }
786
+ let responseSent = false;
787
+ const sendError = (httpStatusCode, body) => {
788
+ if (responseSent) {
789
+ throw Error('Error response already sent');
790
+ }
791
+ responseSent = true;
792
+ console.error({
793
+ message: body.message,
794
+ httpStatusCode,
795
+ stack: data.stack?.split('\n'),
796
+ url: this.req?.url,
797
+ method: this.req?.method,
798
+ });
799
+ this.setStatus(httpStatusCode).json(body);
800
+ };
801
+ await this.handleError?.({
802
+ httpStatusCode,
803
+ req: this.req,
804
+ entity,
805
+ exception,
806
+ responseBody: data,
807
+ sendError,
706
808
  });
707
- this.setStatus(400).json(data);
809
+ if (!responseSent) {
810
+ sendError(httpStatusCode, data);
811
+ }
708
812
  }
709
813
  }
710
- function throwError() {
711
- throw 'Invalid';
712
- }
713
814
  class inProcessQueueHandler {
714
815
  storage;
715
816
  constructor(storage) {