UNPKG

ketting

Version:

Opiniated HATEAOS / Rest client.

96 lines 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseState = void 0; const action_1 = require("../action"); /** * The Base State provides a convenient way to implement a new State type. */ class BaseState { constructor(uri, data, headers, links, embedded = [], actionInfo = []) { this.uri = uri; this.data = data; this.headers = headers; this.links = links; this.embedded = embedded; this.actionInfo = actionInfo; this.timestamp = Date.now(); } /** * Content-headers are a subset of HTTP headers that related directly * to the content. The obvious ones are Content-Type. * * This set of headers will be sent by the server along with a GET * response, but will also be sent back to the server in a PUT * request. */ contentHeaders() { const contentHeaderNames = [ 'Content-Type', 'Content-Language', 'ETag', 'Last-Modified', ]; const result = {}; for (const contentHeader of contentHeaderNames) { if (this.headers.has(contentHeader)) { result[contentHeader] = this.headers.get(contentHeader); } } return new Headers(result); } /** * Return an action by name. * * If no name is given, the first action is returned. This is useful for * formats that only supply 1 action, and no name. */ action(name) { if (!this.actionInfo.length) { throw new action_1.ActionNotFound('This State does not define any actions'); } if (name === undefined) { return new action_1.SimpleAction(this.client, this.actionInfo[0]); } for (const action of this.actionInfo) { if (action.name === name) { return new action_1.SimpleAction(this.client, this.actionInfo[0]); } } throw new action_1.ActionNotFound('This State defines no action'); } /** * Returns all actions */ actions() { return this.actionInfo.map(action => new action_1.SimpleAction(this.client, action)); } /** * Checks if the specified action exists. * * If no name is given, checks if _any_ action exists. */ hasAction(name) { if (name === undefined) return this.actionInfo.length > 0; for (const action of this.actionInfo) { if (name === action.name) { return true; } } return false; } /** * Certain formats can embed other resources, identified by their * own URI. * * When a format has embedded resources, we will use these to warm * the cache. * * This method returns every embedded resource. */ getEmbedded() { return this.embedded; } } exports.BaseState = BaseState; //# sourceMappingURL=base-state.js.map