UNPKG

semantic-network

Version:

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

286 lines 14.7 kB
"use strict"; 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; 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 __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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FormUtil = void 0; var representationUtil_1 = require("./representationUtil"); var semantic_link_1 = require("semantic-link"); var resourceMergeFactory_1 = require("../representation/resourceMergeFactory"); var sparseRepresentationFactory_1 = require("../representation/sparseRepresentationFactory"); var linkRelation_1 = require("../linkRelation"); var anylogger_1 = __importDefault(require("anylogger")); var linkRelConvertUtil_1 = require("./linkRelConvertUtil"); var formTypes_1 = require("../types/formTypes"); var instanceOfCollection_1 = require("./instanceOf/instanceOfCollection"); var log = (0, anylogger_1.default)('FormUtil'); var FormUtil = /** @class */ (function () { function FormUtil() { } FormUtil.fieldsToAccept = function (form, defaultFields) { if (defaultFields === void 0) { defaultFields = []; } var fieldsFromForm = (form.items || []).map(function (x) { return x.name; }); var allFields = defaultFields === null || defaultFields === void 0 ? void 0 : defaultFields.concat(fieldsFromForm); var distinctFields = new Set(allFields); return Array.from(distinctFields); }; /** * Pick all the fields to resolve in the document at that (a) exist in the form AND (b) exist on the document itself * or are defaults * @param document * @param form * @param defaultFields */ FormUtil.fieldsToResolve = function (document, form, defaultFields) { if (defaultFields === void 0) { defaultFields = []; } // preparation: get all the fields to return back to the API var fieldsToReturn = FormUtil.fieldsToAccept(form, defaultFields); // pick all the fields as specified from the form var fields = representationUtil_1.RepresentationUtil.fields(document); // resolve return (fieldsToReturn ? fields.filter(function (fieldName) { return fieldsToReturn.includes(fieldName); }) : fields); }; /** * Pick all the fields to resolve in the document at that (a) exist in the form AND (b) exist on the document itself * or are defaults * @param document * @param form * @param defaultFields * @returns * */ FormUtil.linksToResolve = function (document, form, defaultFields) { // preparation: get all the fields to return back to the API // pick only link rels that exist in the form // const relsToReturn = fieldsToReturn.map(field => LinkRelConvertUtil.camelToDash(field as string)); // link relations exist as a dashed form and fields/create forms use camel case // return (relsToReturn ? // relsToReturn.filter(fieldName => LinkUtil.matches(document as LinkedRepresentation, fieldName)) : // []) as P[]; if (defaultFields === void 0) { defaultFields = []; } return FormUtil.fieldsToAccept(form, defaultFields) .flatMap(function (field) { return linkRelConvertUtil_1.LinkRelConvertUtil.camelToDash(field); }) .filter(function (fieldName) { return semantic_link_1.LinkUtil.matches(document, fieldName); }); }; /** * Find a {@link FormItem} by matching its {@link FormItem.name} against a field name. A fieldname strategy * is camel cased * * @see LinkRelConvertUtil.dashToCamel * * TODO: field could accept RelationshipType {@see LinkRelConvertUtil.relTypeToCamel} * * @param form * @param field */ FormUtil.findByField = function (form, field) { var _a; return (_a = form.items) === null || _a === void 0 ? void 0 : _a.find(function (item) { return item.name === field; }); }; /** * A basic dirty check type function comparing an original resource with a new document. * @param resource original document * @param document updates to be made * @param form * @param defaultFields that require update * @returns fields to merge that actually requiring updating based on being a different value * * // TODO; return Omit<P, "links"> */ FormUtil.fieldsRequiringUpdate = function (resource, document, form, defaultFields) { if (defaultFields === void 0) { defaultFields = []; } var fieldsToCheck = FormUtil.fieldsToAccept(form, defaultFields); // only return fields that are different return fieldsToCheck .filter(function (field) { // omit any fields that match // WARNING: This might have problems if the field is a 'multiple' <<<<<<<<<<<<<<<< ---- please review return !(representationUtil_1.RepresentationUtil.getProperty(resource, field) === representationUtil_1.RepresentationUtil.getProperty(document, field)); }); }; /** * Returns a new object with only fields explicitly set in the form or default values * @param document * @param form * @param options */ FormUtil.fieldsToReturnFromForm = function (document, form, options) { var e_1, _a; var _b = __assign({}, options).defaultFields, defaultFields = _b === void 0 ? [] : _b; var fieldsToResolve = FormUtil.fieldsToResolve(document, form, defaultFields); var doc = {}; try { for (var fieldsToResolve_1 = __values(fieldsToResolve), fieldsToResolve_1_1 = fieldsToResolve_1.next(); !fieldsToResolve_1_1.done; fieldsToResolve_1_1 = fieldsToResolve_1.next()) { var field = fieldsToResolve_1_1.value; // really not sure how to avoid indexer errors doc[field] = representationUtil_1.RepresentationUtil.getProperty(document, field); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (fieldsToResolve_1_1 && !fieldsToResolve_1_1.done && (_a = fieldsToResolve_1.return)) _a.call(fieldsToResolve_1); } finally { if (e_1) throw e_1.error; } } return doc; }; /** * A {@link FormItem} can have a lazy loaded {@link FieldType.Collection} on a {@link FieldType.Select} where the * {@link FormItem.id} is set to the uri of the collection that is resolved via an optional {@link MergeOptions.resourceResolver}. * This collection may or may not be resolved at the same time via an optional {@link MergeOptions.resolver}. * * Note: there is a current implicit polymorphism to be resolved. The {@link FormItem.items} can be both a {@link FormItem[]} * and a {@link CollectionRepresentation} where the code looks through to the Collection items. * * @param item form item that may optionally have a lazy loaded items collection * @param options contains the optional resolvers */ FormUtil.resolveItemsFromCollection = function (item, options) { return __awaiter(this, void 0, void 0, function () { var _a, _b, resourceResolver, _c, resolver, uri, representation, resource; return __generator(this, function (_d) { switch (_d.label) { case 0: if (item.type !== formTypes_1.FieldType.Select) { log.warn('Only selects form type should be called but have called %s', item.type); } if (!item.id) return [3 /*break*/, 2]; _a = __assign({}, options), _b = _a.resourceResolver, resourceResolver = _b === void 0 ? undefined : _b, _c = _a.resolver, resolver = _c === void 0 ? resourceMergeFactory_1.noopResolver : _c; if (!resourceResolver) return [3 /*break*/, 2]; uri = resolver.resolve(item.id); representation = sparseRepresentationFactory_1.SparseRepresentationFactory.make(__assign(__assign({}, options), { uri: uri })); log.debug('matching items collection with resource resolver \'%s\' on \'%s\' --> \'%s\'', item.name, item.id, uri); return [4 /*yield*/, resourceResolver(item.name)(representation, options)]; case 1: resource = _d.sent(); if ((0, instanceOfCollection_1.instanceOfCollection)(resource)) { // put the collection onto the items. // TODO: merge onto existing items // TODO: workout how to deal with Collection versus FormItem[] if (item.items) { log.warn('Potential conflict between existing form items and merged collection'); } item['items'] = resource; } else { if (resource) { log.error('Only a collection may be lazy loaded onto form items: %s', semantic_link_1.LinkUtil.getUri(resource, linkRelation_1.LinkRelation.Self)); } // do nothing to the items } _d.label = 2; case 2: // on a FormItem, items is optional but it is easier if instead of null, items is an empty list where the form type // is select if (!item.items) { item.items = []; } return [2 /*return*/]; } }); }); }; /** * Take a form representation and return back a document based on the keys in the form representation. * * TODO: values are currently null but could include any defaults from the form */ FormUtil.toEmptyDocument = function (form) { var formItems = form.items || []; var documentation = formItems.map(function (key) { var _a; return (_a = {}, _a[key.name] = null, _a); }); // ensure that it is cloned //?? check, shouldn't need this return Object.assign.apply(Object, __spreadArray([{}], __read(documentation), false)); }; return FormUtil; }()); exports.FormUtil = FormUtil; //# sourceMappingURL=formUtil.js.map