remult 0.25.8-exp.8 → 0.25.8-exp.9

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.
@@ -6,5 +6,80 @@ export function initAsyncHooks() {
6
6
  if (init)
7
7
  return;
8
8
  init = true;
9
- remultStatic.asyncContext = new RemultAsyncLocalStorage(new AsyncLocalStorage());
9
+ remultStatic.asyncContext = new RemultAsyncLocalStorage(new AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore());
10
+ let test = new AsyncLocalStorage();
11
+ test.run(1, async () => {
12
+ await Promise.resolve();
13
+ if (test.getStore() === undefined) {
14
+ console.log("async_hooks.AsyncLocalStorage not working, using sequential implementation (You're probably running on stackblitz, this will work on a normal nodejs environment");
15
+ remultStatic.asyncContext = new RemultAsyncLocalStorage(new SequentialRemultAsyncLocalStorageCore());
16
+ }
17
+ });
18
+ }
19
+ export class AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl {
20
+ asyncLocalStorage = new AsyncLocalStorage();
21
+ wasImplemented;
22
+ run(store, callback) {
23
+ let r;
24
+ this.asyncLocalStorage.run(store, () => {
25
+ r = new Promise(async (res, rej) => {
26
+ try {
27
+ res(await callback());
28
+ }
29
+ catch (err) {
30
+ rej(err);
31
+ }
32
+ });
33
+ });
34
+ return r;
35
+ }
36
+ getStore() {
37
+ return this.asyncLocalStorage.getStore();
38
+ }
39
+ }
40
+ const ignoreInStack = ["AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore.run", "RemultAsyncLocalStorage.run", "Module.withRemult", "RemultServerImplementation.runWithRemult"];
41
+ export class SequentialRemultAsyncLocalStorageCore {
42
+ wasImplemented;
43
+ async run(store, callback) {
44
+ let log = (msg) => {
45
+ console.log(msg);
46
+ };
47
+ if (false) {
48
+ let stack = new Error().stack;
49
+ let y = stack.split('\n');
50
+ while (y.length > 0 && (y[0].trim().startsWith("Error") || ignoreInStack.includes(y[0].trim().split(' ')[1]))) {
51
+ y.splice(0, 1);
52
+ }
53
+ stack = y.join('\n');
54
+ log = (msg) => {
55
+ console.log(msg, stack);
56
+ };
57
+ }
58
+ log('waiting on ');
59
+ const nextPromise = this.lastPromise.then(async () => {
60
+ log('executing ');
61
+ const previousValue = this.currentValue;
62
+ this.currentValue = store;
63
+ const result = await callback();
64
+ this.currentValue = previousValue;
65
+ return result;
66
+ });
67
+ this.lastPromise = nextPromise.catch(() => {
68
+ log("Error on ");
69
+ return undefined;
70
+ });
71
+ try {
72
+ return await nextPromise;
73
+ }
74
+ finally {
75
+ log('completed ');
76
+ }
77
+ }
78
+ getStore() {
79
+ return this.currentValue;
80
+ }
81
+ lastPromise = Promise.resolve(undefined);
82
+ currentValue;
83
+ }
84
+ export class AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore extends AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl {
10
85
  }
@@ -24,11 +24,12 @@ export class RemultAsyncLocalStorage {
24
24
  constructor(remultObjectStorage) {
25
25
  this.remultObjectStorage = remultObjectStorage;
26
26
  }
27
- run(remult, callback) {
28
- if (this.remultObjectStorage)
29
- this.remultObjectStorage.run(remult, () => callback(remult));
27
+ async run(remult, callback) {
28
+ if (this.remultObjectStorage) {
29
+ return this.remultObjectStorage.run(remult, () => callback(remult));
30
+ }
30
31
  else
31
- callback(remult);
32
+ return callback(remult);
32
33
  }
33
34
  getRemult() {
34
35
  if (!this.remultObjectStorage) {
@@ -285,16 +286,5 @@ export function withRemult(callback, options) {
285
286
  const remult = new Remult();
286
287
  if (options?.dataProvider)
287
288
  remult.dataProvider = options.dataProvider;
288
- let r;
289
- remultStatic.asyncContext.run(remult, () => {
290
- r = new Promise(async (res, rej) => {
291
- try {
292
- res(await callback(remult));
293
- }
294
- catch (err) {
295
- rej(err);
296
- }
297
- });
298
- });
299
- return r;
289
+ return remultStatic.asyncContext.run(remult, r => callback(r));
300
290
  }
@@ -2,10 +2,13 @@ import { createId } from '@paralleldrive/cuid2';
2
2
  import { v4 as uuid } from 'uuid';
3
3
  import { ValueConverters } from '../valueConverters.js';
4
4
  import { buildOptions } from './RepositoryImplementation.js';
5
- import { Validators } from '../validators.js';
5
+ import { Validators, createValueValidator, getEnumValues } from '../validators.js';
6
6
  import { relationInfoMemberInOptions } from './relationInfoMember.js';
7
7
  import { remultStatic } from '../remult-static.js';
8
- import { addValidatorKey } from './addValidatorKey.js';
8
+ import { addValidator } from './addValidator.js';
9
+ const validateNumber = createValueValidator((x) => {
10
+ return !isNaN(x) && isFinite(x);
11
+ });
9
12
  export class Fields {
10
13
  /**
11
14
  * Stored as a JSON.stringify - to store as json use Fields.json
@@ -35,6 +38,7 @@ export class Fields {
35
38
  static integer(...options) {
36
39
  return Field(() => Number, {
37
40
  valueConverter: ValueConverters.Integer,
41
+ validate: validateNumber,
38
42
  }, ...options);
39
43
  }
40
44
  static autoIncrement(...options) {
@@ -48,7 +52,9 @@ export class Fields {
48
52
  }, ...options);
49
53
  }
50
54
  static number(...options) {
51
- return Field(() => Number, ...options);
55
+ return Field(() => Number, {
56
+ validate: validateNumber,
57
+ }, ...options);
52
58
  }
53
59
  static createdAt(...options) {
54
60
  return Field(() => Date, {
@@ -123,8 +129,7 @@ export class Fields {
123
129
  */
124
130
  static literal(optionalValues, ...options) {
125
131
  return Fields.string({
126
- //@ts-ignore
127
- [addValidatorKey]: (entity, event) => Validators.in(optionalValues())(entity, event)
132
+ validate: (entity, event) => Validators.in(optionalValues())(entity, event)
128
133
  }, ...options);
129
134
  }
130
135
  static enum(enumType, ...options) {
@@ -132,12 +137,11 @@ export class Fields {
132
137
  return Field(() =>
133
138
  //@ts-ignore
134
139
  enumType(), {
135
- [addValidatorKey]: (entity, event) => Validators.enum(enumType())(entity, event)
140
+ validate: (entity, event) => Validators.enum(enumType())(entity, event)
136
141
  }, ...options, (options) => {
137
142
  if (valueConverter === undefined) {
138
143
  let enumObj = enumType();
139
- let enumValues = Object.values(enumObj)
140
- .filter((x) => typeof enumObj[x] !== 'number');
144
+ let enumValues = getEnumValues(enumObj);
141
145
  valueConverter = enumValues.find(x => typeof x === "string") ? ValueConverters.String : ValueConverters.Integer;
142
146
  }
143
147
  if (!options.valueConverter) {
@@ -249,10 +253,7 @@ export function Field(valueType, ...options) {
249
253
  let factory = (remult) => {
250
254
  let r = buildOptions(options, remult);
251
255
  if (r.required) {
252
- r.validate = addValidator(r.validate, Validators.required);
253
- }
254
- if (r[addValidatorKey]) {
255
- r.validate = addValidator(r.validate, r[addValidatorKey]);
256
+ r.validate = addValidator(r.validate, Validators.required, true);
256
257
  }
257
258
  if (r.maxLength) {
258
259
  r.validate = addValidator(r.validate, Validators.maxLength(r.maxLength));
@@ -306,18 +307,3 @@ export function checkTarget(target) {
306
307
  if (!target)
307
308
  throw new Error("Set the 'experimentalDecorators:true' option in your 'tsconfig' or 'jsconfig' (target undefined)");
308
309
  }
309
- function addValidator(validators, newValidator, atStart = false) {
310
- if (!newValidator)
311
- return;
312
- const newValidators = Array.isArray(newValidator)
313
- ? newValidator
314
- : [newValidator];
315
- const validatorsArray = Array.isArray(validators)
316
- ? validators
317
- : validators
318
- ? [validators]
319
- : [];
320
- return atStart
321
- ? [...newValidators, ...validatorsArray]
322
- : [...validatorsArray, ...newValidators];
323
- }
@@ -15,6 +15,7 @@ import { getInternalKey, } from './repository-internals.js';
15
15
  import { entityDbName, fieldDbName, } from '../filter/filter-consumer-bridge-to-sql-request.js';
16
16
  import { remultStatic } from '../remult-static.js';
17
17
  import { Validators } from '../validators.js';
18
+ import { addValidator } from './addValidator.js';
18
19
  //import { remult } from "../remult-proxy";
19
20
  let classValidatorValidate = undefined;
20
21
  // import ("class-validator".toString())
@@ -2074,8 +2075,11 @@ export function buildOptions(options, remult) {
2074
2075
  if (o) {
2075
2076
  if (typeof o === 'function')
2076
2077
  o(r, remult);
2077
- else
2078
- Object.assign(r, o);
2078
+ else {
2079
+ const { validate, ...otherOptions } = o;
2080
+ r.validate = addValidator(r.validate, validate);
2081
+ Object.assign(r, otherOptions);
2082
+ }
2079
2083
  }
2080
2084
  }
2081
2085
  return r;
@@ -2084,10 +2088,7 @@ export function decorateColumnSettings(settings, remult) {
2084
2088
  if (settings.valueType) {
2085
2089
  let settingsOnTypeLevel = settings.valueType[storableMember];
2086
2090
  if (settingsOnTypeLevel) {
2087
- settings = {
2088
- ...buildOptions(settingsOnTypeLevel, remult),
2089
- ...settings,
2090
- };
2091
+ settings = buildOptions([...settingsOnTypeLevel, settings], remult);
2091
2092
  }
2092
2093
  }
2093
2094
  if (settings.valueType == String) {
@@ -0,0 +1,15 @@
1
+ export function addValidator(validators, newValidator, atStart = false) {
2
+ if (!newValidator)
3
+ return validators;
4
+ const newValidators = Array.isArray(newValidator)
5
+ ? newValidator
6
+ : [newValidator];
7
+ const validatorsArray = Array.isArray(validators)
8
+ ? validators
9
+ : validators
10
+ ? [validators]
11
+ : [];
12
+ return atStart
13
+ ? [...newValidators, ...validatorsArray]
14
+ : [...validatorsArray, ...newValidators];
15
+ }
@@ -1,12 +1,12 @@
1
1
  export {};
2
2
  //p1 - `preprocessApiFindOptions`, naming - allow find options preprocessor for api calls, to use for authorization
3
3
  //p1 - admin url1 - pocketbase use /_ for the admin //{allowed?:Allowed,url?:string}
4
- //p1 - Validate for NAN
5
4
  //p1 - Make async hooks gracefully handle non async hooks environment
6
- //p1 - chain validators with options
5
+ //p1 - implement generic sqlite support better-sqlite3/ bun sqlite
6
+ //p1 - article auth.js with express
7
+ //p1 - document offline support
7
8
  //y2 - should we validate relations
8
9
  //y1 - consider replacing all errors with error classes that extend the base Error class
9
- //y2 - consider if field types should include validation in them by default (string,number that it's not NaN etc...) and if so, what message?
10
10
  //y2 - should enforce integer - currently we probably round / truncate it
11
11
  /*y1 - talk about modules in init express with entities/controllers,initRequest,initApi
12
12
  - support get with backend method, with url search params as the first parameter, & url as second parameter
@@ -14,8 +14,6 @@ export {};
14
14
 
15
15
  */
16
16
  //p1 - in this video I'll use remult to turn a frontend app to a fullstack app
17
- //y1 - getFields didn't work for kobi in the home component
18
- //p1 - document offline support
19
17
  /*y1 - Talk JYC - JYC - add some integrity checks on delete
20
18
  - soft delete
21
19
  - delete restrict (implicit, or user selected - and if so, how) (delete & update of id)
@@ -28,8 +28,7 @@ export class Validators {
28
28
  static url = createValueValidator((val) => !!new URL(val), 'Invalid Url');
29
29
  static in = createValueValidatorWithArgs((val, values) => values.includes(val), (values) => `Value must be one of ${values.map(y => typeof y === "object" ? y['id'] !== undefined ? y['id'] : y.toString() : y).join(', ')}`);
30
30
  static notNull = createValueValidator((val) => val != null, 'Should not be null');
31
- static enum = createValueValidatorWithArgs((value, enumObj) => Object.values(enumObj).includes(value), (enumObj) => `Value must be one of ${Object.values(enumObj)
32
- .filter((x) => typeof enumObj[x] !== 'number')
31
+ static enum = createValueValidatorWithArgs((value, enumObj) => Object.values(enumObj).includes(value), (enumObj) => `Value must be one of ${getEnumValues(enumObj)
33
32
  .join(', ')}`);
34
33
  static relationExists = createValidator(async (_, e) => {
35
34
  if (e.valueIsNull())
@@ -134,3 +133,7 @@ function createValidatorWithArgsInternal(validate, defaultMessage, isValueValida
134
133
  },
135
134
  });
136
135
  }
136
+ export function getEnumValues(enumObj) {
137
+ return Object.values(enumObj)
138
+ .filter((x) => typeof enumObj[x] !== 'number');
139
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remult",
3
- "version": "0.25.8-exp.8",
3
+ "version": "0.25.8-exp.9",
4
4
  "description": "A CRUD framework for full-stack TypeScript",
5
5
  "homepage": "https://remult.dev",
6
6
  "repository": {
@@ -1 +1,17 @@
1
+ import { type RemultAsyncLocalStorageCore } from '../src/context.js';
1
2
  export declare function initAsyncHooks(): void;
3
+ export declare class AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl<T> implements RemultAsyncLocalStorageCore<T> {
4
+ private asyncLocalStorage;
5
+ wasImplemented: 'yes';
6
+ run<R>(store: T, callback: () => Promise<R>): Promise<R>;
7
+ getStore(): T;
8
+ }
9
+ export declare class SequentialRemultAsyncLocalStorageCore<T> implements RemultAsyncLocalStorageCore<T> {
10
+ wasImplemented: 'yes';
11
+ run<R>(store: T, callback: () => Promise<R>): Promise<R>;
12
+ getStore(): T;
13
+ lastPromise: Promise<T>;
14
+ currentValue: T;
15
+ }
16
+ export declare class AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore<T> extends AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl<T> {
17
+ }
@@ -1,14 +1,141 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.initAsyncHooks = void 0;
3
+ exports.AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore = exports.SequentialRemultAsyncLocalStorageCore = exports.AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl = exports.initAsyncHooks = void 0;
4
+ var tslib_1 = require("tslib");
4
5
  var async_hooks_1 = require("async_hooks");
5
6
  var context_js_1 = require("../src/context.js");
6
7
  var remult_static_js_1 = require("../src/remult-static.js");
7
8
  var init = false;
8
9
  function initAsyncHooks() {
10
+ var _this = this;
9
11
  if (init)
10
12
  return;
11
13
  init = true;
12
- remult_static_js_1.remultStatic.asyncContext = new context_js_1.RemultAsyncLocalStorage(new async_hooks_1.AsyncLocalStorage());
14
+ remult_static_js_1.remultStatic.asyncContext = new context_js_1.RemultAsyncLocalStorage(new AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore());
15
+ var test = new async_hooks_1.AsyncLocalStorage();
16
+ test.run(1, function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
17
+ return tslib_1.__generator(this, function (_a) {
18
+ switch (_a.label) {
19
+ case 0: return [4 /*yield*/, Promise.resolve()];
20
+ case 1:
21
+ _a.sent();
22
+ if (test.getStore() === undefined) {
23
+ console.log("async_hooks.AsyncLocalStorage not working, using sequential implementation (You're probably running on stackblitz, this will work on a normal nodejs environment");
24
+ remult_static_js_1.remultStatic.asyncContext = new context_js_1.RemultAsyncLocalStorage(new SequentialRemultAsyncLocalStorageCore());
25
+ }
26
+ return [2 /*return*/];
27
+ }
28
+ });
29
+ }); });
13
30
  }
14
31
  exports.initAsyncHooks = initAsyncHooks;
32
+ var AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl = /** @class */ (function () {
33
+ function AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl() {
34
+ this.asyncLocalStorage = new async_hooks_1.AsyncLocalStorage();
35
+ }
36
+ AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl.prototype.run = function (store, callback) {
37
+ var _this = this;
38
+ var r;
39
+ this.asyncLocalStorage.run(store, function () {
40
+ r = new Promise(function (res, rej) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
41
+ var _a, err_1;
42
+ return tslib_1.__generator(this, function (_b) {
43
+ switch (_b.label) {
44
+ case 0:
45
+ _b.trys.push([0, 2, , 3]);
46
+ _a = res;
47
+ return [4 /*yield*/, callback()];
48
+ case 1:
49
+ _a.apply(void 0, [_b.sent()]);
50
+ return [3 /*break*/, 3];
51
+ case 2:
52
+ err_1 = _b.sent();
53
+ rej(err_1);
54
+ return [3 /*break*/, 3];
55
+ case 3: return [2 /*return*/];
56
+ }
57
+ });
58
+ }); });
59
+ });
60
+ return r;
61
+ };
62
+ AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl.prototype.getStore = function () {
63
+ return this.asyncLocalStorage.getStore();
64
+ };
65
+ return AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl;
66
+ }());
67
+ exports.AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl = AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl;
68
+ var ignoreInStack = ["AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore.run", "RemultAsyncLocalStorage.run", "Module.withRemult", "RemultServerImplementation.runWithRemult"];
69
+ var SequentialRemultAsyncLocalStorageCore = /** @class */ (function () {
70
+ function SequentialRemultAsyncLocalStorageCore() {
71
+ this.lastPromise = Promise.resolve(undefined);
72
+ }
73
+ SequentialRemultAsyncLocalStorageCore.prototype.run = function (store, callback) {
74
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
75
+ var log, stack_1, y, nextPromise;
76
+ var _this = this;
77
+ return tslib_1.__generator(this, function (_a) {
78
+ switch (_a.label) {
79
+ case 0:
80
+ log = function (msg) {
81
+ console.log(msg);
82
+ };
83
+ if (false) {
84
+ stack_1 = new Error().stack;
85
+ y = stack_1.split('\n');
86
+ while (y.length > 0 && (y[0].trim().startsWith("Error") || ignoreInStack.includes(y[0].trim().split(' ')[1]))) {
87
+ y.splice(0, 1);
88
+ }
89
+ stack_1 = y.join('\n');
90
+ log = function (msg) {
91
+ console.log(msg, stack_1);
92
+ };
93
+ }
94
+ log('waiting on ');
95
+ nextPromise = this.lastPromise.then(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
96
+ var previousValue, result;
97
+ return tslib_1.__generator(this, function (_a) {
98
+ switch (_a.label) {
99
+ case 0:
100
+ log('executing ');
101
+ previousValue = this.currentValue;
102
+ this.currentValue = store;
103
+ return [4 /*yield*/, callback()];
104
+ case 1:
105
+ result = _a.sent();
106
+ this.currentValue = previousValue;
107
+ return [2 /*return*/, result];
108
+ }
109
+ });
110
+ }); });
111
+ this.lastPromise = nextPromise.catch(function () {
112
+ log("Error on ");
113
+ return undefined;
114
+ });
115
+ _a.label = 1;
116
+ case 1:
117
+ _a.trys.push([1, , 3, 4]);
118
+ return [4 /*yield*/, nextPromise];
119
+ case 2: return [2 /*return*/, _a.sent()];
120
+ case 3:
121
+ log('completed ');
122
+ return [7 /*endfinally*/];
123
+ case 4: return [2 /*return*/];
124
+ }
125
+ });
126
+ });
127
+ };
128
+ SequentialRemultAsyncLocalStorageCore.prototype.getStore = function () {
129
+ return this.currentValue;
130
+ };
131
+ return SequentialRemultAsyncLocalStorageCore;
132
+ }());
133
+ exports.SequentialRemultAsyncLocalStorageCore = SequentialRemultAsyncLocalStorageCore;
134
+ var AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore = /** @class */ (function (_super) {
135
+ tslib_1.__extends(AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore, _super);
136
+ function AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore() {
137
+ return _super !== null && _super.apply(this, arguments) || this;
138
+ }
139
+ return AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore;
140
+ }(AsyncLocalStorageBridgeToRemultAsyncLocalStorageCoreImpl));
141
+ exports.AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore = AsyncLocalStorageBridgeToRemultAsyncLocalStorageCore;
package/src/context.d.ts CHANGED
@@ -8,13 +8,14 @@ export declare class RemultAsyncLocalStorage {
8
8
  private readonly remultObjectStorage;
9
9
  static enable(): void;
10
10
  static disable(): void;
11
- constructor(remultObjectStorage: myAsyncLocalStorage<Remult>);
12
- run(remult: Remult, callback: (remult: Remult) => void): void;
11
+ constructor(remultObjectStorage: RemultAsyncLocalStorageCore<Remult>);
12
+ run<T>(remult: Remult, callback: (remult: Remult) => Promise<T>): Promise<T>;
13
13
  getRemult(): Remult;
14
14
  }
15
- type myAsyncLocalStorage<T> = {
16
- run<R>(store: T, callback: (...args: any[]) => R, ...args: any[]): R;
15
+ export type RemultAsyncLocalStorageCore<T> = {
16
+ run<R>(store: T, callback: () => Promise<R>): Promise<R>;
17
17
  getStore(): T | undefined;
18
+ wasImplemented: 'yes';
18
19
  };
19
20
  export declare function isBackend(): boolean;
20
21
  export declare class Remult {
@@ -189,4 +190,3 @@ export declare function doTransaction(remult: Remult, what: (dp: DataProvider) =
189
190
  export declare function withRemult<T>(callback: (remult: any) => Promise<T>, options?: {
190
191
  dataProvider?: DataProvider;
191
192
  }): Promise<T>;
192
- export {};
package/src/context.js CHANGED
@@ -28,10 +28,16 @@ var RemultAsyncLocalStorage = /** @class */ (function () {
28
28
  (0, remult_static_js_1.resetFactory)();
29
29
  };
30
30
  RemultAsyncLocalStorage.prototype.run = function (remult, callback) {
31
- if (this.remultObjectStorage)
32
- this.remultObjectStorage.run(remult, function () { return callback(remult); });
33
- else
34
- callback(remult);
31
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
32
+ return tslib_1.__generator(this, function (_a) {
33
+ if (this.remultObjectStorage) {
34
+ return [2 /*return*/, this.remultObjectStorage.run(remult, function () { return callback(remult); })];
35
+ }
36
+ else
37
+ return [2 /*return*/, callback(remult)];
38
+ return [2 /*return*/];
39
+ });
40
+ });
35
41
  };
36
42
  RemultAsyncLocalStorage.prototype.getRemult = function () {
37
43
  if (!this.remultObjectStorage) {
@@ -449,32 +455,9 @@ var transactionLiveQueryPublisher = /** @class */ (function () {
449
455
  return transactionLiveQueryPublisher;
450
456
  }());
451
457
  function withRemult(callback, options) {
452
- var _this = this;
453
458
  var remult = new Remult();
454
459
  if (options === null || options === void 0 ? void 0 : options.dataProvider)
455
460
  remult.dataProvider = options.dataProvider;
456
- var r;
457
- remult_static_js_1.remultStatic.asyncContext.run(remult, function () {
458
- r = new Promise(function (res, rej) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
459
- var _a, err_1;
460
- return tslib_1.__generator(this, function (_b) {
461
- switch (_b.label) {
462
- case 0:
463
- _b.trys.push([0, 2, , 3]);
464
- _a = res;
465
- return [4 /*yield*/, callback(remult)];
466
- case 1:
467
- _a.apply(void 0, [_b.sent()]);
468
- return [3 /*break*/, 3];
469
- case 2:
470
- err_1 = _b.sent();
471
- rej(err_1);
472
- return [3 /*break*/, 3];
473
- case 3: return [2 /*return*/];
474
- }
475
- });
476
- }); });
477
- });
478
- return r;
461
+ return remult_static_js_1.remultStatic.asyncContext.run(remult, function (r) { return callback(r); });
479
462
  }
480
463
  exports.withRemult = withRemult;
@@ -9,7 +9,10 @@ var RepositoryImplementation_js_1 = require("./RepositoryImplementation.js");
9
9
  var validators_js_1 = require("../validators.js");
10
10
  var relationInfoMember_js_1 = require("./relationInfoMember.js");
11
11
  var remult_static_js_1 = require("../remult-static.js");
12
- var addValidatorKey_js_1 = require("./addValidatorKey.js");
12
+ var addValidator_js_1 = require("./addValidator.js");
13
+ var validateNumber = (0, validators_js_1.createValueValidator)(function (x) {
14
+ return !isNaN(x) && isFinite(x);
15
+ });
13
16
  var Fields = /** @class */ (function () {
14
17
  function Fields() {
15
18
  }
@@ -64,6 +67,7 @@ var Fields = /** @class */ (function () {
64
67
  return Field.apply(void 0, tslib_1.__spreadArray([function () { return Number; },
65
68
  {
66
69
  valueConverter: valueConverters_js_1.ValueConverters.Integer,
70
+ validate: validateNumber,
67
71
  }], tslib_1.__read(options), false));
68
72
  };
69
73
  Fields.autoIncrement = function () {
@@ -83,7 +87,9 @@ var Fields = /** @class */ (function () {
83
87
  for (var _i = 0; _i < arguments.length; _i++) {
84
88
  options[_i] = arguments[_i];
85
89
  }
86
- return Field.apply(void 0, tslib_1.__spreadArray([function () { return Number; }], tslib_1.__read(options), false));
90
+ return Field.apply(void 0, tslib_1.__spreadArray([function () { return Number; }, {
91
+ validate: validateNumber,
92
+ }], tslib_1.__read(options), false));
87
93
  };
88
94
  Fields.createdAt = function () {
89
95
  var options = [];
@@ -178,18 +184,15 @@ var Fields = /** @class */ (function () {
178
184
  * // This approach allows easy management and updates of the allowed values for the `status` field.
179
185
  */
180
186
  Fields.literal = function (optionalValues) {
181
- var _a;
182
187
  var options = [];
183
188
  for (var _i = 1; _i < arguments.length; _i++) {
184
189
  options[_i - 1] = arguments[_i];
185
190
  }
186
- return Fields.string.apply(Fields, tslib_1.__spreadArray([(_a = {},
187
- //@ts-ignore
188
- _a[addValidatorKey_js_1.addValidatorKey] = function (entity, event) { return validators_js_1.Validators.in(optionalValues())(entity, event); },
189
- _a)], tslib_1.__read(options), false));
191
+ return Fields.string.apply(Fields, tslib_1.__spreadArray([{
192
+ validate: function (entity, event) { return validators_js_1.Validators.in(optionalValues())(entity, event); }
193
+ }], tslib_1.__read(options), false));
190
194
  };
191
195
  Fields.enum = function (enumType) {
192
- var _a;
193
196
  var options = [];
194
197
  for (var _i = 1; _i < arguments.length; _i++) {
195
198
  options[_i - 1] = arguments[_i];
@@ -198,13 +201,13 @@ var Fields = /** @class */ (function () {
198
201
  return Field.apply(void 0, tslib_1.__spreadArray(tslib_1.__spreadArray([function () {
199
202
  //@ts-ignore
200
203
  return (enumType());
201
- }, (_a = {},
202
- _a[addValidatorKey_js_1.addValidatorKey] = function (entity, event) { return validators_js_1.Validators.enum(enumType())(entity, event); },
203
- _a)], tslib_1.__read(options), false), [function (options) {
204
+ },
205
+ {
206
+ validate: function (entity, event) { return validators_js_1.Validators.enum(enumType())(entity, event); }
207
+ }], tslib_1.__read(options), false), [function (options) {
204
208
  if (valueConverter === undefined) {
205
- var enumObj_1 = enumType();
206
- var enumValues = Object.values(enumObj_1)
207
- .filter(function (x) { return typeof enumObj_1[x] !== 'number'; });
209
+ var enumObj = enumType();
210
+ var enumValues = (0, validators_js_1.getEnumValues)(enumObj);
208
211
  valueConverter = enumValues.find(function (x) { return typeof x === "string"; }) ? valueConverters_js_1.ValueConverters.String : valueConverters_js_1.ValueConverters.Integer;
209
212
  }
210
213
  if (!options.valueConverter) {
@@ -323,16 +326,13 @@ function Field(valueType) {
323
326
  var factory = function (remult) {
324
327
  var r = (0, RepositoryImplementation_js_1.buildOptions)(options, remult);
325
328
  if (r.required) {
326
- r.validate = addValidator(r.validate, validators_js_1.Validators.required);
327
- }
328
- if (r[addValidatorKey_js_1.addValidatorKey]) {
329
- r.validate = addValidator(r.validate, r[addValidatorKey_js_1.addValidatorKey]);
329
+ r.validate = (0, addValidator_js_1.addValidator)(r.validate, validators_js_1.Validators.required, true);
330
330
  }
331
331
  if (r.maxLength) {
332
- r.validate = addValidator(r.validate, validators_js_1.Validators.maxLength(r.maxLength));
332
+ r.validate = (0, addValidator_js_1.addValidator)(r.validate, validators_js_1.Validators.maxLength(r.maxLength));
333
333
  }
334
334
  if (r.minLength) {
335
- r.validate = addValidator(r.validate, validators_js_1.Validators.minLength(r.minLength));
335
+ r.validate = (0, addValidator_js_1.addValidator)(r.validate, validators_js_1.Validators.minLength(r.minLength));
336
336
  }
337
337
  if (!r.valueType && valueType) {
338
338
  r.valueType = valueType();
@@ -382,18 +382,3 @@ function checkTarget(target) {
382
382
  throw new Error("Set the 'experimentalDecorators:true' option in your 'tsconfig' or 'jsconfig' (target undefined)");
383
383
  }
384
384
  exports.checkTarget = checkTarget;
385
- function addValidator(validators, newValidator, atStart) {
386
- if (atStart === void 0) { atStart = false; }
387
- if (!newValidator)
388
- return;
389
- var newValidators = Array.isArray(newValidator)
390
- ? newValidator
391
- : [newValidator];
392
- var validatorsArray = Array.isArray(validators)
393
- ? validators
394
- : validators
395
- ? [validators]
396
- : [];
397
- return atStart
398
- ? tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(newValidators), false), tslib_1.__read(validatorsArray), false) : tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(validatorsArray), false), tslib_1.__read(newValidators), false);
399
- }
@@ -19,6 +19,7 @@ var repository_internals_js_1 = require("./repository-internals.js");
19
19
  var filter_consumer_bridge_to_sql_request_js_1 = require("../filter/filter-consumer-bridge-to-sql-request.js");
20
20
  var remult_static_js_1 = require("../remult-static.js");
21
21
  var validators_js_1 = require("../validators.js");
22
+ var addValidator_js_1 = require("./addValidator.js");
22
23
  //import { remult } from "../remult-proxy";
23
24
  var classValidatorValidate = undefined;
24
25
  // import ("class-validator".toString())
@@ -3379,8 +3380,11 @@ function buildOptions(options, remult) {
3379
3380
  if (o) {
3380
3381
  if (typeof o === 'function')
3381
3382
  o(r, remult);
3382
- else
3383
- Object.assign(r, o);
3383
+ else {
3384
+ var validate = o.validate, otherOptions = tslib_1.__rest(o, ["validate"]);
3385
+ r.validate = (0, addValidator_js_1.addValidator)(r.validate, validate);
3386
+ Object.assign(r, otherOptions);
3387
+ }
3384
3388
  }
3385
3389
  }
3386
3390
  }
@@ -3398,7 +3402,7 @@ function decorateColumnSettings(settings, remult) {
3398
3402
  if (settings.valueType) {
3399
3403
  var settingsOnTypeLevel = settings.valueType[exports.storableMember];
3400
3404
  if (settingsOnTypeLevel) {
3401
- settings = tslib_1.__assign(tslib_1.__assign({}, buildOptions(settingsOnTypeLevel, remult)), settings);
3405
+ settings = buildOptions(tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(settingsOnTypeLevel), false), [settings], false), remult);
3402
3406
  }
3403
3407
  }
3404
3408
  if (settings.valueType == String) {
@@ -0,0 +1,2 @@
1
+ import type { FieldOptions } from '../column-interfaces.js';
2
+ export declare function addValidator(validators: FieldOptions['validate'], newValidator: FieldOptions['validate'], atStart?: boolean): import("../column-interfaces.js").FieldValidator<any, any> | import("../column-interfaces.js").FieldValidator<any, any>[];
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addValidator = void 0;
4
+ var tslib_1 = require("tslib");
5
+ function addValidator(validators, newValidator, atStart) {
6
+ if (atStart === void 0) { atStart = false; }
7
+ if (!newValidator)
8
+ return validators;
9
+ var newValidators = Array.isArray(newValidator)
10
+ ? newValidator
11
+ : [newValidator];
12
+ var validatorsArray = Array.isArray(validators)
13
+ ? validators
14
+ : validators
15
+ ? [validators]
16
+ : [];
17
+ return atStart
18
+ ? tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(newValidators), false), tslib_1.__read(validatorsArray), false) : tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(validatorsArray), false), tslib_1.__read(newValidators), false);
19
+ }
20
+ exports.addValidator = addValidator;
@@ -2,12 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  //p1 - `preprocessApiFindOptions`, naming - allow find options preprocessor for api calls, to use for authorization
4
4
  //p1 - admin url1 - pocketbase use /_ for the admin //{allowed?:Allowed,url?:string}
5
- //p1 - Validate for NAN
6
5
  //p1 - Make async hooks gracefully handle non async hooks environment
7
- //p1 - chain validators with options
6
+ //p1 - implement generic sqlite support better-sqlite3/ bun sqlite
7
+ //p1 - article auth.js with express
8
+ //p1 - document offline support
8
9
  //y2 - should we validate relations
9
10
  //y1 - consider replacing all errors with error classes that extend the base Error class
10
- //y2 - consider if field types should include validation in them by default (string,number that it's not NaN etc...) and if so, what message?
11
11
  //y2 - should enforce integer - currently we probably round / truncate it
12
12
  /*y1 - talk about modules in init express with entities/controllers,initRequest,initApi
13
13
  - support get with backend method, with url search params as the first parameter, & url as second parameter
@@ -15,8 +15,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
 
16
16
  */
17
17
  //p1 - in this video I'll use remult to turn a frontend app to a fullstack app
18
- //y1 - getFields didn't work for kobi in the home component
19
- //p1 - document offline support
20
18
  /*y1 - Talk JYC - JYC - add some integrity checks on delete
21
19
  - soft delete
22
20
  - delete restrict (implicit, or user selected - and if so, how) (delete & update of id)
@@ -47,3 +47,4 @@ export type ValidatorWithArgs<valueType, argsType> = (args: argsType, message?:
47
47
  export declare function createValidatorWithArgs<valueType, argsType>(validate: (entity: any, e: ValidateFieldEvent<any, valueType>, args: argsType) => Promise<boolean | string> | boolean | string, defaultMessage: ValidationMessage<valueType, argsType>): ValidatorWithArgs<valueType, argsType> & {
48
48
  defaultMessage: ValidationMessage<valueType, argsType>;
49
49
  };
50
+ export declare function getEnumValues<theEnum = any>(enumObj: theEnum): any[];
package/src/validators.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createValidatorWithArgs = exports.createValueValidatorWithArgs = exports.createValueValidator = exports.valueValidator = exports.createValidator = exports.Validators = void 0;
3
+ exports.getEnumValues = exports.createValidatorWithArgs = exports.createValueValidatorWithArgs = exports.createValueValidator = exports.valueValidator = exports.createValidator = exports.Validators = void 0;
4
4
  var tslib_1 = require("tslib");
5
5
  var Validators = /** @class */ (function () {
6
6
  function Validators() {
@@ -53,8 +53,7 @@ var Validators = /** @class */ (function () {
53
53
  }).join(', ')); });
54
54
  Validators.notNull = createValueValidator(function (val) { return val != null; }, 'Should not be null');
55
55
  Validators.enum = createValueValidatorWithArgs(function (value, enumObj) { return Object.values(enumObj).includes(value); }, function (enumObj) {
56
- return "Value must be one of ".concat(Object.values(enumObj)
57
- .filter(function (x) { return typeof enumObj[x] !== 'number'; })
56
+ return "Value must be one of ".concat(getEnumValues(enumObj)
58
57
  .join(', '));
59
58
  });
60
59
  Validators.relationExists = createValidator(function (_, e) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
@@ -209,3 +208,8 @@ function createValidatorWithArgsInternal(validate, defaultMessage, isValueValida
209
208
  },
210
209
  });
211
210
  }
211
+ function getEnumValues(enumObj) {
212
+ return Object.values(enumObj)
213
+ .filter(function (x) { return typeof enumObj[x] !== 'number'; });
214
+ }
215
+ exports.getEnumValues = getEnumValues;
@@ -1 +0,0 @@
1
- export const addValidatorKey = '__addValidator';
@@ -1 +0,0 @@
1
- export declare const addValidatorKey = "__addValidator";
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.addValidatorKey = void 0;
4
- exports.addValidatorKey = '__addValidator';