UNPKG

@rytass/cms-base-nestjs-module

Version:

Rytass Content Management System NestJS Base Module

70 lines (67 loc) 3.02 kB
import { Injectable, Inject } from '@nestjs/common'; import DataLoader from 'dataloader'; import { LRUCache } from 'lru-cache'; import { Brackets } from 'typeorm'; import { RESOLVED_ARTICLE_VERSION_REPO } from '../typings/cms-base-providers.js'; function _ts_decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function _ts_param(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; } class ArticleSignatureDataLoader { articleVersionRepo; constructor(articleVersionRepo){ this.articleVersionRepo = articleVersionRepo; this.versionSignaturesLoader = new DataLoader(async (ids)=>{ const pairs = ids.map((token)=>{ const [id, version] = token.split('|'); const nVersion = Number(version); if (!id || Number.isNaN(nVersion) || nVersion < 0) { throw new Error(`Invalid id: ${token}, please use format: id|version`); } return { id, version: Number(version) }; }); const qb = this.articleVersionRepo.createQueryBuilder('articleVersions'); qb.leftJoinAndSelect('articleVersions.signatures', 'signatures'); qb.leftJoinAndSelect('signatures.signatureLevel', 'signatureLevel'); pairs.forEach((pair, index)=>{ qb.orWhere(new Brackets((subQb)=>{ subQb.andWhere(`articleVersions.articleId = :id_${index}`, { [`id_${index}`]: pair.id }); subQb.andWhere(`articleVersions.version = :version_${index}`, { [`version_${index}`]: pair.version }); return subQb; })); }); const versions = await qb.getMany(); const versionMap = new Map(versions.map((version)=>[ `${version.articleId}|${version.version}`, version ])); return ids.map((id)=>versionMap.get(id)?.signatures ?? []); }, { cacheMap: new LRUCache({ max: 100, ttl: 1000 * 15, ttlAutopurge: true }) }); } versionSignaturesLoader; } ArticleSignatureDataLoader = _ts_decorate([ Injectable(), _ts_param(0, Inject(RESOLVED_ARTICLE_VERSION_REPO)) ], ArticleSignatureDataLoader); export { ArticleSignatureDataLoader };