UNPKG

semantic-network

Version:

A utility library for manipulating a list of links that form a semantic interface to a network of resources.

71 lines 3.14 kB
import { __awaiter } from "tslib"; import { LinkUtil } from 'semantic-link'; import { LinkRelation } from '../linkRelation'; import { FormUtil } from './formUtil'; import { LinkRelConvertUtil } from './linkRelConvertUtil'; import { noopResolver } from '../representation/resourceMergeFactory'; import anylogger from 'anylogger'; const log = anylogger('FieldLinksResolverUtil'); export class FieldLinksResolverUtil { /** * On a resource, iterate through all the link relations that match the form items and resolve the reference * to a value and attach onto the original resource. * * Note: while this treats a link rel as a uri-list, it doesn't current support multiple resolutions */ static resolveLinks(resource, form, options) { return __awaiter(this, void 0, void 0, function* () { if (!resource) { log.warn('Document does not exist for form %s', LinkUtil.getUri(form, LinkRelation.Self)); return undefined; } const { defaultFields } = Object.assign({}, options); const linksToResolve = FormUtil.linksToResolve(resource, form, defaultFields); const { resourceResolver } = Object.assign({}, options); for (const rel of linksToResolve) { if (resourceResolver && rel) { // throw new Error('Resource resolver not implemented'); yield resourceResolver(rel)(resource, options); } const fieldName = LinkRelConvertUtil.dashToCamel(rel); const formItem = FormUtil.findByField(form, fieldName); if (formItem) { const fieldValue = this.resolveFormItemToUri(resource, formItem, rel, options); if (fieldValue) { resource[fieldName] = fieldValue; } } } }); } /** * Filters all the links on the document based on the link relations and makes into a uri-list. However, based on the * {@link FormItem.multiple} the uri-list may be a single (text) or multiple (array) return type. * * All uris are also resolved via optional {@link MergeOptions.resolver} * * Note: the {@link FormItem.multiple} overrides the single versus multiple and will pick the head of the array to * return a single uri * * @param document * @param formItem * @param rel * @param options? * @returns the resolved {@link UriListValue} */ static resolveFormItemToUri(document, formItem, rel, options) { const { resolver = noopResolver } = Object.assign({}, options); const links = LinkUtil.filter(document, rel); const values = links.map(link => resolver.resolve(link.href)); if (formItem.multiple) { return values; } else { // single if (values.length > 1) { log.warn('More than one in array, returning first'); } return values[0]; } } } //# sourceMappingURL=fieldLinksResolverUtil.js.map