UNPKG

@n0safe/indirectus

Version:
124 lines 4.09 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnmappedRelationship = void 0; exports.isRelationship = isRelationship; exports.isOneToMany = isOneToMany; exports.isUnmapped = isUnmapped; exports.isManyToOne = isManyToOne; exports.isAnyToOne = isAnyToOne; exports.getRelationship = getRelationship; class UnmappedRelationship extends Error { collection; constructor(collection) { super("Can't find primary key for collection " + collection); this.collection = collection; } } exports.UnmappedRelationship = UnmappedRelationship; function isRelationship(relationship) { return !!relationship; } function isOneToMany(relationship) { return relationship?.type === "o2m"; } function isUnmapped(relationship) { return relationship?.type === "unmapped"; } function isManyToOne(relationship) { return relationship?.type === "m2o"; } function isAnyToOne(relationship) { return relationship?.type === "a2o"; } function getRelationship(fields, relations, context) { const { collection, field } = context; const relationship = relations.find((relation) => (relation.collection == collection && relation.field === field) || (relation.related_collection === collection && relation.meta?.one_field === field)); if (!relationship) { return null; } const parseCollections = (collections) => { if (!Array.isArray(collections)) { collections = collections.split(","); } return collections .map((collection) => collection.trim()) .map((collection) => ({ collection: collection, pk: findPrimaryKey(collection), })); }; const findPrimaryKey = (collection) => { const field = fields.find((candidate) => candidate.collection == collection && candidate.schema?.is_primary_key); if (!field) { throw new UnmappedRelationship(collection); } return field.field; }; const meta = relationship.meta; try { if (meta) { if (relationship.collection === collection && relationship.field === field && meta.one_collection_field && meta.one_allowed_collections) { return { type: "a2o", collection, field, refs: parseCollections(meta.one_allowed_collections), }; } if (relationship.collection === collection && relationship.field === field && meta.one_collection) { return { type: "m2o", many: false, collection, field, ref: { collection: meta.one_collection, pk: findPrimaryKey(meta.one_collection), }, }; } if (relationship.related_collection === collection && meta.one_field === field) { return { type: "o2m", many: true, collection, field, ref: { collection: meta.many_collection, pk: findPrimaryKey(meta.many_collection), }, }; } } else { return { type: "m2o", many: false, collection, field, ref: { collection: relationship.related_collection, pk: findPrimaryKey(relationship.related_collection), }, }; } } catch (e) { if (e instanceof UnmappedRelationship) { return { type: "unmapped", collection: e.collection, }; } } return null; } //# sourceMappingURL=relationships.js.map