remult 3.5.0-next.1 → 3.5.0-next.2

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 (36) hide show
  1. package/esm/remult-knex/index.js +29 -6
  2. package/esm/server/remult-api-server.js +13 -5
  3. package/esm/src/buildRestDataProvider.js +4 -4
  4. package/esm/src/context.js +1 -1
  5. package/esm/src/data-providers/array-entity-data-provider.js +4 -4
  6. package/esm/src/data-providers/rest-data-provider-using-fetch.js +11 -4
  7. package/esm/src/filter/filter-consumer-bridge-to-sql-request.js +35 -4
  8. package/esm/src/filter/filter-interfaces.js +18 -4
  9. package/esm/src/remult-proxy.js +12 -0
  10. package/esm/src/remult-static.js +1 -0
  11. package/esm/src/remult3/RepositoryImplementation.js +24 -0
  12. package/esm/src/remult3/remult3.js +2 -0
  13. package/esm/src/server-action.js +43 -14
  14. package/index.d.ts +3 -2
  15. package/package.json +1 -1
  16. package/remult-knex/index.js +29 -6
  17. package/server/remult-api-server.d.ts +16 -0
  18. package/server/remult-api-server.js +18 -11
  19. package/src/buildRestDataProvider.d.ts +1 -1
  20. package/src/buildRestDataProvider.js +5 -5
  21. package/src/context.js +1 -1
  22. package/src/data-providers/array-entity-data-provider.js +4 -4
  23. package/src/data-providers/rest-data-provider-using-fetch.d.ts +1 -1
  24. package/src/data-providers/rest-data-provider-using-fetch.js +10 -3
  25. package/src/filter/filter-consumer-bridge-to-sql-request.d.ts +8 -0
  26. package/src/filter/filter-consumer-bridge-to-sql-request.js +58 -19
  27. package/src/filter/filter-interfaces.js +19 -2
  28. package/src/remult-proxy.js +28 -0
  29. package/src/remult-static.d.ts +2 -0
  30. package/src/remult-static.js +1 -0
  31. package/src/remult3/RepositoryImplementation.d.ts +7 -0
  32. package/src/remult3/RepositoryImplementation.js +51 -0
  33. package/src/remult3/remult3.d.ts +62 -4
  34. package/src/remult3/remult3.js +2 -0
  35. package/src/server-action.d.ts +34 -2
  36. package/src/server-action.js +195 -115
@@ -1,4 +1,4 @@
1
- import { CustomSqlFilterBuilder, dbNamesOfWithForceSqlExpression, escapeLike, LIKE_ESCAPE_SQL, } from '../src/filter/filter-consumer-bridge-to-sql-request.js';
1
+ import { CustomSqlFilterBuilder, dbNamesOfWithForceSqlExpression, escapeLike, HandleNull, LIKE_ESCAPE_SQL, } from '../src/filter/filter-consumer-bridge-to-sql-request.js';
2
2
  import { dbNamesOf, isDbReadonly, shouldCreateEntity, shouldNotCreateField, } from '../src/filter/filter-consumer-bridge-to-sql-request.js';
3
3
  import { customDatabaseFilterToken, Filter, } from '../src/filter/filter-interfaces.js';
4
4
  import { remult as remultContext } from '../src/remult-proxy.js';
@@ -372,6 +372,7 @@ class FilterConsumerBridgeToKnexRequest {
372
372
  _addWhere = true;
373
373
  promises = [];
374
374
  result = [];
375
+ handleNull = new HandleNull();
375
376
  async resolveWhere() {
376
377
  while (this.promises.length > 0) {
377
378
  let p = this.promises;
@@ -393,12 +394,14 @@ class FilterConsumerBridgeToKnexRequest {
393
394
  or(orElements) {
394
395
  this.promises.push((async () => {
395
396
  const result = [];
397
+ const branches = new HandleNull();
396
398
  for (const element of orElements) {
397
399
  let f = new FilterConsumerBridgeToKnexRequest(this.innerNameProvider, this.rawSqlWrapIdentifier, this.jsonColumnStorage);
398
400
  f._addWhere = false;
399
401
  element.__applyToConsumer(f);
400
402
  let where = await f.resolveWhere();
401
403
  if (where.length > 0) {
404
+ branches.add(f.handleNull);
402
405
  result.push((b) => {
403
406
  b.orWhere((b) => {
404
407
  where.forEach((x) => x(b));
@@ -409,6 +412,7 @@ class FilterConsumerBridgeToKnexRequest {
409
412
  return; //empty or means all rows
410
413
  }
411
414
  if (result.length > 0) {
415
+ this.handleNull.add(branches);
412
416
  this.result.push((b) => b.where((x) => result.find((y) => y(x))));
413
417
  }
414
418
  })());
@@ -420,23 +424,38 @@ class FilterConsumerBridgeToKnexRequest {
420
424
  element.__applyToConsumer(f);
421
425
  let where = await f.resolveWhere();
422
426
  if (where.length > 0) {
423
- this.result.push((b) => {
424
- b.whereNot((b) => {
425
- where.forEach((x) => x(b));
427
+ if (f.handleNull.nullable) {
428
+ this.result.push((b) => {
429
+ const nested = b.client.queryBuilder();
430
+ where.forEach((x) => x(nested));
431
+ const compiled = nested.toSQL();
432
+ const pred = compiled.sql.replace(/^select \* where /i, '');
433
+ b.whereRaw(`case when (${pred}) then 0 else 1 end = 1`, compiled.bindings);
426
434
  });
427
- });
435
+ }
436
+ else {
437
+ this.result.push((b) => {
438
+ b.whereNot((x) => {
439
+ where.forEach((w) => w(x));
440
+ });
441
+ });
442
+ }
428
443
  }
429
444
  else
430
- return; //empty or means all rows
445
+ this.result.push((b) => b.whereRaw('1 = 0'));
431
446
  })());
432
447
  }
433
448
  isNull(col) {
449
+ this.handleNull.column(col);
434
450
  this.result.push((b) => b.whereNull(this.innerNameProvider.$dbNameOf(col)));
435
451
  }
436
452
  isNotNull(col) {
453
+ this.handleNull.column(col);
437
454
  this.result.push((b) => b.whereNotNull(this.innerNameProvider.$dbNameOf(col)));
438
455
  }
439
456
  isIn(col, val) {
457
+ if (val?.length)
458
+ this.handleNull.column(col);
440
459
  this.result.push((knex) => knex.whereIn(this.innerNameProvider.$dbNameOf(col), val.map((x) => translateValueAndHandleArrayAndHandleArray(col, x, this.jsonColumnStorage))));
441
460
  }
442
461
  isEqualTo(col, val) {
@@ -470,6 +489,7 @@ class FilterConsumerBridgeToKnexRequest {
470
489
  this.like(col, '%' + escapeLike(val));
471
490
  }
472
491
  like(col, pattern, not = '') {
492
+ this.handleNull.column(col);
473
493
  this.result.push((b) => b.whereRaw(not +
474
494
  'lower (' +
475
495
  b.client.ref(this.innerNameProvider.$dbNameOf(col)) +
@@ -478,12 +498,14 @@ class FilterConsumerBridgeToKnexRequest {
478
498
  this.promises.push((async () => { })());
479
499
  }
480
500
  add(col, val, operator) {
501
+ this.handleNull.column(col);
481
502
  this.result.push((b) => b.where(this.innerNameProvider.$dbNameOf(col), operator, translateValueAndHandleArrayAndHandleArray(col, val, this.jsonColumnStorage)));
482
503
  }
483
504
  databaseCustom(databaseCustom) {
484
505
  this.promises.push((async () => {
485
506
  if (databaseCustom?.buildKnex) {
486
507
  this.result.push(await databaseCustom.buildKnex());
508
+ this.handleNull.custom();
487
509
  }
488
510
  if (databaseCustom?.buildSql) {
489
511
  let r = new KnexCommandHelper();
@@ -492,6 +514,7 @@ class FilterConsumerBridgeToKnexRequest {
492
514
  if (typeof sql !== 'string')
493
515
  sql = item.sql;
494
516
  if (sql) {
517
+ this.handleNull.custom();
495
518
  this.result.push((b) => b.whereRaw(sql, r.values));
496
519
  }
497
520
  }
@@ -2,6 +2,7 @@ import { __decorate, __metadata } from "tslib";
2
2
  import { SseSubscriptionServer } from '../SseSubscriptionServer.js';
3
3
  import { Remult, RemultAsyncLocalStorage, withRemult } from '../src/context.js';
4
4
  import { DataApi, serializeError } from '../src/data-api.js';
5
+ import { EntityError } from '../src/data-interfaces.js';
5
6
  import { liveQueryKeepAliveRoute } from '../src/live-query/SubscriptionChannel.js';
6
7
  import { InMemoryLiveQueryStorage, LiveQueryPublisher, } from '../src/live-query/SubscriptionServer.js';
7
8
  import { IdEntity } from '../src/remult3/IdEntity.js';
@@ -360,7 +361,7 @@ export class RemultServerImplementation {
360
361
  genReq.params = req['_tempParams'];
361
362
  }
362
363
  let myReq = new RequestBridgeToDataApiRequest(genReq);
363
- let myRes = new ResponseBridgeToDataApiResponse(origRes, req, genReq, this.options.error);
364
+ let myRes = new ResponseBridgeToDataApiResponse(origRes, req, genReq, this.options.error, this.options.defaultErrorStatus);
364
365
  try {
365
366
  if (remultStatic.asyncContext.isInInitRequest() &&
366
367
  !doNotReuseInitRequest)
@@ -847,17 +848,19 @@ class ResponseBridgeToDataApiResponse {
847
848
  req;
848
849
  genReq;
849
850
  handleError;
851
+ defaultErrorStatus;
850
852
  forbidden(message = 'Forbidden') {
851
853
  this.error({ message }, undefined, 403);
852
854
  }
853
855
  setStatus(status) {
854
856
  return this.r.status(status);
855
857
  }
856
- constructor(r, req, genReq, handleError) {
858
+ constructor(r, req, genReq, handleError, defaultErrorStatus = 400) {
857
859
  this.r = r;
858
860
  this.req = req;
859
861
  this.genReq = genReq;
860
862
  this.handleError = handleError;
863
+ this.defaultErrorStatus = defaultErrorStatus;
861
864
  }
862
865
  progress(progress) { }
863
866
  success(data) {
@@ -875,16 +878,21 @@ class ResponseBridgeToDataApiResponse {
875
878
  async error(exception, entity, httpStatusCode) {
876
879
  let data = serializeError(exception);
877
880
  if (!httpStatusCode) {
878
- if (data.httpStatusCode) {
879
- httpStatusCode = data.httpStatusCode;
881
+ // serializeError drops httpStatusCode from an Error.
882
+ const explicitStatus = exception.httpStatusCode ?? data.httpStatusCode;
883
+ if (explicitStatus) {
884
+ httpStatusCode = explicitStatus;
880
885
  }
881
886
  else if (isOfType(exception, 'isForbiddenError') &&
882
887
  exception.isForbiddenError) {
883
888
  httpStatusCode = 403;
884
889
  }
885
- else if (data.modelState) {
890
+ else if (data.modelState || exception instanceof EntityError) {
886
891
  httpStatusCode = 400;
887
892
  }
893
+ else if (exception instanceof Error) {
894
+ httpStatusCode = this.defaultErrorStatus;
895
+ }
888
896
  else {
889
897
  httpStatusCode = 400;
890
898
  }
@@ -1,5 +1,7 @@
1
+ import { EntityError, } from './data-interfaces.js';
1
2
  import { RestDataProviderHttpProviderUsingFetch } from './data-providers/rest-data-provider-using-fetch.js';
2
3
  import { isReadPost, retry } from './data-providers/retry.js';
4
+ import { flags } from './remult3/remult3.js';
3
5
  export function buildRestDataProvider(provider) {
4
6
  if (!provider)
5
7
  return new RestDataProviderHttpProviderUsingFetch();
@@ -93,8 +95,6 @@ export async function processHttpException(ex) {
93
95
  if (httpStatusCode !== undefined && httpStatusCode !== null) {
94
96
  error.httpStatusCode = httpStatusCode;
95
97
  }
96
- var result = Object.assign(error ?? {}, {
97
- // exception: ex disabled for now because JSON.stringify crashed with this
98
- });
99
- return result;
98
+ error ??= {};
99
+ return flags.clientErrorsAsEntityError ? new EntityError(error) : error;
100
100
  }
@@ -228,7 +228,7 @@ export class Remult {
228
228
  if (!z.doWork)
229
229
  throw Error('The method received is not a valid backend method');
230
230
  //@ts-ignore
231
- return z.doWork(args, classInstance, this.apiClient.url, buildRestDataProvider(this.apiClient.httpClient));
231
+ return z.doWork(args, classInstance, this);
232
232
  }
233
233
  /* @internal*/
234
234
  liveQuerySubscriber = new LiveQueryClient(() => this.apiClient, () => this.user?.id);
@@ -468,7 +468,7 @@ class FilterConsumerBridgeToObject {
468
468
  }
469
469
  containsCaseInsensitive(col, val) {
470
470
  let v = this.row[this.dbNames.$dbNameOf(col)];
471
- if (!v) {
471
+ if (v === undefined || v === null) {
472
472
  this.ok = false;
473
473
  return;
474
474
  }
@@ -482,7 +482,7 @@ class FilterConsumerBridgeToObject {
482
482
  }
483
483
  notContainsCaseInsensitive(col, val) {
484
484
  let v = this.row[this.dbNames.$dbNameOf(col)];
485
- if (!v) {
485
+ if (v === undefined || v === null) {
486
486
  this.ok = false;
487
487
  return;
488
488
  }
@@ -496,7 +496,7 @@ class FilterConsumerBridgeToObject {
496
496
  }
497
497
  startsWithCaseInsensitive(col, val) {
498
498
  let v = this.row[this.dbNames.$dbNameOf(col)];
499
- if (!v) {
499
+ if (v === undefined || v === null) {
500
500
  this.ok = false;
501
501
  return;
502
502
  }
@@ -510,7 +510,7 @@ class FilterConsumerBridgeToObject {
510
510
  }
511
511
  endsWithCaseInsensitive(col, val) {
512
512
  let v = this.row[this.dbNames.$dbNameOf(col)];
513
- if (!v) {
513
+ if (v === undefined || v === null) {
514
514
  this.ok = false;
515
515
  return;
516
516
  }
@@ -1,3 +1,5 @@
1
+ import { EntityError, } from '../data-interfaces.js';
2
+ import { flags } from '../remult3/remult3.js';
1
3
  import { isReadPost, retry } from './retry.js';
2
4
  export class RestDataProviderHttpProviderUsingFetch {
3
5
  fetch;
@@ -60,19 +62,24 @@ function onSuccess(response) {
60
62
  throw response
61
63
  .json()
62
64
  .then((x) => {
63
- return {
65
+ return fetchError({
64
66
  ...x,
65
67
  message: x.message || response.statusText,
66
68
  url: response.url,
67
69
  status: response.status,
68
- };
70
+ });
69
71
  })
70
72
  .catch(() => {
71
- throw {
73
+ throw fetchError({
72
74
  message: response.statusText,
73
75
  url: response.url,
74
76
  status: response.status,
75
- };
77
+ });
76
78
  });
77
79
  }
78
80
  }
81
+ function fetchError(info) {
82
+ return flags.clientErrorsAsEntityError
83
+ ? new EntityError({ ...info, httpStatusCode: info.status })
84
+ : info;
85
+ }
@@ -13,6 +13,21 @@ export const LIKE_ESCAPE_SQL = " escape '!'";
13
13
  export function escapeLike(val) {
14
14
  return val.replace(REGEX_LIKE_SPECIAL, '!$&');
15
15
  }
16
+ /** `$not` uses `case when` once the predicate mentions a column that allows null. */
17
+ export class HandleNull {
18
+ nullable = false;
19
+ add(other) {
20
+ if (other.nullable)
21
+ this.nullable = true;
22
+ }
23
+ column(col) {
24
+ if (col.allowNull)
25
+ this.nullable = true;
26
+ }
27
+ custom() {
28
+ this.nullable = true;
29
+ }
30
+ }
16
31
  export class FilterConsumerBridgeToSqlRequest {
17
32
  r;
18
33
  nameProvider;
@@ -20,6 +35,7 @@ export class FilterConsumerBridgeToSqlRequest {
20
35
  where = '';
21
36
  _addWhere = true;
22
37
  promises = [];
38
+ handleNull = new HandleNull();
23
39
  async resolveWhere() {
24
40
  while (this.promises.length > 0) {
25
41
  let p = this.promises;
@@ -39,8 +55,9 @@ export class FilterConsumerBridgeToSqlRequest {
39
55
  throw new Error('Custom filter should be translated before it gets here');
40
56
  }
41
57
  or(orElements) {
42
- let statement = '';
43
58
  this.promises.push((async () => {
59
+ let statement = '';
60
+ const branches = new HandleNull();
44
61
  for (const element of orElements) {
45
62
  let f = new FilterConsumerBridgeToSqlRequest(this.r, this.nameProvider, this.jsonColumnStorage);
46
63
  f._addWhere = false;
@@ -49,6 +66,7 @@ export class FilterConsumerBridgeToSqlRequest {
49
66
  if (!where)
50
67
  return; //since if any member of or is empty, then the entire or is irrelevant
51
68
  if (where.length > 0) {
69
+ branches.add(f.handleNull);
52
70
  if (statement.length > 0) {
53
71
  statement += ' or ';
54
72
  }
@@ -59,6 +77,7 @@ export class FilterConsumerBridgeToSqlRequest {
59
77
  statement += where;
60
78
  }
61
79
  }
80
+ this.handleNull.add(branches);
62
81
  this.addToWhere('(' + statement + ')');
63
82
  })());
64
83
  }
@@ -68,18 +87,27 @@ export class FilterConsumerBridgeToSqlRequest {
68
87
  f._addWhere = false;
69
88
  element.__applyToConsumer(f);
70
89
  let where = await f.resolveWhere();
71
- if (!where)
72
- return; //since if any member of or is empty, then the entire or is irrelevant
73
- this.addToWhere('not (' + where + ')');
90
+ // An empty filter matches every row, so its not matches none.
91
+ if (!where) {
92
+ this.addToWhere('1 = 0');
93
+ return;
94
+ }
95
+ this.addToWhere(f.handleNull.nullable
96
+ ? 'case when (' + where + ') then 0 else 1 end = 1'
97
+ : 'not (' + where + ')');
74
98
  })());
75
99
  }
76
100
  isNull(col) {
101
+ this.handleNull.column(col);
77
102
  this.promises.push((async () => this.addToWhere(this.nameProvider.$dbNameOf(col) + ' is null'))());
78
103
  }
79
104
  isNotNull(col) {
105
+ this.handleNull.column(col);
80
106
  this.promises.push((async () => this.addToWhere(this.nameProvider.$dbNameOf(col) + ' is not null'))());
81
107
  }
82
108
  isIn(col, val) {
109
+ if (val?.length)
110
+ this.handleNull.column(col);
83
111
  this.promises.push((async () => {
84
112
  if (val && val.length > 0)
85
113
  this.addToWhere(this.nameProvider.$dbNameOf(col) +
@@ -123,6 +151,7 @@ export class FilterConsumerBridgeToSqlRequest {
123
151
  this.like(col, '%' + escapeLike(val));
124
152
  }
125
153
  like(col, pattern, not = '') {
154
+ this.handleNull.column(col);
126
155
  this.promises.push((async () => {
127
156
  this.addToWhere(not +
128
157
  'lower (' +
@@ -134,6 +163,7 @@ export class FilterConsumerBridgeToSqlRequest {
134
163
  })());
135
164
  }
136
165
  add(col, val, operator) {
166
+ this.handleNull.column(col);
137
167
  this.promises.push((async () => {
138
168
  let x = this.nameProvider.$dbNameOf(col) +
139
169
  ' ' +
@@ -160,6 +190,7 @@ export class FilterConsumerBridgeToSqlRequest {
160
190
  if (typeof sql !== 'string')
161
191
  sql = item.sql;
162
192
  if (sql) {
193
+ this.handleNull.custom();
163
194
  this.addToWhere('(' + sql + ')');
164
195
  }
165
196
  }
@@ -357,15 +357,20 @@ class filterHelper {
357
357
  }
358
358
  isNotIn(values) {
359
359
  return new Filter((add) => {
360
- for (const v of values) {
361
- add.isDifferentFrom(this.metadata, this.processVal(v));
362
- }
360
+ for (const v of values)
361
+ this.isDifferentFrom(v).__applyToConsumer(add);
363
362
  });
364
363
  }
365
364
  isDifferentFrom(val) {
366
365
  val = this.processVal(val);
367
366
  if ((val === null || val === undefined) && this.metadata.allowNull)
368
367
  return new Filter((add) => add.isNotNull(this.metadata));
368
+ // NULL is a value, so it differs from every other value. SQL `<>` does not.
369
+ if (this.metadata.allowNull)
370
+ return new Filter((add) => add.or([
371
+ new Filter((add) => add.isDifferentFrom(this.metadata, val)),
372
+ new Filter((add) => add.isNull(this.metadata)),
373
+ ]));
369
374
  return new Filter((add) => add.isDifferentFrom(this.metadata, val));
370
375
  }
371
376
  isLessOrEqualTo(val) {
@@ -384,6 +389,15 @@ class filterHelper {
384
389
  }
385
390
  isIn(val) {
386
391
  val = val.map((x) => this.processVal(x));
392
+ if (this.metadata.allowNull) {
393
+ const values = val.filter((x) => x !== null && x !== undefined);
394
+ if (values.length !== val.length) {
395
+ const isNull = new Filter((add) => add.isNull(this.metadata));
396
+ if (values.length === 0)
397
+ return isNull;
398
+ return new Filter((add) => add.or([this.isIn(values), isNull]));
399
+ }
400
+ }
387
401
  if (val?.length == 1 && val[0] != undefined && val[0] !== null)
388
402
  return new Filter((add) => add.isEqualTo(this.metadata, val[0]));
389
403
  return new Filter((add) => add.isIn(this.metadata, val));
@@ -660,7 +674,7 @@ export function buildFilterFromRequestParameters(entity, filterInfo) {
660
674
  addFilter('.ne', (val) => ({ $ne: val }));
661
675
  addFilter('.in', (val) => val, true);
662
676
  var nullFilter = filterInfo.get(col.key + '.null');
663
- if (nullFilter) {
677
+ if (nullFilter !== undefined) {
664
678
  nullFilter = nullFilter.toString().trim().toLowerCase();
665
679
  switch (nullFilter) {
666
680
  case 'y':
@@ -150,6 +150,18 @@ export class RemultProxy {
150
150
  .remultFactory()
151
151
  .repo(...args)
152
152
  .findId(a, b),
153
+ findIdOrThrow: (a, b) => self
154
+ .remultFactory()
155
+ .repo(...args)
156
+ .findIdOrThrow(a, b),
157
+ findFirstOrThrow: (...args2) => self
158
+ .remultFactory()
159
+ .repo(...args)
160
+ .findFirstOrThrow(...args2),
161
+ findOneOrThrow: (...args2) => self
162
+ .remultFactory()
163
+ .repo(...args)
164
+ .findOneOrThrow(...args2),
153
165
  //@ts-ignore
154
166
  toJson: (json) => self
155
167
  .remultFactory()
@@ -23,6 +23,7 @@ let x = {
23
23
  nullSort: undefined,
24
24
  defaultIdFactory: undefined,
25
25
  defaultDataProvider: () => undefined,
26
+ backendMethodSerializer: undefined,
26
27
  };
27
28
  if ((typeof process !== 'undefined' &&
28
29
  process.env['IGNORE_GLOBAL_REMULT_IN_TESTS']) ||
@@ -53,6 +53,12 @@ export class RepositoryImplementation {
53
53
  httpStatusCode: 404,
54
54
  };
55
55
  }
56
+ _noMatchError() {
57
+ return {
58
+ message: `no row matches the filter in entity ${this.metadata.key}`,
59
+ httpStatusCode: 404,
60
+ };
61
+ }
56
62
  [getInternalKey]() {
57
63
  return this;
58
64
  }
@@ -1036,6 +1042,24 @@ export class RepositoryImplementation {
1036
1042
  where: this.metadata.idMetadata.getIdFilter(id),
1037
1043
  }, true);
1038
1044
  }
1045
+ async findIdOrThrow(id, options) {
1046
+ const row = await this.findId(id, options);
1047
+ if (!row)
1048
+ throw new EntityError(this._notFoundError(id));
1049
+ return row;
1050
+ }
1051
+ async findFirstOrThrow(where, options) {
1052
+ const row = await this.findFirst(where, options);
1053
+ if (!row)
1054
+ throw new EntityError(this._noMatchError());
1055
+ return row;
1056
+ }
1057
+ async findOneOrThrow(options) {
1058
+ const row = await this.findOne(options);
1059
+ if (!row)
1060
+ throw new EntityError(this._noMatchError());
1061
+ return row;
1062
+ }
1039
1063
  async _translateWhereToFilter(where) {
1040
1064
  let safeWhere = where ?? {};
1041
1065
  if (this._defaultFindOptions?.where) {
@@ -22,6 +22,8 @@ export const flags = {
22
22
  liveQueryKeepAliveMs: 30_000,
23
23
  /** Version poll while SSE is stale */
24
24
  liveQueryPollWhenStaleMs: 1_000,
25
+ /** Client calls reject with an `EntityError` instead of a plain object. On by default in the next major. */
26
+ clientErrorsAsEntityError: false,
25
27
  };
26
28
  /*p1 - issues in https://stackblitz.com/edit/demo-allow-delete-based-on-other-entity:
27
29
  - don't like the ensure schema
@@ -91,9 +91,9 @@ export class myServerAction extends Action {
91
91
  await decideTransaction(remult, this.options, async () => {
92
92
  if (!remult.isAllowedForInstance(undefined, this.options.allowed))
93
93
  throw new ForbiddenError();
94
- info.args = await prepareReceivedArgs(this.types(), info.args, remult, ds, res);
94
+ info.args = await prepareReceivedArgs(this.types(), await fromWire(info.args, remult, this.options, 'args'), remult, ds, res);
95
95
  try {
96
- result.data = await this.originalMethod(info.args);
96
+ result.data = await toWire(await this.originalMethod(info.args), remult, this.options, 'result');
97
97
  }
98
98
  catch (err) {
99
99
  throw err;
@@ -151,13 +151,16 @@ export function BackendMethod(options) {
151
151
  if (target.prototype !== undefined) {
152
152
  // if types are undefined - you've forgot to set: "emitDecoratorMetadata":true
153
153
  let serverAction = new myServerAction((options?.apiPrefix ? options.apiPrefix + '/' : '') + key, () => getTypes(), options, (args) => originalMethod.apply(undefined, args));
154
- serverAction.doWork = async (args, self, url, http) => {
155
- args = prepareArgsToSend(getTypes(), args);
154
+ serverAction.doWork = async (args, self, caller) => {
155
+ const calling = caller ?? remult;
156
+ const url = calling.apiClient.url;
157
+ const http = buildRestDataProvider(calling.apiClient.httpClient);
158
+ const sent = await toWire(prepareArgsToSend(getTypes(), args), calling, options, 'args');
156
159
  if (options.blockUser === false) {
157
- return await remultStatic.actionInfo.runActionWithoutBlockingUI(async () => (await serverAction.run({ args }, url, http)).data);
160
+ return await remultStatic.actionInfo.runActionWithoutBlockingUI(async () => fromWire((await serverAction.run({ args: sent }, url, http)).data, calling, options, 'result'));
158
161
  }
159
162
  else
160
- return (await serverAction.run({ args }, url, http)).data;
163
+ return fromWire((await serverAction.run({ args: sent }, url, http)).data, calling, options, 'result');
161
164
  };
162
165
  result = async function (...args) {
163
166
  if (!isBackend()) {
@@ -194,10 +197,10 @@ export function BackendMethod(options) {
194
197
  '/' +
195
198
  (options?.apiPrefix ? options.apiPrefix + '/' : '') +
196
199
  key, options ? (options.queue ?? false) : false, options.allowed, async (d, req, res) => {
197
- d.args = d.args.map((x) => (isCustomUndefined(x) ? undefined : x));
198
200
  let allowed = options.allowed;
199
201
  try {
200
202
  let remult = req;
203
+ d.args = (await fromWire(d.args, remult, options, 'args')).map((x) => (isCustomUndefined(x) ? undefined : x));
201
204
  let r;
202
205
  await decideTransaction(remult, options, async () => {
203
206
  d.args = await prepareReceivedArgs(getTypes(), d.args, remult, remult.dataProvider, res);
@@ -217,8 +220,13 @@ export function BackendMethod(options) {
217
220
  $and: [repo.metadata.options.apiPrefilter ?? {}],
218
221
  },
219
222
  });
223
+ // The client sent a stale row id, so this is a 400 even when
224
+ // defaultErrorStatus is 500.
220
225
  if (rows.length != 1)
221
- throw new Error('not found or too many matches');
226
+ throw {
227
+ message: 'not found or too many matches',
228
+ httpStatusCode: 400,
229
+ };
222
230
  y = rows[0];
223
231
  await repo.getEntityRef(y)._updateEntityBasedOnApi(rowInfo.data);
224
232
  }
@@ -228,7 +236,7 @@ export function BackendMethod(options) {
228
236
  await defs.__validateEntity();
229
237
  try {
230
238
  r = {
231
- result: await originalMethod.apply(y, d.args),
239
+ result: await toWire(await originalMethod.apply(y, d.args), remult, options, 'result'),
232
240
  rowInfo: {
233
241
  data: await defs.toApiJson(),
234
242
  isNewRow: defs.isNew(),
@@ -250,7 +258,7 @@ export function BackendMethod(options) {
250
258
  await controllerRef.__validateEntity();
251
259
  try {
252
260
  r = {
253
- result: await originalMethod.apply(y, d.args),
261
+ result: await toWire(await originalMethod.apply(y, d.args), remult, options, 'result'),
254
262
  fields: await controllerRef.toApiJson(),
255
263
  };
256
264
  }
@@ -271,8 +279,11 @@ export function BackendMethod(options) {
271
279
  });
272
280
  }
273
281
  },
274
- doWork: async function (args, self, baseUrl, http) {
275
- args = prepareArgsToSend(getTypes(), args);
282
+ doWork: async function (args, self, caller) {
283
+ const calling = caller ?? remult;
284
+ const baseUrl = calling.apiClient.url;
285
+ const http = buildRestDataProvider(calling.apiClient.httpClient);
286
+ args = await toWire(prepareArgsToSend(getTypes(), args), calling, options, 'args');
276
287
  if (remultStatic.allEntities.includes(target.constructor)) {
277
288
  let defs = getEntityRef(self);
278
289
  await defs.__validateEntity();
@@ -296,7 +307,7 @@ export function BackendMethod(options) {
296
307
  },
297
308
  }, baseUrl, http);
298
309
  await defs._updateResultsFromServerAction(r.rowInfo);
299
- return r.result;
310
+ return fromWire(r.result, calling, options, 'result');
300
311
  }
301
312
  catch (err) {
302
313
  throw defs.catchSaveErrors(err);
@@ -316,7 +327,7 @@ export function BackendMethod(options) {
316
327
  fields: await defs.toApiJson(),
317
328
  }, baseUrl, http);
318
329
  await defs._updateEntityBasedOnApi(r.fields);
319
- return r.result;
330
+ return fromWire(r.result, calling, options, 'result');
320
331
  }
321
332
  catch (e) {
322
333
  throw defs.catchSaveErrors(e);
@@ -343,6 +354,12 @@ export function BackendMethod(options) {
343
354
  return result;
344
355
  };
345
356
  }
357
+ Object.defineProperty(BackendMethod, 'serializer', {
358
+ get: () => remultStatic.backendMethodSerializer,
359
+ set: (value) => {
360
+ remultStatic.backendMethodSerializer = value;
361
+ },
362
+ });
346
363
  const customUndefined = {
347
364
  _isUndefined: true,
348
365
  };
@@ -354,6 +371,18 @@ function registerAction(target, resultMethod) {
354
371
  function isCustomUndefined(x) {
355
372
  return x && x._isUndefined;
356
373
  }
374
+ async function toWire(value, remult, options, part) {
375
+ const serializer = remultStatic.backendMethodSerializer;
376
+ return serializer
377
+ ? serializer[part].serialize(value, { remult, options })
378
+ : value;
379
+ }
380
+ async function fromWire(value, remult, options, part) {
381
+ const serializer = remultStatic.backendMethodSerializer;
382
+ return serializer
383
+ ? serializer[part].deserialize(value, { remult, options })
384
+ : value;
385
+ }
357
386
  export class ProgressListener {
358
387
  res;
359
388
  constructor(res) {