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/graphql.js CHANGED
@@ -1,148 +1,689 @@
1
- import { Remult } from ".";
2
- import { allEntities } from "./src/context";
3
- import { DataApi } from "./src/data-api";
4
- export function remultGraphql(api) {
5
- let r = new Remult();
6
- let types = [];
7
- let filterTypes = '';
8
- let query = '';
9
- let root = {};
10
- function getType(key) {
1
+ import { DataApi } from './src/data-api';
2
+ import { Remult, remult } from './index';
3
+ const v2ConnectionAndPagination = false;
4
+ const andImplementation = false;
5
+ let _removeComments = false;
6
+ export function remultGraphql(options) {
7
+ if (!options.getRemultFromRequest) {
8
+ options.getRemultFromRequest = () => remult;
9
+ }
10
+ const { removeComments } = {
11
+ removeComments: false,
12
+ ...options,
13
+ };
14
+ if (removeComments) {
15
+ _removeComments = true;
16
+ }
17
+ const entities = (() => {
18
+ const remult = new Remult();
19
+ return options.entities?.map(x => remult.repo(x).metadata) || [];
20
+ })();
21
+ const types = [];
22
+ const root = {};
23
+ const resolversQuery = {};
24
+ const resolversMutation = {};
25
+ const resolvers = { Query: resolversQuery, Mutation: resolversMutation };
26
+ function upsertTypes(key, kind = 'type', order = 0) {
11
27
  let t = types.find(t => t.key === key);
12
- if (!t)
13
- types.push((t = ({ fields: "", key, moreFields: "", resultProcessors: [] })));
28
+ if (!t) {
29
+ types.push((t = {
30
+ key,
31
+ kind,
32
+ fields: [],
33
+ query: {
34
+ orderBy: [],
35
+ whereType: [],
36
+ whereTypeSubFields: [],
37
+ resultProcessors: [],
38
+ },
39
+ mutation: {
40
+ create: {},
41
+ update: {},
42
+ delete: {},
43
+ },
44
+ order,
45
+ }));
46
+ if (kind === 'type_impl_node') {
47
+ t.fields.push({ ...argNodeId, order: 111 });
48
+ }
49
+ }
14
50
  return t;
15
51
  }
16
- for (const e of allEntities) {
17
- let meta = r.repo(e).metadata;
18
- let filterFields = '';
19
- let key = meta.key;
20
- const t = getType(key);
21
- let q = "\n\t" + key + "(options: options, filter:" + key + "Filter): [" + key + "]";
22
- if (key) {
23
- for (const f of meta.fields) {
24
- {
25
- let type = "String";
26
- switch (f.valueType) {
27
- case Boolean:
28
- type = "Boolean";
29
- break;
30
- case Number:
31
- {
32
- if (f.valueConverter?.fieldTypeInDb == 'integer')
33
- type = "Int";
34
- else
35
- type = "Float";
36
- }
37
- break;
38
- }
39
- if (allEntities.includes(f.valueType)) {
40
- const refKey = r.repo(f.valueType).metadata.key;
41
- t.fields += "\n\t" + f.key + ":" + refKey;
42
- t.resultProcessors.push(r => {
43
- const val = r[f.key];
44
- r[f.key] = async (args, req, gqlInfo) => {
45
- const queryResult = await root[refKey]({ ...args.filter, filter: { id: val }, options: { limit: 1 } }, req, gqlInfo);
46
- if (queryResult.length > 0)
47
- return queryResult[0];
48
- return null;
49
- };
50
- });
51
- let refT = getType(refKey);
52
- refT.moreFields += q;
53
- refT.resultProcessors.push(r => {
54
- const val = r.id;
55
- r[key] = async (args, req, gqlInfo) => {
56
- return await root[key]({ filter: { ...args.filter, [f.key]: val }, options: args.options }, req, gqlInfo);
57
- };
58
- });
59
- }
60
- else
61
- t.fields += "\n\t" + f.key + ":" + type;
62
- for (const operator of ["", "_ne"]) {
63
- filterFields += "\n\t" + f.key + operator + ":" + type;
64
- }
65
- if (f.valueType === String || f.valueType === Number)
66
- for (const operator of ["_gt", "_gte", "_lt", "_lte"]) {
67
- filterFields += "\n\t" + f.key + operator + ":" + type;
68
- }
69
- if (f.valueType === String)
70
- for (const operator of ["_st", "_contains"]) {
71
- filterFields += "\n\t" + f.key + operator + ":" + type;
72
- }
73
- if (f.allowNull)
74
- filterFields += "\n\t" + f.key + "_null:Boolean";
75
- filterFields += "\n\t" + f.key + "_in:[" + type + "]";
76
- }
52
+ // Where - GraphQL primitives
53
+ for (const whereType of ['String', 'Int', 'Float', 'Boolean', 'ID']) {
54
+ const currentWhere = upsertTypes(`Where${whereType}`, 'input', 20);
55
+ const currentWhereNullable = upsertTypes(`Where${whereType}Nullable`, 'input', 20);
56
+ // For everyone
57
+ const operatorType = ['eq', 'ne'];
58
+ const operatorTypeArray = ['in', 'nin'];
59
+ for (const operator of [...operatorType, ...operatorTypeArray]) {
60
+ const field = {
61
+ key: operator,
62
+ value: operatorTypeArray.includes(operator) ? `[${whereType}!]` : whereType,
63
+ };
64
+ currentWhere.fields.push(field);
65
+ currentWhereNullable.fields.push(field);
66
+ }
67
+ // only for specific types
68
+ if (whereType === 'String' || whereType === 'Int' || whereType === 'Float') {
69
+ for (const operator of ['gt', 'gte', 'lt', 'lte']) {
70
+ const field = {
71
+ key: operator,
72
+ value: whereType,
73
+ };
74
+ currentWhere.fields.push(field);
75
+ currentWhereNullable.fields.push(field);
77
76
  }
78
- filterTypes += "input " + key + "Filter{" + filterFields + "\n\tOR:[" + key + "Filter]\n}\n";
79
- query += q;
80
- root[key] = async (arg1, req, a) => {
81
- const { options, filter } = arg1;
82
- return new Promise(async (res, error) => {
83
- //TODO - consider this with remult usage when working with other servers
84
- api.withRemult(req, undefined, async () => {
85
- let remult = await api.getRemult(req);
86
- let repo = remult.repo(e);
87
- let dApi = new DataApi(repo, remult);
77
+ }
78
+ if (whereType === 'String') {
79
+ for (const operator of ['st']) {
80
+ const field = {
81
+ key: operator,
82
+ value: whereType,
83
+ };
84
+ currentWhere.fields.push(field);
85
+ currentWhereNullable.fields.push(field);
86
+ }
87
+ }
88
+ // add only for nullable
89
+ currentWhereNullable.fields.push({
90
+ key: 'null',
91
+ value: 'Boolean',
92
+ });
93
+ }
94
+ const root_query = upsertTypes('Query', 'type', -10);
95
+ root_query.comment = `Represents all Remult entities.`;
96
+ const argId = { key: `id`, value: `ID!` };
97
+ const nodeIdKey = 'nodeId';
98
+ const argNodeId = {
99
+ key: nodeIdKey,
100
+ value: `ID!`,
101
+ comment: `The globally unique \`ID\` _(_typename:id)_`,
102
+ };
103
+ const argClientMutationId = { key: 'clientMutationId', value: `String` };
104
+ for (const meta of entities) {
105
+ const orderByFields = [];
106
+ const key = meta.key;
107
+ const currentType = upsertTypes(getMetaType(meta), 'type_impl_node');
108
+ if (key) {
109
+ const createResultPromise = (work) => {
110
+ return async (arg1, req) => {
111
+ return new Promise((res, error) => {
88
112
  let result;
89
113
  let err;
90
- await dApi.getArray({
91
- success: x => result = x.map(y => {
92
- t.resultProcessors.forEach(z => z(y));
93
- return y;
94
- }),
95
- created: undefined,
96
- deleted: undefined,
97
- error: x => err = x,
98
- forbidden: () => err = 'forbidden',
99
- notFound: () => err = 'not found',
100
- progress: undefined
101
- }, {
102
- get: key => {
103
- if (options)
104
- switch (key) {
105
- case "_limit":
106
- return options.limit;
107
- case "_page":
108
- return options.page;
109
- case "_sort":
110
- return options.sort;
111
- case "_order":
112
- return options.order;
113
- }
114
+ const response = {
115
+ success: (x) => {
116
+ err = 'success not handled';
117
+ },
118
+ created: () => {
119
+ err = 'created not handled';
120
+ },
121
+ deleted: () => {
122
+ err = 'deleted not handled';
123
+ },
124
+ error: (x) => (err = x),
125
+ forbidden: () => (err = 'forbidden'),
126
+ notFound: () => (err = 'not found'),
127
+ progress: () => { },
128
+ };
129
+ work(response, x => (result = x), arg1, req)
130
+ .then(() => {
131
+ if (err) {
132
+ error(err);
133
+ return;
114
134
  }
115
- }, filter);
116
- if (err) {
117
- error(err);
118
- return;
119
- }
120
- res(result);
135
+ res(result);
136
+ })
137
+ .catch(err => error(err));
121
138
  });
139
+ };
140
+ };
141
+ const handleRequestWithDataApiContext = (work) => {
142
+ return createResultPromise(async (response, setResult, arg1, req) => {
143
+ const remult = options.getRemultFromRequest(req);
144
+ const repo = remult.repo(meta.entityType);
145
+ const dApi = new DataApi(repo, remult);
146
+ await work(dApi, response, setResult, arg1, meta);
122
147
  });
123
148
  };
149
+ const queryArgsConnection = [
150
+ {
151
+ key: 'limit',
152
+ value: 'Int',
153
+ comment: `
154
+ For **page by page** pagination.
155
+ Limit the number of result.
156
+ _Side note: \`Math.ceil(totalCount / limit)\` to determine how many pages there are._`,
157
+ },
158
+ {
159
+ key: 'page',
160
+ value: 'Int',
161
+ comment: `
162
+ For **page by page** pagination.
163
+ Select a dedicated page.`,
164
+ },
165
+ { key: 'orderBy', value: `${key}OrderBy`, comment: `Remult sorting options` },
166
+ { key: 'where', value: `${key}Where`, comment: `Remult filtering options` },
167
+ ];
168
+ if (v2ConnectionAndPagination) {
169
+ queryArgsConnection.push({
170
+ key: 'first',
171
+ value: 'Int',
172
+ comment: `
173
+ For **forward cursor** pagination
174
+ Takes the \`first\`: \`n\` elements from the list.`,
175
+ }, {
176
+ key: 'after',
177
+ value: 'String',
178
+ comment: `
179
+ For **forward cursor** pagination
180
+ \`after\` this \`cursor\`.`,
181
+ }, {
182
+ key: 'last',
183
+ value: 'Int',
184
+ comment: `
185
+ For **backward cursor** pagination
186
+ Takes the \`last\`: \`n\` elements from the list.`,
187
+ }, {
188
+ key: 'before',
189
+ value: 'String',
190
+ comment: `
191
+ For **backward cursor** pagination
192
+ \`before\` this \`cursor\`.`,
193
+ });
194
+ }
195
+ const getSingleEntityKey = toCamelCase(getMetaType(meta));
196
+ root_query.fields.push({
197
+ key: getSingleEntityKey,
198
+ args: [argId],
199
+ value: `${getMetaType(meta)}`,
200
+ comment: `Get \`${getMetaType(meta)}\` entity`,
201
+ });
202
+ root[getSingleEntityKey] = handleRequestWithDataApiContext(async (dApi, response, setResult, arg1, req) => {
203
+ await dApi.get({
204
+ ...response,
205
+ success: y => {
206
+ currentType.query.resultProcessors.forEach(z => z(y));
207
+ setResult(y);
208
+ },
209
+ }, arg1.id);
210
+ });
211
+ resolversQuery[getSingleEntityKey] = (origItem, args, req, gqlInfo) => root[getSingleEntityKey](args, req, gqlInfo);
212
+ // Connection (v1 items, v2 edges)
213
+ const connectionKey = `${getMetaType(meta)}Connection`;
214
+ root_query.fields.push({
215
+ key,
216
+ args: queryArgsConnection,
217
+ value: connectionKey,
218
+ comment: `List all \`${getMetaType(meta)}\` entity (with pagination, sorting and filtering)`,
219
+ });
220
+ const connection = upsertTypes(connectionKey, 'type');
221
+ const totalCountKey = 'totalCount';
222
+ connection.fields.push({
223
+ key: totalCountKey,
224
+ value: 'Int!',
225
+ });
226
+ if (v2ConnectionAndPagination) {
227
+ connection.fields.push({
228
+ key: 'edges',
229
+ value: `[${getMetaType(meta)}Edge!]!`,
230
+ });
231
+ }
232
+ const itemsKey = 'items';
233
+ connection.fields.push({
234
+ key: itemsKey,
235
+ value: `[${getMetaType(meta)}!]!`,
236
+ });
237
+ if (v2ConnectionAndPagination) {
238
+ connection.fields.push({
239
+ key: 'pageInfo',
240
+ value: `PageInfo!`,
241
+ });
242
+ }
243
+ if (v2ConnectionAndPagination) {
244
+ const edge = upsertTypes(`${getMetaType(meta)}Edge`, 'type');
245
+ edge.fields.push({
246
+ key: 'node',
247
+ value: `${getMetaType(meta)}!`,
248
+ });
249
+ const cursorKey = 'cursor';
250
+ edge.fields.push({
251
+ key: cursorKey,
252
+ value: `String!`,
253
+ });
254
+ }
255
+ root[key] = handleRequestWithDataApiContext(async (dApi, response, setResult, arg1, meta) => {
256
+ setResult({
257
+ [itemsKey]: createResultPromise(async (response, setResult) => {
258
+ await dApi.getArray({
259
+ ...response,
260
+ success: (x) => {
261
+ setResult(x.map((y) => {
262
+ currentType.query.resultProcessors.forEach(z => z(y));
263
+ return y;
264
+ }));
265
+ },
266
+ }, {
267
+ get: bridgeQueryOptionsToDataApiGet(arg1),
268
+ }, translateWhereToRestBody(meta.fields, arg1));
269
+ }),
270
+ [totalCountKey]: createResultPromise(async (response, setResult) => {
271
+ await dApi.count({
272
+ ...response,
273
+ success: x => setResult(x.count),
274
+ }, {
275
+ get: bridgeQueryOptionsToDataApiGet(arg1),
276
+ }, translateWhereToRestBody(meta.fields, arg1));
277
+ }),
278
+ });
279
+ });
280
+ resolversQuery[key] = (origItem, args, req, gqlInfo) => {
281
+ return root[key](args, req, gqlInfo);
282
+ };
283
+ // Mutation
284
+ const root_mutation = upsertTypes('Mutation', 'type', -9);
285
+ const checkCanExist = (rule) => rule !== false && !(rule === undefined && (meta.options.allowApiCrud === false || meta.options.allowApiCrud === undefined));
286
+ if (checkCanExist(meta.options.allowApiInsert)) {
287
+ // create
288
+ const createInput = `Create${getMetaType(meta)}Input`;
289
+ const createPayload = `Create${getMetaType(meta)}Payload`;
290
+ const createResolverKey = `create${getMetaType(meta)}`;
291
+ root_mutation.fields.push({
292
+ key: createResolverKey,
293
+ args: [{ key: 'input', value: `${createInput}!` }, argClientMutationId],
294
+ value: `${createPayload}`,
295
+ comment: `Create a new \`${getMetaType(meta)}\``,
296
+ });
297
+ currentType.mutation.create.input = upsertTypes(createInput, 'input');
298
+ currentType.mutation.create.payload = upsertTypes(createPayload);
299
+ currentType.mutation.create.payload.fields.push({
300
+ key: `${toCamelCase(getMetaType(meta))}`,
301
+ value: `${getMetaType(meta)}`,
302
+ }, argClientMutationId);
303
+ root[createResolverKey] = handleRequestWithDataApiContext(async (dApi, response, setResult, arg1, req) => {
304
+ await dApi.post({
305
+ ...response,
306
+ created: y => {
307
+ currentType.query.resultProcessors.forEach(z => z(y));
308
+ setResult({
309
+ [toCamelCase(getMetaType(meta))]: y,
310
+ });
311
+ },
312
+ }, arg1.input);
313
+ });
314
+ resolversMutation[createResolverKey] = (origItem, args, req, gqlInfo) => root[createResolverKey](args, req, gqlInfo);
315
+ }
316
+ if (checkCanExist(meta.options.allowApiUpdate)) {
317
+ // update
318
+ const updateInput = `Update${getMetaType(meta)}Input`;
319
+ const updatePayload = `Update${getMetaType(meta)}Payload`;
320
+ const updateResolverKey = `update${getMetaType(meta)}`;
321
+ root_mutation.fields.push({
322
+ key: updateResolverKey,
323
+ args: [argId, { key: 'patch', value: `${updateInput}!` }, argClientMutationId],
324
+ value: `${updatePayload}`,
325
+ comment: `Update a \`${getMetaType(meta)}\``,
326
+ });
327
+ currentType.mutation.update.input = upsertTypes(updateInput, 'input');
328
+ currentType.mutation.update.payload = upsertTypes(updatePayload);
329
+ currentType.mutation.update.payload.fields.push({
330
+ key: `${toCamelCase(getMetaType(meta))}`,
331
+ value: `${getMetaType(meta)}`,
332
+ }, argClientMutationId);
333
+ root[updateResolverKey] = handleRequestWithDataApiContext(async (dApi, response, setResult, arg1, req) => {
334
+ await dApi.put({
335
+ ...response,
336
+ success: y => {
337
+ currentType.query.resultProcessors.forEach(z => z(y));
338
+ setResult({
339
+ [toCamelCase(getMetaType(meta))]: y,
340
+ });
341
+ },
342
+ }, arg1.id, arg1.patch);
343
+ });
344
+ resolversMutation[updateResolverKey] = (origItem, args, req, gqlInfo) => root[updateResolverKey](args, req, gqlInfo);
345
+ }
346
+ if (checkCanExist(meta.options.allowApiDelete)) {
347
+ // delete
348
+ const deletePayload = `Delete${getMetaType(meta)}Payload`;
349
+ const deleteResolverKey = `delete${getMetaType(meta)}`;
350
+ root_mutation.fields.push({
351
+ key: deleteResolverKey,
352
+ args: [argId, argClientMutationId],
353
+ value: `${deletePayload}`,
354
+ comment: `Delete a \`${getMetaType(meta)}\``,
355
+ });
356
+ currentType.mutation.delete.payload = upsertTypes(deletePayload);
357
+ const deletedResultKey = `id`;
358
+ currentType.mutation.delete.payload.fields.push({
359
+ key: deletedResultKey,
360
+ value: 'ID',
361
+ }, argClientMutationId);
362
+ root[deleteResolverKey] = handleRequestWithDataApiContext(async (dApi, response, setResult, arg1, req) => {
363
+ await dApi.delete({
364
+ ...response,
365
+ deleted: () => {
366
+ setResult({ [deletedResultKey]: arg1.id });
367
+ },
368
+ }, arg1.id);
369
+ });
370
+ resolversMutation[deleteResolverKey] = (origItem, args, req, gqlInfo) => root[deleteResolverKey](args, req, gqlInfo);
371
+ }
372
+ const whereTypeFields = [];
373
+ for (const f of meta.fields) {
374
+ if (f.options.includeInApi === false)
375
+ continue;
376
+ let type = 'String';
377
+ switch (f.valueType) {
378
+ case Boolean:
379
+ type = 'Boolean';
380
+ break;
381
+ case Number:
382
+ {
383
+ if (f.valueConverter?.fieldTypeInDb === 'integer' ||
384
+ f.valueConverter?.fieldTypeInDb === 'autoincrement')
385
+ type = 'Int';
386
+ else
387
+ type = 'Float';
388
+ }
389
+ break;
390
+ }
391
+ const ref = entities.find((i) => i.entityType === f.valueType);
392
+ currentType.query.resultProcessors.push(r => {
393
+ r[nodeIdKey] = () => getMetaType(meta) + ':' + meta.idMetadata.getId(r);
394
+ });
395
+ if (ref !== undefined) {
396
+ // will do: Task.category
397
+ currentType.fields.push({
398
+ key: f.key,
399
+ value: `${getMetaType(ref)}${f.allowNull ? '' : '!'}`,
400
+ comment: f.caption,
401
+ });
402
+ const refKey = ref.key;
403
+ currentType.query.resultProcessors.push(r => {
404
+ const val = r[f.key];
405
+ if (val === null || val === undefined)
406
+ return null;
407
+ r[f.key] = async (args, req, gqlInfo) => {
408
+ const queryResult = await (await root[refKey]({
409
+ ...args.where,
410
+ where: { id: { eq: val } },
411
+ options: { limit: 1 },
412
+ }, req, gqlInfo)).items();
413
+ if (queryResult.length > 0)
414
+ return queryResult[0];
415
+ return null;
416
+ };
417
+ });
418
+ // will do: Category.tasks
419
+ const refT = upsertTypes(getMetaType(ref), 'type_impl_node');
420
+ refT.fields.push({
421
+ key,
422
+ args: queryArgsConnection,
423
+ value: connectionKey,
424
+ order: 10,
425
+ comment: `List all \`${getMetaType(meta)}\` of \`${refKey}\``,
426
+ });
427
+ refT.query.resultProcessors.push(r => {
428
+ const val = r.id;
429
+ r[key] = async (args, req, gqlInfo) => {
430
+ return await root[key]({
431
+ where: { ...args.where, [f.key]: { eq: val } },
432
+ options: { ...args.limit, ...args.page, ...args.orderBy },
433
+ }, req, gqlInfo);
434
+ };
435
+ });
436
+ }
437
+ else {
438
+ currentType.fields.push({
439
+ key: f.key,
440
+ value: `${type}${f.allowNull ? '' : '!'}`,
441
+ comment: f.caption,
442
+ });
443
+ }
444
+ // sorting
445
+ if (!f.isServerExpression)
446
+ orderByFields.push(`${f.key}: OrderByDirection`);
447
+ // helper
448
+ const it_is_not_at_ref = ref === undefined;
449
+ // where
450
+ if (it_is_not_at_ref && !f.isServerExpression) {
451
+ whereTypeFields.push(`${f.key}: Where${type}${f.allowNull ? 'Nullable' : ''}`);
452
+ }
453
+ const includeInUpdateOrInsert = f.options.allowApiUpdate !== false;
454
+ const updateType = it_is_not_at_ref ? type : 'ID';
455
+ if (includeInUpdateOrInsert) {
456
+ // create
457
+ if (currentType.mutation.create.input)
458
+ currentType.mutation.create.input.fields.push({
459
+ key: f.key,
460
+ value: updateType,
461
+ });
462
+ // update
463
+ if (currentType.mutation.update.input)
464
+ currentType.mutation.update.input.fields.push({
465
+ key: f.key,
466
+ value: updateType,
467
+ });
468
+ }
469
+ }
470
+ currentType.query.orderBy.push(blockFormat({
471
+ prefix: `input ${key}OrderBy`,
472
+ data: orderByFields,
473
+ comment: `OrderBy options for \`${key}\``,
474
+ }));
475
+ whereTypeFields.push(`OR: [${key}Where!]`);
476
+ if (andImplementation)
477
+ whereTypeFields.push(`AND: [${key}Where!]`);
478
+ currentType.query.whereType.push(blockFormat({
479
+ prefix: `input ${key}Where`,
480
+ data: whereTypeFields,
481
+ comment: `Where options for \`${key}\``,
482
+ }));
124
483
  }
125
484
  }
126
- if (query.length > 0) {
127
- query = `type Query {${query}
128
- }`;
485
+ // Add the node interface at the end
486
+ const nodeKey = 'node';
487
+ root_query.fields.push({
488
+ key: nodeKey,
489
+ args: [argNodeId],
490
+ value: `Node`,
491
+ comment: `Grab any Remult entity given it's globally unique \`ID\``,
492
+ });
493
+ if (v2ConnectionAndPagination) {
494
+ const pageInfo = upsertTypes('PageInfo', 'type', 30);
495
+ pageInfo.fields.push({ key: 'endCursor', value: 'String!' });
496
+ pageInfo.fields.push({ key: 'hasNextPage', value: 'Boolean!' });
497
+ pageInfo.fields.push({ key: 'hasPreviousPage', value: 'Boolean!' });
498
+ pageInfo.fields.push({ key: 'startCursor', value: 'String!' });
129
499
  }
500
+ resolversQuery[nodeKey] = (origItem, args, req, gqlInfo) => root[nodeKey](args, req, gqlInfo);
501
+ root[nodeKey] = async (args, req, gqlInfo) => {
502
+ const nodeId = args.nodeId;
503
+ const sp = nodeId.split(':');
504
+ const r = await root[toCamelCase(sp[0])]({
505
+ id: sp[1],
506
+ }, req, gqlInfo);
507
+ r.__typename = sp[0];
508
+ return r;
509
+ };
510
+ const orderByDirection = upsertTypes('OrderByDirection', 'enum', 30);
511
+ orderByDirection.comment = `Determines the order of returned elements`;
512
+ orderByDirection.fields.push({
513
+ key: 'ASC',
514
+ value: { Enum: true },
515
+ comment: 'Sort data in ascending order',
516
+ });
517
+ orderByDirection.fields.push({
518
+ key: 'DESC',
519
+ value: { Enum: true },
520
+ comment: 'Sort data in descending order',
521
+ });
522
+ const nodeInterface = upsertTypes('Node', 'interface', 31);
523
+ nodeInterface.comment = `Node interface of remult entities (eg: nodeId: \`Task:1\` so \`__typename:id\`)`;
524
+ nodeInterface.fields.push(argNodeId);
130
525
  return {
526
+ resolvers,
131
527
  rootValue: root,
132
- schema: `${types.map(({ key, fields, moreFields }) => "type " + key + "{" + fields + moreFields + "\n}\n").join('')}
133
- ${query}
134
- ${filterTypes}
135
- input options{
136
- limit:Int
137
- page:Int
138
- sort:String
139
- order:String
528
+ typeDefs: `${types
529
+ .sort((a, b) => (a.order ? a.order : 0) - (b.order ? b.order : 0))
530
+ .map(({ key, kind, fields, query, comment }) => {
531
+ const { orderBy, whereType, whereTypeSubFields } = query;
532
+ let prefix = `${kind} ${key}`;
533
+ if (kind === 'type_impl_node') {
534
+ prefix = `type ${key} implements Node`;
535
+ }
536
+ const type = blockFormat({
537
+ prefix,
538
+ data: fields
539
+ .sort((a, b) => (a.order ? a.order : 0) - (b.order ? b.order : 0))
540
+ .map(field => fieldFormat(field)),
541
+ comment: comment ?? `The ${kind} for \`${key}\``,
542
+ });
543
+ const orderByStr = orderBy.length > 0 ? `\n\n${orderBy.join('\n\n')}` : ``;
544
+ const whereTypeStr = whereType.length > 0 ? `\n\n${whereType.join('\n\n')}` : ``;
545
+ const whereTypeSubFieldsStr = whereTypeSubFields.length > 0 ? `\n\n${whereTypeSubFields.join('\n\n')}` : ``;
546
+ return `${type}${orderByStr}${whereTypeStr}${whereTypeSubFieldsStr}`;
547
+ })
548
+ .join(`\n\n`)}
549
+ `,
550
+ };
551
+ }
552
+ // For cursor pagination (v2)
553
+ // function checkPaginationArgs(args: any) {
554
+ // let paginationPage = !!args.limit ? 1 : 0
555
+ // paginationPage += !!args.page ? 1 : 0
556
+ // let paginationCursor = !!args.first ? 1 : 0
557
+ // paginationCursor += !!args.after ? 1 : 0
558
+ // paginationCursor += !!args.last ? 1 : 0
559
+ // paginationCursor += !!args.before ? 1 : 0
560
+ // if (paginationPage > 0 && paginationCursor > 0) {
561
+ // throw new GraphQLError(
562
+ // `You can't use \`limit,page\` and \`first,after,last,before\` at the same time. Choose your pagination style.`,
563
+ // )
564
+ // }
565
+ // }
566
+ function blockFormat(obj) {
567
+ if (obj.data.length === 0) {
568
+ return ``;
569
+ }
570
+ const str = `${obj.prefix} {
571
+ ${obj.data.join('\n ')}
572
+ }`;
573
+ let commentsStr = `"""
574
+ ${obj.comment}
575
+ """
576
+ `;
577
+ if (_removeComments) {
578
+ commentsStr = ``;
579
+ }
580
+ return `${commentsStr}${str}`;
140
581
  }
141
- `
582
+ function argsFormat(args) {
583
+ if (args) {
584
+ return `(${args
585
+ .map(arg => {
586
+ let strComment = `
587
+ """
588
+ ${arg.comment}
589
+ """
590
+ `;
591
+ if (_removeComments || !arg.comment) {
592
+ strComment = ``;
593
+ }
594
+ if (strComment) {
595
+ return `${strComment} ${arg.key}: ${arg.value}
596
+ `;
597
+ }
598
+ return `${arg.key}: ${arg.value}`;
599
+ })
600
+ .join(', ')})`;
601
+ }
602
+ return ``;
603
+ }
604
+ function fieldFormat(field) {
605
+ // First, the comment
606
+ let strComment = `"""
607
+ ${field.comment}
608
+ """
609
+ `;
610
+ if (_removeComments || !field.comment) {
611
+ strComment = ``;
612
+ }
613
+ let key_value = `${field.key}${field.args ? `${argsFormat(field.args)}` : ``}: ${field.value}`;
614
+ // It's an enum
615
+ if (typeof field.value === 'object') {
616
+ key_value = `${field.key}`;
617
+ }
618
+ return `${strComment} ${key_value}`;
619
+ }
620
+ function getMetaType(entityMeta) {
621
+ return entityMeta.entityType.name;
622
+ }
623
+ function toCamelCase(str) {
624
+ return str
625
+ .split('')
626
+ .map((c, i) => (i === 0 ? c.toLowerCase() : c))
627
+ .join('');
628
+ }
629
+ function bridgeQueryOptionsToDataApiGet(arg1) {
630
+ const { limit, page, orderBy, where } = arg1;
631
+ return (key) => {
632
+ if (limit && key === '_limit') {
633
+ return limit;
634
+ }
635
+ if (page && key === '_page') {
636
+ return page;
637
+ }
638
+ if (orderBy) {
639
+ if (key === '_sort') {
640
+ const sort_keys = [];
641
+ Object.keys(orderBy).forEach(sort_key => {
642
+ sort_keys.push(sort_key);
643
+ });
644
+ if (sort_keys.length > 0) {
645
+ return sort_keys.join(',');
646
+ }
647
+ }
648
+ else if (key === '_order') {
649
+ const sort_directions = [];
650
+ Object.keys(orderBy).forEach(sort_key => {
651
+ const direction = orderBy[sort_key].toLowerCase();
652
+ sort_directions.push(direction);
653
+ });
654
+ if (sort_directions.length > 0) {
655
+ return sort_directions.join(',');
656
+ }
657
+ }
658
+ }
142
659
  };
143
660
  }
144
- //TODO - filter doesn't work since we changed id_eq to be id.eq in rest, but graphql doesn't allow it.
145
- //TODO - the list of entities, is based on allEntities - that's wrong - it should be based on the api entities - or a separate array.
146
- //TODO - it's currently only planned for express server - it uses it's 'withRemult' that doesn't exist in all other servers.
147
- //TODO - it doesn't support mutations
148
- //TODO - it doesn't support backend methods
661
+ //@internal
662
+ export function translateWhereToRestBody(fields, { where }) {
663
+ if (!where)
664
+ return undefined;
665
+ const result = {};
666
+ for (const field of fields) {
667
+ if (field.includedInApi === false)
668
+ continue;
669
+ const condition = where[field.key];
670
+ if (condition) {
671
+ const tr = (key, what) => {
672
+ const val = condition[key];
673
+ if (val != undefined)
674
+ what(val);
675
+ };
676
+ for (const op of ['gt', 'gte', 'lt', 'lte', 'ne', 'in']) {
677
+ tr(op, val => (result[field.key + '.' + op] = val));
678
+ }
679
+ tr('nin', x => (result[field.key + '.ne'] = x));
680
+ tr('eq', x => (result[field.key] = x));
681
+ }
682
+ }
683
+ if (where.OR) {
684
+ result.OR = where.OR.map((where) => translateWhereToRestBody(fields, { where }));
685
+ }
686
+ return result;
687
+ }
688
+ //[ ] - when fetching a related entity - make sure it's include in api is true in the specific context.
689
+ //[ ] - test graphql where in entity definitions there is a reference to static remult