remult 0.25.8-exp.3 → 0.25.8-exp.5

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.
@@ -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;
@@ -22,11 +22,17 @@ export class CompoundIdField {
22
22
  return Promise.resolve('');
23
23
  }
24
24
  getId(instance) {
25
+ let get = (field) => {
26
+ return instance[field.key];
27
+ };
28
+ if (typeof instance === 'function') {
29
+ get = instance;
30
+ }
25
31
  let r = '';
26
32
  this.fields.forEach((c) => {
27
33
  if (r.length > 0)
28
34
  r += ',';
29
- r += instance[c.key];
35
+ r += c.valueConverter.toJson(get(c));
30
36
  });
31
37
  return r;
32
38
  }
@@ -49,7 +55,7 @@ export class CompoundIdField {
49
55
  let val = value.toString();
50
56
  let id = val.split(',');
51
57
  this.fields.forEach((c, i) => {
52
- result[c.key] = id[i];
58
+ result[c.key] = c.valueConverter.fromJson(id[i]);
53
59
  });
54
60
  return result;
55
61
  }
@@ -23,16 +23,30 @@ export class DataApi {
23
23
  }
24
24
  async httpPost(res, req, body, serializeContext) {
25
25
  const action = req?.get('__action');
26
- if (action?.startsWith(liveQueryAction))
26
+ function validateWhereInBody() {
27
+ if (!body?.where) {
28
+ throw {
29
+ message: `POST with action ${action} must have a where clause in the body`,
30
+ httpStatusCode: 400,
31
+ };
32
+ }
33
+ }
34
+ if (action?.startsWith(liveQueryAction)) {
35
+ validateWhereInBody();
27
36
  return this.liveQuery(res, req, body, serializeContext, action.substring(liveQueryAction.length));
37
+ }
28
38
  switch (action) {
29
39
  case 'get':
40
+ validateWhereInBody();
30
41
  return this.getArray(res, req, body);
31
42
  case 'count':
43
+ validateWhereInBody();
32
44
  return this.count(res, req, body);
33
45
  case 'deleteMany':
46
+ validateWhereInBody();
34
47
  return this.deleteMany(res, req, body);
35
48
  case 'updateMany':
49
+ validateWhereInBody();
36
50
  return this.updateManyImplementation(res, req, body);
37
51
  case 'endLiveQuery':
38
52
  await this.remult.liveQueryStorage.remove(body.id);
@@ -1186,7 +1186,7 @@ export class rowHelperImplementation extends rowHelperBase {
1186
1186
  return this.instance[y.key];
1187
1187
  };
1188
1188
  if (this.metadata.idMetadata.field instanceof CompoundIdField)
1189
- return this.metadata.idMetadata.field.fields.map(getVal).join(',');
1189
+ return this.metadata.idMetadata.field.getId(getVal);
1190
1190
  return getVal(this.metadata.idMetadata.field);
1191
1191
  }
1192
1192
  saveMoreOriginalData() {
@@ -1,7 +1,5 @@
1
1
  export {};
2
- //y1 - reconsider adding where to all in case of post - it is a breaking change and no longer required
3
- //y1 - review that with deleteMany, and updateMany I've taken a similar approach to get, that when the filter is complex, we go to post - one reason is that delete doesn't accept a body.
4
- //y1 - should the remult api be deleteMany({id:[1,2]}) or deleteMany({where:{id:[1,2]}})
2
+ //p1 - should the remult api be deleteMany({id:[1,2]}) or deleteMany({where:{id:[1,2]}})
5
3
  //p1 - in this video I'll use remult to turn a frontend app to a fullstack app
6
4
  //y1 - getFields didn't work for kobi in the home component
7
5
  //y1 - consider replacing all errors with error classes that extend the base Error class
@@ -3,13 +3,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.updateMigrationsFile = void 0;
4
4
  var tslib_1 = require("tslib");
5
5
  // consider replacing with https://www.npmjs.com/package/ts-morph
6
- var ts = tslib_1.__importStar(require("typescript"));
6
+ var typescript_1 = tslib_1.__importDefault(require("typescript"));
7
7
  var fs = tslib_1.__importStar(require("fs"));
8
8
  function updateMigrationsFile(filePath, steps) {
9
9
  return tslib_1.__awaiter(this, void 0, void 0, function () {
10
10
  function buildSteps() {
11
11
  return steps.map(function (step) {
12
- return ts.factory.createPropertyAssignment(ts.factory.createIdentifier((++maxStep).toString()), ts.factory.createIdentifier(step));
12
+ return typescript_1.default.factory.createPropertyAssignment(typescript_1.default.factory.createIdentifier((++maxStep).toString()), typescript_1.default.factory.createIdentifier(step));
13
13
  });
14
14
  }
15
15
  var maxStep, importPath, importName, sourceFile, migrationsExportFound, updatedSourceFile, importFound_1, newMigrationsExport, code, prettier, err_1, options, err_2;
@@ -22,23 +22,23 @@ function updateMigrationsFile(filePath, steps) {
22
22
  }
23
23
  importPath = 'remult/migrations';
24
24
  importName = 'Migrations';
25
- sourceFile = ts.createSourceFile(filePath, fs.readFileSync(filePath).toString(), ts.ScriptTarget.Latest, true);
25
+ sourceFile = typescript_1.default.createSourceFile(filePath, fs.readFileSync(filePath).toString(), typescript_1.default.ScriptTarget.Latest, true);
26
26
  migrationsExportFound = false;
27
- updatedSourceFile = ts.transform(sourceFile, [
27
+ updatedSourceFile = typescript_1.default.transform(sourceFile, [
28
28
  function (context) {
29
29
  return function (node) {
30
30
  var visitor = function (node) {
31
- if (ts.isVariableStatement(node) &&
31
+ if (typescript_1.default.isVariableStatement(node) &&
32
32
  node.declarationList.declarations.length > 0) {
33
33
  var declaration = node.declarationList.declarations[0];
34
- if (ts.isIdentifier(declaration.name) &&
34
+ if (typescript_1.default.isIdentifier(declaration.name) &&
35
35
  declaration.name.text === 'migrations' &&
36
36
  declaration.initializer &&
37
- ts.isObjectLiteralExpression(declaration.initializer)) {
37
+ typescript_1.default.isObjectLiteralExpression(declaration.initializer)) {
38
38
  migrationsExportFound = true;
39
39
  declaration.initializer.properties.forEach(function (property) {
40
- if (ts.isPropertyAssignment(property)) {
41
- if (ts.isNumericLiteral(property.name)) {
40
+ if (typescript_1.default.isPropertyAssignment(property)) {
41
+ if (typescript_1.default.isNumericLiteral(property.name)) {
42
42
  var step = parseInt(property.name.text);
43
43
  if (step > maxStep) {
44
44
  maxStep = step;
@@ -49,18 +49,18 @@ function updateMigrationsFile(filePath, steps) {
49
49
  var steps_1 = buildSteps();
50
50
  // Found the "migrations" array
51
51
  // Update the initializer with the new steps
52
- var updatedInitializer = ts.factory.updateObjectLiteralExpression(declaration.initializer, tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(declaration.initializer.properties), false), tslib_1.__read(steps_1), false));
52
+ var updatedInitializer = typescript_1.default.factory.updateObjectLiteralExpression(declaration.initializer, tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(declaration.initializer.properties), false), tslib_1.__read(steps_1), false));
53
53
  // Update the declaration with the new initializer
54
- var updatedDeclaration = ts.factory.updateVariableDeclaration(declaration, declaration.name, undefined, declaration.type, // Preserve the original type annotation if present
54
+ var updatedDeclaration = typescript_1.default.factory.updateVariableDeclaration(declaration, declaration.name, undefined, declaration.type, // Preserve the original type annotation if present
55
55
  updatedInitializer);
56
- return ts.factory.updateVariableStatement(node, node.modifiers, ts.factory.updateVariableDeclarationList(node.declarationList, [
56
+ return typescript_1.default.factory.updateVariableStatement(node, node.modifiers, typescript_1.default.factory.updateVariableDeclarationList(node.declarationList, [
57
57
  updatedDeclaration,
58
58
  ]));
59
59
  }
60
60
  }
61
- return ts.visitEachChild(node, visitor, context);
61
+ return typescript_1.default.visitEachChild(node, visitor, context);
62
62
  };
63
- return ts.visitNode(node, visitor);
63
+ return typescript_1.default.visitNode(node, visitor);
64
64
  };
65
65
  },
66
66
  ]).transformed[0];
@@ -69,11 +69,11 @@ function updateMigrationsFile(filePath, steps) {
69
69
  // Check if the import statement already exists
70
70
  sourceFile.statements.forEach(function (statement) {
71
71
  var _a, _b;
72
- if (ts.isImportDeclaration(statement) &&
73
- ts.isStringLiteral(statement.moduleSpecifier) &&
72
+ if (typescript_1.default.isImportDeclaration(statement) &&
73
+ typescript_1.default.isStringLiteral(statement.moduleSpecifier) &&
74
74
  statement.moduleSpecifier.text === "".concat(importPath)) {
75
75
  (_b = (_a = statement.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings) === null || _b === void 0 ? void 0 : _b.forEachChild(function (namedBinding) {
76
- if (ts.isImportSpecifier(namedBinding) &&
76
+ if (typescript_1.default.isImportSpecifier(namedBinding) &&
77
77
  namedBinding.name.text === importName) {
78
78
  importFound_1 = true;
79
79
  }
@@ -82,20 +82,20 @@ function updateMigrationsFile(filePath, steps) {
82
82
  });
83
83
  // If the import statement doesn't exist, create it
84
84
  if (!importFound_1) {
85
- updatedSourceFile = ts.factory.updateSourceFile(updatedSourceFile, tslib_1.__spreadArray([
86
- ts.factory.createExpressionStatement(ts.factory.createIdentifier("import type { ".concat(importName, " } from '").concat(importPath, "'")))
85
+ updatedSourceFile = typescript_1.default.factory.updateSourceFile(updatedSourceFile, tslib_1.__spreadArray([
86
+ typescript_1.default.factory.createExpressionStatement(typescript_1.default.factory.createIdentifier("import type { ".concat(importName, " } from '").concat(importPath, "'")))
87
87
  ], tslib_1.__read(updatedSourceFile.statements), false));
88
88
  }
89
- newMigrationsExport = ts.factory.createVariableStatement([ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], ts.factory.createVariableDeclarationList([
90
- ts.factory.createVariableDeclaration('migrations', undefined, // You can add a type annotation here if needed
91
- ts.factory.createTypeReferenceNode(importName, undefined), ts.factory.createObjectLiteralExpression(buildSteps(), false)),
92
- ], ts.NodeFlags.Const));
89
+ newMigrationsExport = typescript_1.default.factory.createVariableStatement([typescript_1.default.factory.createModifier(typescript_1.default.SyntaxKind.ExportKeyword)], typescript_1.default.factory.createVariableDeclarationList([
90
+ typescript_1.default.factory.createVariableDeclaration('migrations', undefined, // You can add a type annotation here if needed
91
+ typescript_1.default.factory.createTypeReferenceNode(importName, undefined), typescript_1.default.factory.createObjectLiteralExpression(buildSteps(), false)),
92
+ ], typescript_1.default.NodeFlags.Const));
93
93
  // Add the new export to the end of the file
94
- updatedSourceFile = ts.factory.updateSourceFile(updatedSourceFile, tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(updatedSourceFile.statements), false), [
94
+ updatedSourceFile = typescript_1.default.factory.updateSourceFile(updatedSourceFile, tslib_1.__spreadArray(tslib_1.__spreadArray([], tslib_1.__read(updatedSourceFile.statements), false), [
95
95
  newMigrationsExport,
96
96
  ], false));
97
97
  }
98
- code = ts.createPrinter().printFile(updatedSourceFile);
98
+ code = typescript_1.default.createPrinter().printFile(updatedSourceFile);
99
99
  _a.label = 1;
100
100
  case 1:
101
101
  _a.trys.push([1, 9, , 10]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remult",
3
- "version": "0.25.8-exp.3",
3
+ "version": "0.25.8-exp.5",
4
4
  "description": "A CRUD framework for full-stack TypeScript",
5
5
  "homepage": "https://remult.dev",
6
6
  "repository": {
@@ -28,11 +28,17 @@ var CompoundIdField = /** @class */ (function () {
28
28
  return Promise.resolve('');
29
29
  };
30
30
  CompoundIdField.prototype.getId = function (instance) {
31
+ var get = function (field) {
32
+ return instance[field.key];
33
+ };
34
+ if (typeof instance === 'function') {
35
+ get = instance;
36
+ }
31
37
  var r = '';
32
38
  this.fields.forEach(function (c) {
33
39
  if (r.length > 0)
34
40
  r += ',';
35
- r += instance[c.key];
41
+ r += c.valueConverter.toJson(get(c));
36
42
  });
37
43
  return r;
38
44
  };
@@ -48,7 +54,7 @@ var CompoundIdField = /** @class */ (function () {
48
54
  var val = value.toString();
49
55
  var id = val.split(',');
50
56
  this.fields.forEach(function (c, i) {
51
- result[c.key] = id[i];
57
+ result[c.key] = c.valueConverter.fromJson(id[i]);
52
58
  });
53
59
  return result;
54
60
  };
package/src/data-api.js CHANGED
@@ -25,13 +25,23 @@ var DataApi = /** @class */ (function () {
25
25
  };
26
26
  DataApi.prototype.httpPost = function (res, req, body, serializeContext) {
27
27
  return tslib_1.__awaiter(this, void 0, void 0, function () {
28
+ function validateWhereInBody() {
29
+ if (!(body === null || body === void 0 ? void 0 : body.where)) {
30
+ throw {
31
+ message: "POST with action ".concat(action, " must have a where clause in the body"),
32
+ httpStatusCode: 400,
33
+ };
34
+ }
35
+ }
28
36
  var action, _a;
29
37
  return tslib_1.__generator(this, function (_b) {
30
38
  switch (_b.label) {
31
39
  case 0:
32
40
  action = req === null || req === void 0 ? void 0 : req.get('__action');
33
- if (action === null || action === void 0 ? void 0 : action.startsWith(rest_data_provider_js_1.liveQueryAction))
41
+ if (action === null || action === void 0 ? void 0 : action.startsWith(rest_data_provider_js_1.liveQueryAction)) {
42
+ validateWhereInBody();
34
43
  return [2 /*return*/, this.liveQuery(res, req, body, serializeContext, action.substring(rest_data_provider_js_1.liveQueryAction.length))];
44
+ }
35
45
  _a = action;
36
46
  switch (_a) {
37
47
  case 'get': return [3 /*break*/, 1];
@@ -41,10 +51,18 @@ var DataApi = /** @class */ (function () {
41
51
  case 'endLiveQuery': return [3 /*break*/, 5];
42
52
  }
43
53
  return [3 /*break*/, 7];
44
- case 1: return [2 /*return*/, this.getArray(res, req, body)];
45
- case 2: return [2 /*return*/, this.count(res, req, body)];
46
- case 3: return [2 /*return*/, this.deleteMany(res, req, body)];
47
- case 4: return [2 /*return*/, this.updateManyImplementation(res, req, body)];
54
+ case 1:
55
+ validateWhereInBody();
56
+ return [2 /*return*/, this.getArray(res, req, body)];
57
+ case 2:
58
+ validateWhereInBody();
59
+ return [2 /*return*/, this.count(res, req, body)];
60
+ case 3:
61
+ validateWhereInBody();
62
+ return [2 /*return*/, this.deleteMany(res, req, body)];
63
+ case 4:
64
+ validateWhereInBody();
65
+ return [2 /*return*/, this.updateManyImplementation(res, req, body)];
48
66
  case 5: return [4 /*yield*/, this.remult.liveQueryStorage.remove(body.id)];
49
67
  case 6:
50
68
  _b.sent();
@@ -4,7 +4,7 @@ import type { FieldMetadata, FieldOptions, ValueConverter, ValueListItem } from
4
4
  import { Remult } from '../context.js';
5
5
  import type { EntityOptions } from '../entity.js';
6
6
  import { Filter } from '../filter/filter-interfaces.js';
7
- import type { ControllerRef, ControllerRefForControllerBase, EntityFilter, EntityMetadata, EntityOrderBy, EntityRef, EntityRefForEntityBase, FieldRef, FieldsMetadata, FieldsRef, FieldsRefForEntityBase, FindFirstOptions, FindFirstOptionsBase, FindOptions, IdMetadata, LiveQuery, LoadOptions, MembersOnly, QueryOptions, QueryResult, Repository, RepositoryRelations, Subscribable } from './remult3.js';
7
+ import type { ControllerRef, ControllerRefForControllerBase, EntityFilter, EntityMetadata, EntityOrderBy, EntityRef, EntityRefForEntityBase, FieldRef, FieldsMetadata, FieldsRef, FieldsRefForEntityBase, FindFirstOptions, FindFirstOptionsBase, FindOptions, IdMetadata, LiveQuery, LoadOptions, MembersOnly, QueryOptions, QueryResult, Repository, RepositoryRelations, Subscribable, idType } from './remult3.js';
8
8
  import type { RefSubscriber } from './remult3.js';
9
9
  import type { entityEventListener } from '../__EntityValueProvider.js';
10
10
  import type { DataProvider, EntityDataProvider, EntityDataProviderFindOptions, ErrorInfo } from '../data-interfaces.js';
@@ -41,22 +41,14 @@ export declare class RepositoryImplementation<entityType> implements Repository<
41
41
  addEventListener(listener: entityEventListener<entityType>): () => void;
42
42
  query(options?: QueryOptions<entityType>): QueryResult<entityType>;
43
43
  getEntityRef(entity: entityType): EntityRef<entityType>;
44
- delete(id: entityType extends {
45
- id?: number;
46
- } ? number : entityType extends {
47
- id?: string;
48
- } ? string : string | number): Promise<void>;
44
+ delete(id: idType<entityType>): Promise<void>;
49
45
  delete(item: entityType): Promise<void>;
50
46
  insert(item: Partial<MembersOnly<entityType>>[]): Promise<entityType[]>;
51
47
  insert(item: Partial<MembersOnly<entityType>>): Promise<entityType>;
52
48
  get fields(): FieldsMetadata<entityType>;
53
49
  validate(entity: Partial<MembersOnly<entityType>>, ...fields: Extract<keyof MembersOnly<entityType>, string>[]): Promise<ErrorInfo<entityType> | undefined>;
54
50
  updateMany(where: EntityFilter<entityType>, set: Partial<MembersOnly<entityType>>): Promise<number>;
55
- update(id: entityType extends {
56
- id?: number;
57
- } ? number : entityType extends {
58
- id?: string;
59
- } ? string : string | number, item: Partial<MembersOnly<entityType>>): Promise<entityType>;
51
+ update(id: idType<entityType>, item: Partial<MembersOnly<entityType>>): Promise<entityType>;
60
52
  update(originalItem: Partial<MembersOnly<entityType>>, item: Partial<MembersOnly<entityType>>): Promise<entityType>;
61
53
  private _getRefForExistingRow;
62
54
  save(item: Partial<MembersOnly<entityType>>[]): Promise<entityType[]>;
@@ -1956,7 +1956,7 @@ var rowHelperImplementation = /** @class */ (function (_super) {
1956
1956
  return _this.instance[y.key];
1957
1957
  };
1958
1958
  if (this.metadata.idMetadata.field instanceof CompoundIdField_js_1.CompoundIdField)
1959
- return this.metadata.idMetadata.field.fields.map(getVal).join(',');
1959
+ return this.metadata.idMetadata.field.getId(getVal);
1960
1960
  return getVal(this.metadata.idMetadata.field);
1961
1961
  };
1962
1962
  rowHelperImplementation.prototype.saveMoreOriginalData = function () {
@@ -239,10 +239,8 @@ export declare type MembersOnly<T> = {
239
239
  [K in keyof Omit<T, keyof EntityBase> as T[K] extends Function ? never : K]: T[K];
240
240
  };
241
241
  export declare type idType<entityType> = entityType extends {
242
- id?: number;
243
- } ? number : entityType extends {
244
- id?: string;
245
- } ? string : string | number;
242
+ id?: infer U;
243
+ } ? U : string | number;
246
244
  /**used to perform CRUD operations on an `entityType` */
247
245
  export interface Repository<entityType> {
248
246
  /** returns a result array based on the provided options */
@@ -312,22 +310,14 @@ export interface Repository<entityType> {
312
310
  * @example
313
311
  * taskRepo.update(task.id,{...task,completed:true})
314
312
  */
315
- update(id: entityType extends {
316
- id?: number;
317
- } ? number : entityType extends {
318
- id?: string;
319
- } ? string : string | number, item: Partial<MembersOnly<entityType>>): Promise<entityType>;
313
+ update(id: idType<entityType>, item: Partial<MembersOnly<entityType>>): Promise<entityType>;
320
314
  update(id: Partial<MembersOnly<entityType>>, item: Partial<MembersOnly<entityType>>): Promise<entityType>;
321
315
  /**
322
316
  * Updates all items that match the `where` condition.
323
317
  */
324
318
  updateMany(where: EntityFilter<entityType>, item: Partial<MembersOnly<entityType>>): Promise<number>;
325
319
  /** Deletes an Item*/
326
- delete(id: entityType extends {
327
- id?: number;
328
- } ? number : entityType extends {
329
- id?: string;
330
- } ? string : string | number): Promise<void>;
320
+ delete(id: idType<entityType>): Promise<void>;
331
321
  delete(item: Partial<MembersOnly<entityType>>): Promise<void>;
332
322
  /**
333
323
  * Deletes all items that match the `where` condition.
@@ -1,8 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //y1 - reconsider adding where to all in case of post - it is a breaking change and no longer required
4
- //y1 - review that with deleteMany, and updateMany I've taken a similar approach to get, that when the filter is complex, we go to post - one reason is that delete doesn't accept a body.
5
- //y1 - should the remult api be deleteMany({id:[1,2]}) or deleteMany({where:{id:[1,2]}})
3
+ //p1 - should the remult api be deleteMany({id:[1,2]}) or deleteMany({where:{id:[1,2]}})
6
4
  //p1 - in this video I'll use remult to turn a frontend app to a fullstack app
7
5
  //y1 - getFields didn't work for kobi in the home component
8
6
  //y1 - consider replacing all errors with error classes that extend the base Error class