UNPKG

2.02 kBPlain TextView Raw
1// Copyright IBM Corp. and LoopBack contributors 2018,2020. All Rights Reserved.
2// Node module: @loopback/repository
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6import {Getter} from '@loopback/core';
7import {DataObject, Options} from '../../common-types';
8import {EntityNotFoundError} from '../../errors';
9import {Entity} from '../../model';
10import {constrainFilter, EntityCrudRepository} from '../../repositories';
11
12/**
13 * CRUD operations for a target repository of a ReferencesMany relation
14 */
15export interface ReferencesManyRepository<Target extends Entity> {
16 /**
17 * Gets the target model instance
18 * @param options
19 * @returns A promise resolved with the target object or rejected
20 * with an EntityNotFoundError when target model instance was not found.
21 */
22 get(options?: Options): Promise<Target>;
23}
24
25export class DefaultReferencesManyRepository<
26 TargetEntity extends Entity,
27 TargetIds,
28 TargetRepository extends EntityCrudRepository<TargetEntity, TargetIds>,
29> implements ReferencesManyRepository<TargetEntity>
30{
31 /**
32 * Constructor of DefaultReferencesManyEntityCrudRepository
33 * @param getTargetRepository - the getter of the related target model repository instance
34 * @param constraint - the key value pair representing foreign key name to constrain
35 * the target repository instance
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 // We don't have a direct access to the foreign key value here :(
50 const id = 'constraint ' + JSON.stringify(this.constraint);
51 throw new EntityNotFoundError(targetRepo.entityClass, id);
52 }
53 return result[0];
54 }
55}