1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import {Getter} from '@loopback/core';
|
7 | import {DataObject, Options} from '../../common-types';
|
8 | import {EntityNotFoundError} from '../../errors';
|
9 | import {Entity} from '../../model';
|
10 | import {constrainFilter, EntityCrudRepository} from '../../repositories';
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | export interface ReferencesManyRepository<Target extends Entity> {
|
16 | |
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | get(options?: Options): Promise<Target>;
|
23 | }
|
24 |
|
25 | export class DefaultReferencesManyRepository<
|
26 | TargetEntity extends Entity,
|
27 | TargetIds,
|
28 | TargetRepository extends EntityCrudRepository<TargetEntity, TargetIds>,
|
29 | > implements ReferencesManyRepository<TargetEntity>
|
30 | {
|
31 | |
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | constructor(
|
38 | public getTargetRepository: Getter<TargetRepository>,
|
39 | public constraint: DataObject<TargetEntity>,
|
40 | ) {}
|
41 |
|
42 | async get(options?: Options): Promise<TargetEntity> {
|
43 | const targetRepo = await this.getTargetRepository();
|
44 | const result = await targetRepo.find(
|
45 | constrainFilter(undefined, this.constraint),
|
46 | options,
|
47 | );
|
48 | if (!result.length) {
|
49 |
|
50 | const id = 'constraint ' + JSON.stringify(this.constraint);
|
51 | throw new EntityNotFoundError(targetRepo.entityClass, id);
|
52 | }
|
53 | return result[0];
|
54 | }
|
55 | }
|