-
Notifications
You must be signed in to change notification settings - Fork 5
/
customVariables.js
340 lines (314 loc) · 9.37 KB
/
customVariables.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import set from "lodash/set";
import omit from "lodash/omit";
import {
GET_ONE,
GET_LIST,
GET_MANY,
GET_MANY_REFERENCE,
DELETE,
CREATE,
UPDATE,
UPDATE_MANY,
DELETE_MANY,
} from "./fetchActions";
const SPLIT_TOKEN = "#";
import getFinalType from "./getFinalType";
const buildGetListVariables =
(introspectionResults) => (resource, aorFetchType, params) => {
const result = {};
let { filter: filterObj = {} } = params;
const { customFilters = [] } = params;
const distinctOnField = "distinct_on";
/** Setting "distinct_on" to be the `filters` object attribute to be used inside RA
* and setting to a `distinct_on` variable
* and removing from the filter object
*/
const { distinct_on = "" } = filterObj;
filterObj = omit(filterObj, [distinctOnField]);
/**
* Nested entities are parsed by CRA, which returns a nested object
* { 'level1': {'level2': 'test'}}
* instead of { 'level1.level2': 'test'}
* That's why we use a HASH for properties, when we declared nested stuff at CRA:
* level1#level2@_ilike
*/
/**
keys with comma separated values
{
'title@ilike,body@like,authors@similar': 'test',
'col1@like,col2@like': 'val'
}
*/
const orFilterKeys = Object.keys(filterObj).filter((e) => e.includes(","));
/**
format filters
{
'title@ilike': 'test',
'body@like': 'test',
'authors@similar': 'test',
'col1@like': 'val',
'col2@like': 'val'
}
*/
const orFilterObj = orFilterKeys.reduce((acc, commaSeparatedKey) => {
const keys = commaSeparatedKey.split(",");
return {
...acc,
...keys.reduce((acc2, key) => {
return {
...acc2,
[key]: filterObj[commaSeparatedKey],
};
}, {}),
};
}, {});
filterObj = omit(filterObj, orFilterKeys);
const makeNestedFilter = (obj, operation) => {
if (Object.keys(obj).length === 1) {
const [key] = Object.keys(obj);
return { [key]: makeNestedFilter(obj[key], operation) };
} else {
return { [operation]: obj };
}
};
const filterReducer = (obj) => (acc, key) => {
let filter;
if (key === "ids") {
filter = { id: { _in: obj["ids"] } };
} else if (Array.isArray(obj[key])) {
filter = { [key]: { _in: obj[key] } };
} else if (obj[key] && obj[key].format === "hasura-raw-query") {
filter = { [key]: obj[key].value || {} };
} else {
let [keyName, operation = ""] = key.split("@");
let operator;
const field = resource.type.fields.find((f) => f.name === keyName);
if (field) {
switch (getFinalType(field.type).name) {
case "String":
operation = operation || "_ilike";
operator = {
[operation]: operation.includes("like")
? `%${obj[key]}%`
: obj[key],
};
filter = set({}, keyName.split(SPLIT_TOKEN), operator);
break;
default:
operator = {
[operation]: operation.includes("like")
? `%${obj[key]}%`
: obj[key],
};
filter = set({}, keyName.split(SPLIT_TOKEN), {
[operation || "_eq"]: obj[key],
});
}
} else {
// Else block runs when the field is not found in Graphql schema.
// Most likely it's nested. If it's not, it's better to let
// Hasura fail with a message than silently fail/ignore it
operator = {
[operation || "_eq"]: operation.includes("like")
? `%${obj[key]}%`
: obj[key],
};
filter = set({}, keyName.split(SPLIT_TOKEN), operator);
}
}
return [...acc, filter];
};
const andFilters = Object.keys(filterObj)
.reduce(filterReducer(filterObj), customFilters)
.filter(Boolean);
const orFilters = Object.keys(orFilterObj)
.reduce(filterReducer(orFilterObj), [])
.filter(Boolean);
result["where"] = {
_and: andFilters,
...(orFilters.length && { _or: orFilters }),
};
if (params.pagination) {
result["limit"] = parseInt(params.pagination.perPage, 10);
result["offset"] = parseInt(
(params.pagination.page - 1) * params.pagination.perPage,
10
);
}
if (params.sort) {
result["order_by"] = set(
{},
params.sort.field,
params.sort.order.toLowerCase()
);
}
if (distinct_on) {
result["distinct_on"] = distinct_on;
}
return result;
};
/**
* Returns a reducer that converts the react-admin key-values to hasura-acceptable values
*
* Currently that means that dates should never be an empty string, but in the future that can be extended
* See https://github.com/marmelab/react-admin/pull/6199
*
*/
const typeAwareKeyValueReducer =
(introspectionResults, resource, params) => (acc, key) => {
const type = introspectionResults.types.find(
(t) => t.name === resource.type.name
);
const field = type.fields.find((t) => t.name === key);
const value =
field &&
field.type &&
field.type.name === "date" &&
params.data[key] === ""
? null
: params.data[key];
return resource.type.fields.some((f) => f.name === key)
? {
...acc,
[key]: value,
}
: acc;
};
const buildUpdateVariables =
(introspectionResults) => (resource, aorFetchType, params, queryType) => {
const reducer = typeAwareKeyValueReducer(
introspectionResults,
resource,
params
);
let permitted_fields = null;
const resource_name = resource.type.name;
if (resource_name) {
let inputType = introspectionResults.types.find(
(obj) => obj.name === `${resource_name}_set_input`
);
if (inputType) {
let inputTypeFields = inputType.inputFields;
if (inputTypeFields) {
permitted_fields = inputTypeFields.map((obj) => obj.name);
}
}
}
return Object.keys(params.data).reduce((acc, key) => {
// If hasura permissions do not allow a field to be updated like (id),
// we are not allowed to put it inside the variables
// RA passes the whole previous Object here
// https://github.com/marmelab/react-admin/issues/2414#issuecomment-428945402
// TODO: To overcome this permission issue,
// it would be better to allow only permitted inputFields from *_set_input INPUT_OBJECT
if (permitted_fields && !permitted_fields.includes(key)) return acc;
if (
params.previousData &&
params.data[key] === params.previousData[key]
) {
return acc;
}
return reducer(acc, key);
}, {});
};
const buildCreateVariables =
(introspectionResults) => (resource, aorFetchType, params, queryType) => {
const reducer = typeAwareKeyValueReducer(
introspectionResults,
resource,
params
);
return Object.keys(params.data).reduce(reducer, {});
};
const makeNestedTarget = (target, id) =>
// This simple example should make clear what this function does
// makeNestedTarget("a.b", 42)
// => { a: { b: { _eq: 42 } } }
target
.split(".")
.reverse()
.reduce(
(acc, key) => ({
[key]: acc,
}),
{ _eq: id }
);
const buildVariables =
(introspectionResults) => (resource, aorFetchType, params, queryType) => {
switch (aorFetchType) {
case GET_LIST:
return buildGetListVariables(introspectionResults)(
resource,
aorFetchType,
params,
queryType
);
case GET_MANY_REFERENCE: {
var built = buildGetListVariables(introspectionResults)(
resource,
aorFetchType,
params,
queryType
);
if (params.filter) {
return {
...built,
where: {
_and: [
...built["where"]["_and"],
makeNestedTarget(params.target, params.id),
],
},
};
}
return {
...built,
where: makeNestedTarget(params.target, params.id),
};
}
case GET_MANY:
case DELETE_MANY:
return {
where: { id: { _in: params.ids } },
};
case GET_ONE:
return {
where: { id: { _eq: params.id } },
limit: 1,
};
case DELETE:
return {
where: { id: { _eq: params.id } },
};
case CREATE:
return {
objects: buildCreateVariables(introspectionResults)(
resource,
aorFetchType,
params,
queryType
),
};
case UPDATE:
return {
_set: buildUpdateVariables(introspectionResults)(
resource,
aorFetchType,
params,
queryType
),
where: { id: { _eq: params.id } },
};
case UPDATE_MANY:
return {
_set: buildUpdateVariables(introspectionResults)(
resource,
aorFetchType,
params,
queryType
),
where: { id: { _in: params.ids } },
};
}
};
export default buildVariables;