UNPKG

ketting

Version:

Opiniated HATEAOS / Rest client.

251 lines 8.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fetcher_1 = require("./http/fetcher"); const resource_1 = require("./resource"); const state_1 = require("./state"); const util_1 = require("./http/util"); const uri_1 = require("./util/uri"); const cache_1 = require("./cache"); const cache_2 = require("./middlewares/cache"); const accept_header_1 = require("./middlewares/accept-header"); const warning_1 = require("./middlewares/warning"); class Client { constructor(bookmarkUri) { /** * Supported content types * * Each content-type has a 'factory' that turns a HTTP response * into a State object. * * The last value in the array is the 'q=' value, used in Accept * headers. Higher means higher priority. */ this.contentTypeMap = { 'application/prs.hal-forms+json': [state_1.halStateFactory, '1.0'], 'application/hal+json': [state_1.halStateFactory, '0.9'], 'application/vnd.api+json': [state_1.jsonApiStateFactory, '0.8'], 'application/vnd.siren+json': [state_1.sirenStateFactory, '0.8'], 'application/vnd.collection+json': [state_1.cjStateFactory, '0.8'], 'application/json': [state_1.halStateFactory, '0.7'], 'text/html': [state_1.htmlStateFactory, '0.6'], }; /** * cacheDependencies contains all cache relationships between * resources. * * This lets a user (for example) let a resource automatically * expire, if another one expires. * * A server can populate this list using the `inv-by' link. * * @deprecated This property will go private in a future release. */ this.cacheDependencies = new Map(); this.bookmarkUri = bookmarkUri; this.fetcher = new fetcher_1.Fetcher(); this.fetcher.use((0, cache_2.default)(this)); this.fetcher.use((0, accept_header_1.default)(this)); this.fetcher.use((0, warning_1.default)()); this.cache = new cache_1.ForeverCache(); this.resources = new Map(); } /** * Follows a relationship, based on its reltype. For example, this might be * 'alternate', 'item', 'edit' or a custom url-based one. * * This function can also follow templated uris. You can specify uri * variables in the optional variables argument. */ follow(rel, variables) { return this.go().follow(rel, variables); } /** * Returns a resource by its uri. * * This function doesn't do any HTTP requests. The uri is optional. If it's * not specified, it will return the bookmark resource. * * If a relative uri is passed, it will be resolved based on the bookmark * uri. * * @example * const res = ketting.go('https://example.org/); * @example * const res = ketting.go<Author>('/users/1'); * @example * const res = ketting.go(); // bookmark */ go(uri) { let absoluteUri; if (uri === undefined) { absoluteUri = this.bookmarkUri; } else if (typeof uri === 'string') { absoluteUri = (0, uri_1.resolve)(this.bookmarkUri, uri); } else { absoluteUri = (0, uri_1.resolve)(uri); } if (!this.resources.has(absoluteUri)) { const resource = new resource_1.default(this, absoluteUri); this.resources.set(absoluteUri, resource); return resource; } return this.resources.get(absoluteUri); } /** * Adds a fetch middleware, which will be executed for * each fetch() call. * * If 'origin' is specified, fetch middlewares can be executed * only if the host/origin matches. */ use(middleware, origin = '*') { this.fetcher.use(middleware, origin); } /** * Clears the entire state cache */ clearCache() { this.cache.clear(); this.cacheDependencies = new Map(); } /** * Caches a State object * * This function will also emit 'update' events to resources, and store all * embedded states. */ cacheState(state) { // Flatten the list of state objects. const newStates = flattenState(state); // Register all cache dependencies. for (const nState of newStates) { for (const invByLink of nState.links.getMany('inv-by')) { this.addCacheDependency((0, uri_1.resolve)(invByLink), nState.uri); } } // Store all new caches for (const nState of newStates) { this.cache.store(nState); } // Emit 'update' events for (const nState of newStates) { const resource = this.resources.get(nState.uri); if (resource) { // We have a resource for this object, notify it as well. resource.emit('update', nState); } } } /** * Adds a cache dependency between two resources. * * If the 'target' resource ever expires, it will cause 'dependentUri' to * also expire. * * Both argument MUST be absolute urls. */ addCacheDependency(targetUri, dependentUri) { if (this.cacheDependencies.has(targetUri)) { this.cacheDependencies.get(targetUri).add(dependentUri); } else { this.cacheDependencies.set(targetUri, new Set([dependentUri])); } } /** * Helper function for clearing the cache for a resource. * * This function will also emit the 'stale' event for resources that have * subscribers, and handle any dependent resource caches. * * If any resources are specified in deletedUris, those will not * receive 'stale' events, but 'delete' events instead. */ clearResourceCache(staleUris, deletedUris) { let stale = new Set(); const deleted = new Set(); for (const uri of staleUris) { stale.add((0, uri_1.resolve)(this.bookmarkUri, uri)); } for (const uri of deletedUris) { stale.add((0, uri_1.resolve)(this.bookmarkUri, uri)); deleted.add((0, uri_1.resolve)(this.bookmarkUri, uri)); } stale = expandCacheDependencies(new Set([...stale, ...deleted]), this.cacheDependencies); for (const uri of stale) { this.cache.delete(uri); const resource = this.resources.get(uri); if (resource) { if (deleted.has(uri)) { resource.emit('delete'); } else { resource.emit('stale'); } } } } /** * Transforms a fetch Response to a State object. */ async getStateForResponse(uri, response) { const contentType = (0, util_1.parseContentType)(response.headers.get('Content-Type')); if (!contentType || response.status === 204) { return (0, state_1.binaryStateFactory)(this, uri, response); } if (contentType in this.contentTypeMap) { return this.contentTypeMap[contentType][0](this, uri, response); } else if (contentType.startsWith('text/')) { // Default to TextState for any format starting with text/ return (0, state_1.textStateFactory)(this, uri, response); } else if (contentType.match(/^application\/[A-Za-z-.]+\+json/)) { // Default to HalState for any format containing a pattern like application/*+json return (0, state_1.halStateFactory)(this, uri, response); } else { return (0, state_1.binaryStateFactory)(this, uri, response); } } } exports.default = Client; /** * Find all dependencies for a given resource. * * For example, if * * if resourceA depends on resourceB * * and resourceB depends on resourceC * * Then if 'resourceC' expires, so should 'resourceA' and 'resourceB'. * * This function helps us find these dependencies recursively and guarding * against recursive loops. */ function expandCacheDependencies(uris, dependencies, output) { if (!output) output = new Set(); for (const uri of uris) { if (!output.has(uri)) { output.add(uri); if (dependencies.has(uri)) { expandCacheDependencies(dependencies.get(uri), dependencies, output); } } } return output; } /** * Take a State object, find all it's embedded resources and return a flat * array of all resources at any depth. */ function flattenState(state, result = new Set()) { result.add(state); for (const embedded of state.getEmbedded()) { flattenState(embedded, result); } return result; } //# sourceMappingURL=client.js.map