ketting
Version:
Opiniated HATEAOS / Rest client.
86 lines • 2.89 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.factory = exports.CjState = void 0;
const base_state_1 = require("./base-state");
const util_1 = require("../http/util");
/**
* Represents a resource state in the HAL format
*/
class CjState extends base_state_1.BaseState {
serializeBody() {
throw new Error('Reserializing Collection+JSON states is not yet supported. Please log an issue in the Ketting project to help figure out how this should be done');
}
}
exports.CjState = CjState;
/**
* Turns a HTTP response into a CjState
*/
const factory = async (client, uri, response) => {
const body = await response.json();
const links = (0, util_1.parseLink)(uri, response.headers.get('Link'));
links.add(...parseCjLinks(uri, body));
// Remove _links and _embedded from body
const { _embedded, _links, ...newBody } = body;
return new CjState({
client,
uri,
data: newBody,
headers: response.headers,
links,
});
};
exports.factory = factory;
function parseCjLinks(contextUri, body) {
const result = [];
if (body.collection.links !== undefined) {
// Lets start with all links from the links property.
for (const link of body.collection.links) {
result.push({
context: contextUri,
href: link.href,
rel: link.rel,
title: link.name,
});
}
}
if (body.collection.items !== undefined) {
// Things that are in the 'items' array should also be considered links
// with the 'item' link relationship.
for (const item of body.collection.items) {
if (!item.href) {
continue;
}
result.push({
context: contextUri,
href: item.href,
rel: 'item',
});
}
}
if (body.collection.queries !== undefined) {
// Things that are in the 'queries' array can be considered links too.
for (const query of body.collection.queries) {
if (!query.data) {
// Non-templated
result.push({
context: contextUri,
href: query.href,
rel: query.rel,
title: query.name,
});
}
else {
// This query has a data property so we need 50% more magic
result.push({
context: contextUri,
href: query.href + query.data.map(property => '{?' + property.name + '}').join(''),
templated: true,
rel: query.rel,
title: query.name,
});
}
}
}
return result;
}
//# sourceMappingURL=collection-json.js.map