ketting
Version:
Opiniated HATEAOS / Rest client.
95 lines • 3.51 kB
JavaScript
;
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
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");
const link_1 = require("../link");
/**
* 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');
}
clone() {
return new CjState(this.uri, this.data, new Headers(this.headers), new link_1.Links(this.uri, this.links));
}
}
exports.CjState = CjState;
/**
* Turns a HTTP response into a CjState
*/
const factory = async (uri, response) => {
const body = await response.json();
const links = util_1.parseLink(uri, response.headers.get('Link'));
links.add(...parseCjLinks(uri, body));
// Remove _links and _embedded from body
const { _embedded, _links } = body, newBody = __rest(body, ["_embedded", "_links"]);
return new CjState(uri, newBody, 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