remult 0.20.6 → 0.21.0

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 (37) hide show
  1. package/esm/graphql.d.ts +13 -4
  2. package/esm/graphql.js +671 -130
  3. package/esm/index.d.ts +1 -2
  4. package/esm/index.js +1 -2
  5. package/esm/remult-express.d.ts +1 -1
  6. package/esm/remult-express.js +1 -1
  7. package/esm/remult-fastify.js +2 -6
  8. package/esm/remult-fresh.js +1 -1
  9. package/esm/remult-next.js +3 -9
  10. package/esm/server/expressBridge.d.ts +4 -4
  11. package/esm/server/expressBridge.js +27 -10
  12. package/esm/src/data-api.d.ts +2 -2
  13. package/esm/src/data-providers/sql-database.d.ts +13 -1
  14. package/esm/src/data-providers/sql-database.js +41 -4
  15. package/esm/src/remult3/RepositoryImplementation.d.ts +3 -0
  16. package/esm/src/remult3/RepositoryImplementation.js +7 -0
  17. package/esm/src/shared-tests/db-tests.db-tests.d.ts +1 -2
  18. package/esm/src/shared-tests/db-tests.db-tests.js +1 -2
  19. package/graphql.d.ts +13 -4
  20. package/graphql.js +792 -189
  21. package/index.d.ts +1 -2
  22. package/index.js +2 -3
  23. package/package.json +1 -2
  24. package/remult-express.d.ts +1 -1
  25. package/remult-express.js +1 -7
  26. package/remult-fastify.js +4 -6
  27. package/remult-fresh.js +1 -1
  28. package/remult-next.js +4 -8
  29. package/server/expressBridge.d.ts +4 -4
  30. package/server/expressBridge.js +32 -14
  31. package/src/data-api.d.ts +2 -2
  32. package/src/data-providers/sql-database.d.ts +13 -1
  33. package/src/data-providers/sql-database.js +42 -5
  34. package/src/remult3/RepositoryImplementation.d.ts +3 -0
  35. package/src/remult3/RepositoryImplementation.js +13 -1
  36. package/src/shared-tests/db-tests.db-tests.d.ts +1 -2
  37. package/src/shared-tests/db-tests.db-tests.js +2 -3
package/esm/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { Field, Fields, FieldsMetadata, Entity, EntityBase, ControllerBase, FieldRef, IdFieldRef, FieldsRef, EntityMetadata, EntityOrderBy, EntityFilter, FindOptions, QueryResult, QueryOptions, Repository, FieldType, FindFirstOptions, ComparisonValueFilter, ValueFilter, IdFilter, ContainsStringValueFilter, getFields, EntityRef, getEntityRef, SortSegments, ValueListFieldType, getValueList, ValueListFieldOptions, ValueListInfo, OmitEB, Paginator, CaptionTransformer, LiveQuery, LiveQueryChangeInfo } from './src/remult3';
1
+ export { Field, Fields, FieldsMetadata, Entity, IdEntity, EntityBase, ControllerBase, FieldRef, IdFieldRef, FieldsRef, EntityMetadata, EntityOrderBy, EntityFilter, FindOptions, QueryResult, QueryOptions, Repository, FieldType, FindFirstOptions, ComparisonValueFilter, ValueFilter, IdFilter, ContainsStringValueFilter, getFields, EntityRef, getEntityRef, SortSegments, ValueListFieldType, getValueList, ValueListFieldOptions, ValueListInfo, OmitEB, Paginator, CaptionTransformer, LiveQuery, LiveQueryChangeInfo } from './src/remult3';
2
2
  export { StringFieldOptions } from './src/remult3/RepositoryImplementation';
3
3
  export { describeClass } from './src/remult3/DecoratorReplacer';
4
4
  export { EntityOptions } from './src/entity';
@@ -16,7 +16,6 @@ export { JsonDataProvider, JsonEntityStorage } from './src/data-providers/json-d
16
16
  export { Controller, BackendMethodOptions, BackendMethod, ProgressListener } from './src/server-action';
17
17
  export { Allowed, Allow, Remult, RemultContext, ApiClient, isBackend, AllowedForInstance, EventDispatcher, EventSource, UserInfo } from './src/context';
18
18
  export { ExternalHttpProvider } from './src/buildRestDataProvider';
19
- export { IdEntity } from './src/id-entity';
20
19
  export { SortSegment, Sort } from './src/sort';
21
20
  export { OneToMany, CompoundIdField } from './src/column';
22
21
  export { Filter } from './src/filter/filter-interfaces';
package/esm/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  * Public API Surface of remult
3
3
  */
4
- export { Field, Fields, Entity, EntityBase, ControllerBase, FieldType, getFields, getEntityRef, ValueListFieldType, getValueList, ValueListInfo, CaptionTransformer } from './src/remult3';
4
+ export { Field, Fields, Entity, IdEntity, EntityBase, ControllerBase, FieldType, getFields, getEntityRef, ValueListFieldType, getValueList, ValueListInfo, CaptionTransformer } from './src/remult3';
5
5
  export { describeClass } from './src/remult3/DecoratorReplacer';
6
6
  export { RestDataProvider } from './src/data-providers/rest-data-provider'; //V
7
7
  export { InMemoryDataProvider } from './src/data-providers/in-memory-database'; //V
@@ -13,7 +13,6 @@ export { JsonDataProvider } from './src/data-providers/json-data-provider'; //V
13
13
  //export * from './src/data-api'; //reconsider if to make internal
14
14
  export { Controller, BackendMethod, ProgressListener } from './src/server-action';
15
15
  export { Allow, Remult, isBackend, EventSource } from './src/context';
16
- export { IdEntity } from './src/id-entity';
17
16
  export { Sort } from './src/sort';
18
17
  export { OneToMany, CompoundIdField } from './src/column';
19
18
  export { Filter } from './src/filter/filter-interfaces';
@@ -1,5 +1,5 @@
1
1
  import * as express from 'express';
2
- import { RemultServerCore, RemultServerOptions } from './server/expressBridge';
2
+ import type { RemultServerCore, RemultServerOptions } from './server/expressBridge';
3
3
  export declare function remultExpress(options?: RemultServerOptions<express.Request> & {
4
4
  bodyParser?: boolean;
5
5
  bodySizeLimit?: string;
@@ -20,6 +20,6 @@ export function remultExpress(options) {
20
20
  return Object.assign(app, {
21
21
  getRemult: (req) => server.getRemult(req),
22
22
  openApiDoc: (options) => server.openApiDoc(options),
23
- withRemult: (...args) => server.withRemult(...args)
23
+ withRemult: (req, res, next) => server.withRemult(req, res, next),
24
24
  });
25
25
  }
@@ -31,7 +31,7 @@ export function remultFastify(options) {
31
31
  }
32
32
  const api = createRemultServer(options, {
33
33
  buildGenericRequestInfo: req => req,
34
- getRequestBody: async (req) => req.body
34
+ getRequestBody: async (req) => req.body,
35
35
  });
36
36
  const pluginFunction = async (instance, op) => {
37
37
  //@ts-ignore
@@ -61,10 +61,6 @@ export function remultFastify(options) {
61
61
  return Object.assign(pluginFunction, {
62
62
  getRemult: x => api.getRemult(x),
63
63
  openApiDoc: x => api.openApiDoc(x),
64
- withRemult: (req, what) => new Promise((resolve) => {
65
- return api.withRemult(req, undefined, () => {
66
- what().then(resolve);
67
- });
68
- })
64
+ withRemult: (req, what) => api.withRemultPromise(req, what),
69
65
  });
70
66
  }
@@ -22,7 +22,7 @@ export function remultFresh(options, response) {
22
22
  return ctx.next();
23
23
  }
24
24
  ;
25
- }
25
+ },
26
26
  };
27
27
  }
28
28
  ;
@@ -40,8 +40,8 @@ export function remultNextApp(options) {
40
40
  let result = createRemultServer(options, {
41
41
  getRequestBody: req => req.json(),
42
42
  buildGenericRequestInfo: (req) => ({
43
- url: req.url,
44
- method: req.method,
43
+ url: req?.url,
44
+ method: req?.method,
45
45
  on: (e, do1) => {
46
46
  if (e === "close") {
47
47
  req["_tempOnClose"] = do1;
@@ -103,12 +103,6 @@ export function remultNextApp(options) {
103
103
  POST: handler,
104
104
  PUT: handler,
105
105
  DELETE: handler,
106
- withRemult: (what) => {
107
- return new Promise((resolve) => {
108
- return result.withRemult({}, undefined, () => {
109
- what().then(resolve);
110
- });
111
- });
112
- }
106
+ withRemult: (what) => result.withRemultPromise({}, what),
113
107
  };
114
108
  }
@@ -1,9 +1,8 @@
1
1
  import { queuedJobInfoResponse } from '../src/server-action';
2
- import { DataProvider } from '../src/data-interfaces';
2
+ import type { DataProvider } from '../src/data-interfaces';
3
3
  import { Remult, UserInfo } from '../src/context';
4
- import { ClassType } from '../classType';
5
- import { Repository } from '../src/remult3';
6
- import { IdEntity } from '../src/id-entity';
4
+ import type { ClassType } from '../classType';
5
+ import { IdEntity, Repository } from '../src/remult3';
7
6
  import { LiveQueryStorage, SubscriptionServer } from '../src/live-query/SubscriptionServer';
8
7
  export interface RemultServerOptions<RequestType> {
9
8
  /**Entities to use for the api */
@@ -63,6 +62,7 @@ export interface RemultServer<RequestType> extends RemultServerCore<RequestType>
63
62
  withRemult(req: RequestType, res: GenericResponse, next: VoidFunction): any;
64
63
  registerRouter(r: GenericRouter): void;
65
64
  handle(req: RequestType, gRes?: GenericResponse): Promise<ServerHandleResponse | undefined>;
65
+ withRemultPromise<T>(request: RequestType, what: () => Promise<T>): Promise<T>;
66
66
  }
67
67
  export interface RemultServerCore<RequestType> {
68
68
  getRemult(req: RequestType): Promise<Remult>;
@@ -2,8 +2,7 @@ import { __decorate, __metadata } from "tslib";
2
2
  import { Action, actionInfo, classBackendMethodsArray, serverActionField } from '../src/server-action';
3
3
  import { DataApi, serializeError } from '../src/data-api';
4
4
  import { allEntities, Remult } from '../src/context';
5
- import { Entity, Fields, getEntityKey } from '../src/remult3';
6
- import { IdEntity } from '../src/id-entity';
5
+ import { Entity, Fields, getEntityKey, IdEntity } from '../src/remult3';
7
6
  import { remult } from '../src/remult-proxy';
8
7
  import { LiveQueryPublisher, InMemoryLiveQueryStorage } from '../src/live-query/SubscriptionServer';
9
8
  import { liveQueryKeepAliveRoute, streamUrl } from '../src/live-query/SubscriptionChannel';
@@ -30,6 +29,7 @@ export function createRemultServerCore(options, serverCoreOptions) {
30
29
  if (options.ensureSchema === undefined)
31
30
  options.ensureSchema = true;
32
31
  RemultAsyncLocalStorage.enable();
32
+ const entitiesMetaData = [];
33
33
  dataProvider = dataProvider.then(async (dp) => {
34
34
  var remult = new Remult(dp);
35
35
  await new Promise((res) => {
@@ -42,10 +42,10 @@ export function createRemultServerCore(options, serverCoreOptions) {
42
42
  started = true;
43
43
  console.time("Ensure Schema");
44
44
  };
45
+ entitiesMetaData.push(...options.entities.map(e => remult.repo(e).metadata));
45
46
  if (dp.ensureSchema) {
46
47
  startConsoleLog();
47
- const entitiesMetadata = options.entities.map(e => remult.repo(e).metadata);
48
- await dp.ensureSchema(entitiesMetadata);
48
+ await dp.ensureSchema(entitiesMetaData);
49
49
  }
50
50
  for (const item of [options.liveQueryStorage, options.queueStorage]) {
51
51
  if (item?.ensureSchema) {
@@ -76,7 +76,7 @@ export function createRemultServerCore(options, serverCoreOptions) {
76
76
  if (options.rootPath === undefined)
77
77
  options.rootPath = '/api';
78
78
  actionInfo.runningOnServer = true;
79
- let bridge = new RemultServerImplementation(new inProcessQueueHandler(options.queueStorage), options, dataProvider, serverCoreOptions);
79
+ let bridge = new RemultServerImplementation(new inProcessQueueHandler(options.queueStorage), options, dataProvider, serverCoreOptions, entitiesMetaData);
80
80
  return bridge;
81
81
  }
82
82
  ;
@@ -112,11 +112,12 @@ export class RemultAsyncLocalStorage {
112
112
  RemultAsyncLocalStorage.instance = new RemultAsyncLocalStorage(undefined);
113
113
  /* @internal*/
114
114
  export class RemultServerImplementation {
115
- constructor(queue, options, dataProvider, coreOptions) {
115
+ constructor(queue, options, dataProvider, coreOptions, entitiesMetaData) {
116
116
  this.queue = queue;
117
117
  this.options = options;
118
118
  this.dataProvider = dataProvider;
119
119
  this.coreOptions = coreOptions;
120
+ this.entitiesMetaData = entitiesMetaData;
120
121
  this.liveQueryStorage = new InMemoryLiveQueryStorage();
121
122
  this.runWithSerializedJsonContextData = async (jsonContextData, entityKey, what) => {
122
123
  for (const e of this.options.entities) {
@@ -154,6 +155,23 @@ export class RemultServerImplementation {
154
155
  if (options.subscriptionServer)
155
156
  this.subscriptionServer = options.subscriptionServer;
156
157
  }
158
+ withRemultPromise(request, what) {
159
+ return new Promise((resolve, error) => {
160
+ return this.withRemult(request, undefined, () => {
161
+ try {
162
+ what().then(resolve).catch(error);
163
+ }
164
+ catch (err) {
165
+ error(err);
166
+ }
167
+ });
168
+ });
169
+ }
170
+ getEntities() {
171
+ //TODO - consider using entitiesMetaData - but it may require making it all awaitable
172
+ var r = new Remult();
173
+ return this.options.entities.map(x => r.repo(x).metadata);
174
+ }
157
175
  ;
158
176
  getRouteImpl() {
159
177
  if (!this.routeImpl) {
@@ -249,6 +267,7 @@ export class RemultServerImplementation {
249
267
  //@ts-ignore
250
268
  .delete(this.process(async (c, req, res, orig) => dataApiFactory(c).delete(res, orig.params.id)));
251
269
  }
270
+ //runs with remult but without init request
252
271
  async runWithRemult(what) {
253
272
  let remult = new Remult();
254
273
  remult.liveQueryPublisher = new LiveQueryPublisher(() => remult.subscriptionServer, () => remult.liveQueryStorage, this.runWithSerializedJsonContextData);
@@ -337,7 +356,6 @@ export class RemultServerImplementation {
337
356
  });
338
357
  }
339
358
  openApiDoc(options) {
340
- let r = new Remult();
341
359
  if (!options.version)
342
360
  options.version = "1.0.0";
343
361
  let spec = {
@@ -386,9 +404,8 @@ export class RemultServerImplementation {
386
404
  return item;
387
405
  }
388
406
  };
389
- for (const e of this.options.entities) {
390
- let meta = r.repo(e).metadata;
391
- let key = getEntityKey(e);
407
+ for (const meta of this.getEntities()) {
408
+ let key = meta.key;
392
409
  let parameters = [];
393
410
  if (key) {
394
411
  let mutationKey = key;
@@ -1,6 +1,6 @@
1
1
  import { Remult } from './context';
2
- import { FindOptions, Repository } from './remult3';
3
- import { ErrorInfo } from './data-interfaces';
2
+ import type { FindOptions, Repository } from './remult3';
3
+ import type { ErrorInfo } from './data-interfaces';
4
4
  export declare class DataApi<T = any> {
5
5
  private repository;
6
6
  private remult;
@@ -13,7 +13,19 @@ export declare class SqlDatabase implements DataProvider {
13
13
  transaction(action: (dataProvider: DataProvider) => Promise<void>): Promise<void>;
14
14
  static rawFilter(build: CustomSqlFilterBuilderFunction): EntityFilter<any>;
15
15
  static filterToRaw<entityType>(repo: RepositoryOverloads<entityType>, condition: EntityFilter<entityType>, sqlCommand?: SqlCommandWithParameters): Promise<string>;
16
- static LogToConsole: boolean;
16
+ /**
17
+ * `false` _(default)_ - No logging
18
+ *
19
+ * `true` - to log all queries to the console
20
+ *
21
+ * `oneLiner` - to log all queries to the console as one line
22
+ *
23
+ * a `function` - to log all queries to the console as a custom format
24
+ */
25
+ static LogToConsole: boolean | 'oneLiner' | ((duration: number, query: string, args: Record<string, any>) => void);
26
+ /**
27
+ * Threshold in milliseconds for logging queries to the console.
28
+ */
17
29
  static durationThreshold: number;
18
30
  constructor(sql: SqlImplementation);
19
31
  private createdEntities;
@@ -92,12 +92,38 @@ export class SqlDatabase {
92
92
  return await b.resolveWhere();
93
93
  }
94
94
  }
95
+ /**
96
+ * `false` _(default)_ - No logging
97
+ *
98
+ * `true` - to log all queries to the console
99
+ *
100
+ * `oneLiner` - to log all queries to the console as one line
101
+ *
102
+ * a `function` - to log all queries to the console as a custom format
103
+ */
95
104
  SqlDatabase.LogToConsole = false;
105
+ /**
106
+ * Threshold in milliseconds for logging queries to the console.
107
+ */
96
108
  SqlDatabase.durationThreshold = 0;
109
+ const icons = new Map([
110
+ // CRUD
111
+ ['INSERT', '⚪'],
112
+ ['SELECT', '🔵'],
113
+ ['UPDATE', '🟣'],
114
+ ['DELETE', '🟤'],
115
+ // Additional
116
+ ['CREATE', '🟩'],
117
+ ['ALTER', '🟨'],
118
+ ['DROP', '🟥'],
119
+ ['TRUNCATE', '⬛'],
120
+ ['GRANT', '🟪'],
121
+ ['REVOKE', '🟫'],
122
+ ]);
97
123
  class LogSQLCommand {
98
- constructor(origin, allQueries) {
124
+ constructor(origin, logToConsole) {
99
125
  this.origin = origin;
100
- this.allQueries = allQueries;
126
+ this.logToConsole = logToConsole;
101
127
  this.args = {};
102
128
  }
103
129
  addParameterAndReturnSqlToken(val) {
@@ -109,10 +135,21 @@ class LogSQLCommand {
109
135
  try {
110
136
  let start = new Date();
111
137
  let r = await this.origin.execute(sql);
112
- if (this.allQueries) {
138
+ if (this.logToConsole !== false) {
113
139
  var d = new Date().valueOf() - start.valueOf();
114
140
  if (d > SqlDatabase.durationThreshold) {
115
- console.info({ query: sql, arguments: this.args, duration: d / 1000 });
141
+ const duration = d / 1000;
142
+ if (this.logToConsole === "oneLiner") {
143
+ const rawSql = sql.replace(/(\r\n|\n|\r|\t)/gm, ' ').replace(/ +/g, ' ').trim();
144
+ const first = rawSql.split(' ')[0].toUpperCase();
145
+ console.info(`${icons.get(first) || '💢'} (${(duration).toFixed(3)}) ${rawSql} ${JSON.stringify(this.args)}`);
146
+ }
147
+ else if (typeof this.logToConsole === "function") {
148
+ this.logToConsole(duration, sql, this.args);
149
+ }
150
+ else {
151
+ console.info({ query: sql, arguments: this.args, duration });
152
+ }
116
153
  }
117
154
  }
118
155
  return r;
@@ -327,6 +327,9 @@ export declare class EntityBase {
327
327
  isNew(): boolean;
328
328
  get $(): FieldsRef<this>;
329
329
  }
330
+ export declare class IdEntity extends EntityBase {
331
+ id: string;
332
+ }
330
333
  export declare class ControllerBase {
331
334
  protected remult: Remult;
332
335
  constructor(remult?: Remult);
@@ -1,3 +1,4 @@
1
+ import { __decorate, __metadata } from "tslib";
1
2
  import { CompoundIdField, LookupColumn, makeTitle } from '../column';
2
3
  import { allEntities, Remult, isBackend, queryConfig as queryConfig, setControllerSettings } from "../context";
3
4
  import { entityFilterToJson, Filter } from "../filter/filter-interfaces";
@@ -1842,6 +1843,12 @@ export class EntityBase {
1842
1843
  isNew() { return this._.isNew(); }
1843
1844
  get $() { return this._.fields; }
1844
1845
  }
1846
+ export class IdEntity extends EntityBase {
1847
+ }
1848
+ __decorate([
1849
+ Fields.uuid(),
1850
+ __metadata("design:type", String)
1851
+ ], IdEntity.prototype, "id", void 0);
1845
1852
  export class ControllerBase {
1846
1853
  constructor(remult) {
1847
1854
  this.remult = remult || defaultRemult;
@@ -1,5 +1,4 @@
1
- import { EntityBase } from "../remult3";
2
- import { IdEntity } from "../id-entity";
1
+ import { EntityBase, IdEntity } from "../remult3";
3
2
  export declare class stam extends EntityBase {
4
3
  id: number;
5
4
  title: string;
@@ -1,6 +1,6 @@
1
1
  import { __decorate, __metadata } from "tslib";
2
2
  import { DataApi } from "../data-api";
3
- import { Fields, Entity, EntityBase, Field } from "../remult3";
3
+ import { Fields, Entity, EntityBase, Field, IdEntity } from "../remult3";
4
4
  import { c } from "../tests/c";
5
5
  import { Done } from "../tests/Done";
6
6
  import { h } from "../tests/h";
@@ -17,7 +17,6 @@ import { entityForrawFilter1 } from "../tests/entityForCustomFilter";
17
17
  import { entityWithValidationsOnColumn } from "../tests/entityWithValidationsOnColumn";
18
18
  import { Validators } from "../validators";
19
19
  import { Status } from "../tests/testModel/models";
20
- import { IdEntity } from "../id-entity";
21
20
  import { describeClass } from "../remult3/DecoratorReplacer";
22
21
  import { DataProviderLiveQueryStorage, LiveQueryStorageEntity } from "../../live-query/data-provider-live-query-storage";
23
22
  import { v4 as uuid } from 'uuid';
package/graphql.d.ts CHANGED
@@ -1,5 +1,14 @@
1
- import { RemultExpressServer } from "./remult-express";
2
- export declare function remultGraphql(api: RemultExpressServer): {
3
- rootValue: {};
4
- schema: string;
1
+ import { Remult } from './index';
2
+ import type { ClassType } from './classType';
3
+ export declare function remultGraphql(options: {
4
+ removeComments?: boolean;
5
+ entities: ClassType<any>[];
6
+ getRemultFromRequest?: (req: any) => Remult;
7
+ }): {
8
+ resolvers: {
9
+ Query: Record<string, unknown>;
10
+ Mutation: Record<string, unknown>;
11
+ };
12
+ rootValue: Record<string, any>;
13
+ typeDefs: string;
5
14
  };