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