Skip to content

HasManyRepository should implement EntityCrudRepository? #5025

@Salketer

Description

@Salketer

Suggestion

The HasManyRepository is missing the *ById, exists and count methods. They would prove to be very handy...

Use Cases

Currently we have to forge the where clause to target entities by ID when working on a relation. This is error prone and more work than it should be.

For the *ById methods:

While routes like GET /project/12/milestone/3 could definitely be narrowed down to /milestone/3
Relation can be used in a multi-tenant architecture like so in a controller:

    this.tenantRepository.milestones(currentUserProfile.tenantId);

To find a milestone, making sure we return it only if it is owned by the current tenant:

async findById(
    @inject(SecurityBindings.USER) currentUserProfile: SscUserProfile,
    @param.path.number('id') id: number,
    @param.filter(CrmContact, {exclude: 'where'})
    filter?: FilterExcludingWhere<CrmContact>,
  ): Promise<CrmContact> {
    filter = filter || {};
    filter.limit = 1;
    const newFilter = Object.assign({}, filter, {where: {id}});
    return (await this.tenantRepository.milestones(currentUserProfile.tenantId).find(newFilter))[0];
  }

This gets cumbersome even if there's better ways to build the where filter like using constraints (?).

For the count method

Another use case if for the count method. We cannot efficiently use the relation to count as we need to use find for it! A worker could be to use the right repository and constrain it to the relation key...

// ... the Where filter should be modified not just thown away but meh
   return this.mileStoneRepository.count({tenantId:currentUserProfile.tenantId});
//or
   const newFilter = {where,fields:{id:true}}; //include the least fields possible.
   return (await this.tenantRepository.milestones(currentUserProfile.tenantId).find(newFilter)).length;

Examples

return this.tenantRepository.milestones(currentUserProfile.tenantId).findById(id);
return this.tenantRepository.milestones(currentUserProfile.tenantId).count(where);

Acceptance criteria

  • implement count, exists and *ById for hasManyRepository
  • implement exists and *ById for hasOneRepository

Metadata

Metadata

Assignees

No one assigned

    Labels

    RelationsModel relations (has many, etc.)feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions