UNPKG

@sqb/connect

Version:

Multi-dialect database connection framework written with TypeScript

73 lines (72 loc) 2.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Link = Link; const entity_metadata_js_1 = require("../model/entity-metadata.js"); const link_chain_js_1 = require("../model/link-chain.js"); function Link(options) { let root; let chain; const fn = (target, propertyKey) => { if (typeof propertyKey !== 'string') throw new TypeError('Symbol properties are not allowed'); const reflectType = Reflect.getMetadata('design:type', target, propertyKey); if (!root) { if (reflectType === Array) { throw new TypeError(`Can't get type information while it is an array. Please define entity type`); } if (!entity_metadata_js_1.EntityMetadata.get(reflectType)) throw new TypeError(`No entity metadata found for type "${reflectType}"`); fn.toOne(reflectType); } if (reflectType !== Array && root.first.returnsMany()) { throw new TypeError(`Link returns single instance however property type is an array`); } if (reflectType === Array && !root.first.returnsMany()) { throw new TypeError(`Link returns array of instances however property type is not an array`); } const entity = entity_metadata_js_1.EntityMetadata.define(target.constructor); // @ts-ignore // noinspection JSConstantReassignment root.first.source = entity.ctor; entity_metadata_js_1.EntityMetadata.defineAssociationField(entity, propertyKey, root.first, options); }; fn.toOne = (type, args) => { if (chain) { chain = chain.linkToOne(type, args?.targetKey, args?.sourceKey); if (args?.where) chain.where(args.where); return fn; } root = linkToOne(type, args?.targetKey, args?.sourceKey); chain = root; if (args?.where) chain.where(args.where); return fn; }; fn.toMany = (type, args) => { if (chain) { chain = chain.linkToMany(type, args?.targetKey, args?.sourceKey); if (args?.where) chain.where(args.where); return fn; } root = linkToMany(type, args?.targetKey, args?.sourceKey); chain = root; if (args?.where) chain.where(args.where); return fn; }; return fn; } /** * Crates an Link Chain object */ function linkToOne(type, targetKey, sourceKey) { return new link_chain_js_1.LinkChain(type, targetKey, sourceKey); } /** * Crates an Link Chain object */ function linkToMany(type, targetKey, sourceKey) { return new link_chain_js_1.LinkChain(type, targetKey, sourceKey, true); }