ra-data-graphql-simple
Version:
A GraphQL simple data provider for react-admin
65 lines • 2.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const ra_core_1 = require("ra-core");
exports.default = (_introspectionResults) => (raFetchMethod, _resource, _queryType) => (response) => {
const data = response.data;
if (raFetchMethod === ra_core_1.GET_LIST ||
raFetchMethod === ra_core_1.GET_MANY ||
raFetchMethod === ra_core_1.GET_MANY_REFERENCE) {
return {
data: response.data.items.map(sanitizeResource),
total: response.data.total.count,
};
}
else if (raFetchMethod === ra_core_1.DELETE_MANY ||
raFetchMethod === ra_core_1.UPDATE_MANY) {
return { data: sanitizeResource(data.data).ids };
}
return { data: sanitizeResource(data.data) };
};
const sanitizeResource = (data) => {
const result = Object.keys(data).reduce((acc, key) => {
if (key.startsWith('_')) {
return acc;
}
const dataForKey = data[key];
if (dataForKey === null || dataForKey === undefined) {
return acc;
}
if (Array.isArray(dataForKey)) {
if (typeof dataForKey[0] === 'object' &&
dataForKey[0] != null &&
// If there is no id, it's not a reference but an embedded array
dataForKey[0].id != null) {
return {
...acc,
[key]: dataForKey.map(sanitizeResource),
[`${key}Ids`]: dataForKey.map(d => d.id),
};
}
else {
return { ...acc, [key]: dataForKey };
}
}
if (typeof dataForKey === 'object' &&
dataForKey != null &&
// If there is no id, it's not a reference but an embedded object
dataForKey.id != null) {
return {
...acc,
...(dataForKey &&
dataForKey.id && {
[`${key}.id`]: dataForKey.id,
}),
// We should only sanitize gql types, not objects
[key]: dataForKey.__typename
? sanitizeResource(dataForKey)
: dataForKey,
};
}
return { ...acc, [key]: dataForKey };
}, {});
return result;
};
module.exports = exports.default;
//# sourceMappingURL=getResponseParser.js.map