|
| 1 | +import { Injectable } from '@nestjs/common'; |
| 2 | +import { isUUID } from 'class-validator'; |
| 3 | +import DataLoader from 'dataloader'; |
| 4 | +import LRU from 'lru-cache'; |
| 5 | +import { ID, NotFoundException } from '~/common'; |
| 6 | +import { IdResolver } from '~/common/validators/short-id.validator'; |
| 7 | +import { ILogger, Logger } from '~/core/logger'; |
| 8 | +import { EdgeDB } from './edgedb.service'; |
| 9 | +import { e } from './reexports'; |
| 10 | + |
| 11 | +@Injectable() |
| 12 | +export class AliasIdResolver implements IdResolver { |
| 13 | + private readonly loader: DataLoader<ID, ID>; |
| 14 | + |
| 15 | + constructor( |
| 16 | + private readonly db: EdgeDB, |
| 17 | + @Logger('alias-resolver') private readonly logger: ILogger, |
| 18 | + ) { |
| 19 | + this.loader = new DataLoader((x) => this.loadMany(x), { |
| 20 | + // Since this loader exists for the lifetime of the process |
| 21 | + // and there's no cache invalidation, we'll just use an LRU cache |
| 22 | + cacheMap: new LRU({ |
| 23 | + max: 10_000, |
| 24 | + }), |
| 25 | + }); |
| 26 | + } |
| 27 | + |
| 28 | + async resolve(value: ID): Promise<ID> { |
| 29 | + try { |
| 30 | + return await this.loader.load(value); |
| 31 | + } catch (e) { |
| 32 | + if (e instanceof NotFoundException) { |
| 33 | + this.loader.clear(value); // maybe it'll be there next request |
| 34 | + return value; // assume valid or defer error |
| 35 | + } |
| 36 | + throw e; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + async loadMany(ids: readonly ID[]): Promise<ReadonlyArray<ID | Error>> { |
| 41 | + const aliases = ids.filter((id) => { |
| 42 | + if (isUUID(id)) { |
| 43 | + return false; |
| 44 | + } |
| 45 | + return true; |
| 46 | + }); |
| 47 | + if (aliases.length === 0) { |
| 48 | + return ids; |
| 49 | + } |
| 50 | + |
| 51 | + this.logger.info('Resolving aliases', { ids: aliases }); |
| 52 | + const foundList = await this.db.run(this.query, { aliasList: aliases }); |
| 53 | + return ids.map((id) => { |
| 54 | + const found = foundList.find((f) => f.name === id); |
| 55 | + return found |
| 56 | + ? found.targetId |
| 57 | + : !aliases.includes(id) |
| 58 | + ? id |
| 59 | + : new NotFoundException(); |
| 60 | + }); |
| 61 | + } |
| 62 | + |
| 63 | + private readonly query = e.params( |
| 64 | + { aliasList: e.array(e.str) }, |
| 65 | + ({ aliasList }) => |
| 66 | + e.select(e.Alias, (alias) => ({ |
| 67 | + filter: e.op(alias.name, 'in', e.array_unpack(aliasList)), |
| 68 | + name: true, |
| 69 | + targetId: alias.target.id, |
| 70 | + })), |
| 71 | + ); |
| 72 | +} |
0 commit comments