@datocms/rest-client-utils
Version:
Utilities for DatoCMS REST API clients
79 lines • 2.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.deserializeRawResponseBodyWithItems = exports.deserializeRawItem = exports.deserializeResponseBody = exports.deserializeJsonEntity = void 0;
function hasData(thing) {
return typeof thing === 'object' && !!thing && 'data' in thing;
}
function hasIncluded(thing) {
return typeof thing === 'object' && !!thing && 'included' in thing;
}
function deserializeJsonEntity({ __itemTypeId, id, type, attributes, relationships, meta, }) {
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (__itemTypeId ? { __itemTypeId } : {})), (id ? { id } : {})), (type ? { type } : {})), (attributes || {})), (relationships
? Object.fromEntries(Object.entries(relationships).map(([rel, value]) => [
rel,
value === null || value === void 0 ? void 0 : value.data,
]))
: {})), (meta ? { meta } : {}));
}
exports.deserializeJsonEntity = deserializeJsonEntity;
function deserializeResponseBody(body) {
if (!hasData(body)) {
throw new Error('Invalid body!');
}
if (Array.isArray(body.data)) {
return body.data.map(deserializeJsonEntity);
}
return deserializeJsonEntity(body.data);
}
exports.deserializeResponseBody = deserializeResponseBody;
function isItemEntity(entity) {
return Boolean(entity &&
typeof entity === 'object' &&
'type' in entity &&
entity.type === 'item');
}
function processValue(value) {
if (Array.isArray(value)) {
return value.map(processValue);
}
if (value && typeof value === 'object') {
if (isItemEntity(value)) {
return deserializeRawItem(value);
}
const result = {};
for (const [key, val] of Object.entries(value)) {
result[key] = processValue(val);
}
return result;
}
return value;
}
function deserializeRawItem(entity) {
if (!isItemEntity(entity)) {
return entity;
}
const processedAttributes = entity.attributes
? processValue(entity.attributes)
: entity.attributes;
return Object.assign(Object.assign({}, entity), { attributes: processedAttributes, __itemTypeId: entity.relationships.item_type.data.id });
}
exports.deserializeRawItem = deserializeRawItem;
function deserializeRawResponseBodyWithItems(body) {
if (!hasData(body)) {
throw new Error('Invalid body!');
}
let data;
if (Array.isArray(body.data)) {
data = body.data.map(deserializeRawItem);
}
else {
data = deserializeRawItem(body.data);
}
let included;
if (hasIncluded(body)) {
included = body.included.map(deserializeRawItem);
}
return Object.assign(Object.assign(Object.assign({}, body), { data }), (included ? { included } : {}));
}
exports.deserializeRawResponseBodyWithItems = deserializeRawResponseBodyWithItems;
//# sourceMappingURL=deserialize.js.map