semantic-network
Version:
A utility library for manipulating a list of links that form a semantic interface to a network of resources.
303 lines • 13.6 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TrackedRepresentationUtil = void 0;
var semantic_link_1 = require("semantic-link");
var types_1 = require("../types/types");
var anylogger_1 = __importDefault(require("anylogger"));
var linkRelation_1 = require("../linkRelation");
var status_1 = require("../representation/status");
var singletonMerger_1 = require("../representation/singletonMerger");
var instanceOfCollection_1 = require("./instanceOf/instanceOfCollection");
var instanceOfTrackedRepresentation_1 = require("./instanceOf/instanceOfTrackedRepresentation");
var checkHeaders_1 = require("../representation/checkHeaders");
var dateToGMTHeader_1 = require("./dateToGMTHeader");
var log = (0, anylogger_1.default)('TrackedRepresentationUtil');
var TrackedRepresentationUtil = /** @class */ (function () {
function TrackedRepresentationUtil() {
}
/**
* Return back the internal {@link State} object for tracking and introspection
* @param resource
*/
TrackedRepresentationUtil.getState = function (resource) {
var tracking = resource[types_1.state];
if (!tracking) {
var uri = semantic_link_1.LinkUtil.getUri(resource, linkRelation_1.LinkRelation.Self);
if (uri) {
log.debug('state not found on %s', uri);
}
else {
log.debug('state not found on unknown');
}
}
return tracking;
};
/**
* Set the headers inside the internal {@link State} object for tracking and introspection
*/
TrackedRepresentationUtil.setHeaders = function (resource, headers) {
var tracking = resource[types_1.state];
if (tracking) {
tracking.headers = headers;
}
return tracking;
};
/**
* Helper to set resource to {@link Status.stale} so that the cache forces need fetch
*/
TrackedRepresentationUtil.setStateStale = function (resource) {
this.setState(resource, status_1.Status.stale);
};
/**
* Helper to set resource to {@link Status.staleFromETag} so that the cache forces need fetch
*/
TrackedRepresentationUtil.setStateStaleFromETag = function (resource) {
this.setState(resource, status_1.Status.staleFromETag);
};
/**
* Looks through into the {@link State} headers for the ETag
*/
TrackedRepresentationUtil.getETag = function (resource) {
var state = this.getState(resource);
// permissive naming strategy for eTags
var _a = __assign({}, state).headers, etag = _a.etag, ETag = _a.ETag, eTag = _a.eTag;
return etag || ETag || eTag;
};
/**
* Looks through into the {@link State} headers for the ETag
*/
TrackedRepresentationUtil.getFeedETag = function (resource) {
var state = this.getState(resource);
// permissive naming strategy for eTags
var _a = __assign({}, state).feedHeaders, etag = _a.etag, ETag = _a.ETag, eTag = _a.eTag;
return etag || ETag || eTag;
};
/**
* Looks through into the {@link State} headers for the 'last-modified'
*/
TrackedRepresentationUtil.getFeedLastModified = function (resource) {
var state = this.getState(resource);
// permissive naming strategy for eTags
var lastModified = __assign({}, state).feedHeaders["last-modified"];
return lastModified;
};
/**
* Sets the value of the feed eTag and if null is provided, it is cleared
*/
TrackedRepresentationUtil.setFeedETag = function (resource, eTag, lastModified) {
var state = this.getState(resource);
// ensure that UTC dates are converted across to GMT headers
var lastModifiedHeader = (0, dateToGMTHeader_1.dateToGMTHeader)(lastModified);
if (eTag) {
state.feedHeaders = __assign(__assign(__assign({}, state.feedHeaders), { etag: eTag }), (lastModifiedHeader && { 'last-modified': lastModifiedHeader }));
}
else {
delete state.feedHeaders.etag;
}
};
/**
* Checks if an eTag exists based on looking through into the {@link State} headers for the ETag
*/
TrackedRepresentationUtil.hasETag = function (resource) {
return this.getETag(resource) !== undefined;
};
/**
* Checks if an eTag exists based on looking through into the {@link State} headers for the ETag
*/
TrackedRepresentationUtil.hasFeedETag = function (resource) {
return this.getFeedETag(resource) !== undefined;
};
/**
* Checks if the header eTag matches the feed eTag. It is deemed stale when both eTags are present and different
* suggesting that the latest is not present
*/
TrackedRepresentationUtil.hasStaleFeedETag = function (resource) {
var feedETag = this.getFeedETag(resource);
var requestETag = this.getETag(resource);
return feedETag !== undefined &&
requestETag !== undefined &&
requestETag !== feedETag;
};
/**
* Checks the named child object is tracked on the resource.
*
* A resource keeps a set of child singletons and a set of child collections. This utility
* provides a logical 'in' operator on those sets.
*
* Note: field name ideally comes in as K only, but in practice it also needs to be dealt with as arbitrary string
* as soon as it is known to be a tracked representation then it can cast string to K (rather than deal with
* string in the subsequent methods
*/
TrackedRepresentationUtil.isTracked = function (resource, name) {
return (0, instanceOfTrackedRepresentation_1.instanceOfTrackedRepresentation)(resource) &&
(this.isSingletonTracked(resource, name) || this.isCollectionTracked(resource, name));
};
/**
* Checks the resource is currently tracked in either as a singleton or a collection
*/
TrackedRepresentationUtil.getTrackedFields = function (resource) {
return (0, instanceOfTrackedRepresentation_1.instanceOfTrackedRepresentation)(resource) ?
__spreadArray(__spreadArray([], __read(this.getState(resource).collection), false), __read(this.getState(resource).singleton), false) :
[];
};
/**
* Checks whether the resource requires an across-the-wire fetch based on the state flags.
*
* We can only do a fetch when we actually have a potentially valid uri and that we haven't already
* got the resource. Currently, the forceLoad allows an override which is an initial cache busting
* strategy that will need improvement
*
* Simple cache bust strategy which is an override switch. To be expanded as needed. Currently, only
* cache bust on {@link Status.hydrated} resources. There is no time-based, refresh strategy at this point.
*
*/
TrackedRepresentationUtil.needsFetchFromState = function (resource, options) {
var _a = __assign({}, options).forceLoad, forceLoad = _a === void 0 ? false : _a;
var _b = this.getState(resource).status, status = _b === void 0 ? undefined : _b;
if (status) {
var fetch_1 = /*status === Status.unknown ||*/ status === status_1.Status.locationOnly ||
status === status_1.Status.stale ||
status === status_1.Status.staleFromETag ||
(forceLoad && status === status_1.Status.hydrated);
if (fetch_1) {
log.debug('fetch resource \'%s\': %s', status.toString(), semantic_link_1.LinkUtil.getUri(resource, linkRelation_1.LinkRelation.Self));
}
else {
log.debug('fetch resource \'%s\' not required: %s', status.toString(), semantic_link_1.LinkUtil.getUri(resource, linkRelation_1.LinkRelation.Self));
}
return fetch_1;
}
else {
log.warn('status not found (on state): %s', semantic_link_1.LinkUtil.getUri(resource, linkRelation_1.LinkRelation.Self));
return true;
}
};
/**
* Respects conditional headers from the server on whether to push back through the application cache. Without it,
* client developers use {@link ResourceFetchOptions.forceLoad} option too often because requests do not respect the server cache-control
* headers.
*
* Note: this code will not attempt to reimplement request headers (that is what browsers already do). However, what
* you may find is inconsistent behaviours between browsers on request cache control headers
*
* @see https://gertjans.home.xs4all.nl/javascript/cache-control.html
*/
TrackedRepresentationUtil.needsFetchFromHeaders = function (resource, options) {
var e_1, _a;
var _b = __assign({}, options).checkHeaderStrategies, checkHeaderStrategies = _b === void 0 ? checkHeaders_1.CheckHeaders.defaultStrategies : _b;
var _c = this.getState(resource).headers, headers = _c === void 0 ? {} : _c;
var now = new Date();
try {
for (var checkHeaderStrategies_1 = __values(checkHeaderStrategies), checkHeaderStrategies_1_1 = checkHeaderStrategies_1.next(); !checkHeaderStrategies_1_1.done; checkHeaderStrategies_1_1 = checkHeaderStrategies_1.next()) {
var strategy = checkHeaderStrategies_1_1.value;
if (strategy(headers, now)) {
return true;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (checkHeaderStrategies_1_1 && !checkHeaderStrategies_1_1.done && (_a = checkHeaderStrategies_1.return)) _a.call(checkHeaderStrategies_1);
}
finally { if (e_1) throw e_1.error; }
}
return false;
};
/**
*
* Returns target.
*
* @param target
* @param prop
* @param resource
* @param options
*/
TrackedRepresentationUtil.add = function (target, prop, resource, options) {
if ((0, instanceOfTrackedRepresentation_1.instanceOfTrackedRepresentation)(target)) {
// add as a tracked collection/singleton on state
if ((0, instanceOfCollection_1.instanceOfCollection)(resource)) {
this.getState(target).collection.add(prop);
}
else {
this.getState(target).singleton.add(prop);
}
singletonMerger_1.SingletonMerger.add(target, prop, resource, options);
}
else {
log.warn('target is not a tracked representation and cannot add resource; \'%s\'', semantic_link_1.LinkUtil.getUri(target, linkRelation_1.LinkRelation.Self));
}
return target;
};
TrackedRepresentationUtil.setState = function (resource, status) {
if ((0, instanceOfTrackedRepresentation_1.instanceOfTrackedRepresentation)(resource)) {
var state_1 = TrackedRepresentationUtil.getState(resource);
state_1.status = status;
}
};
/**
* Checks the resource is currently tracked as a singleton
*/
TrackedRepresentationUtil.isSingletonTracked = function (resource, name) {
return this.getState(resource).singleton.has(name);
};
/**
* Checks the resource is currently tracked as a collection
*/
TrackedRepresentationUtil.isCollectionTracked = function (resource, name) {
return this.getState(resource).collection.has(name);
};
return TrackedRepresentationUtil;
}());
exports.TrackedRepresentationUtil = TrackedRepresentationUtil;
//# sourceMappingURL=trackedRepresentationUtil.js.map