Filter on findById is ignoring the where clause
Steps to reproduce
Submit to any findById call the optional filter argument with a where clause.
Current Behavior
The where clause is beeing ignored and the item is returned in all cases.
Expected Behavior
The item will only be returned if it matches the where clause.
Additional information
This is needed to add item level security based on filters by an Interceptor.
Related Issues
https://github.com/strongloop/loopback-next/issues/1721 Although this issue is about the include and fields of the filter
Acceptance Criteria
_Getting from @bajtos' comment
- [ ] fix TypeScript definitions and our API docs to make it clear which filter properties are accepted by findById function.
I think you'll find that is by design. findById is simply finding the item with the supplied Id. I suggest that you use find and supply the where clause that includes the item Id for your case.
When it takes a filter as argument I expect it uses this filter object.
I don't know how findById works internally, but from the signature it looks like a shortened version for find with the where, which has the benefit, that you do not need to know the name of the id.
For now I am doing excatly that overwriting the findById function in all my repos with a version that uses find with the id added to the where clause.
@mmbabel , are you using the API Explorer to test?
No, I am using Postman to issue the HTTP requests. The filter is also not coming by the request at all, the filter gets populated by an Interceptor and I tested that the filter is there.
As said, as a workaround I am now overwriting the standard findById in all repositories like in this example:
async findById(
id: typeof Firm.prototype.id,
filter?: Filter<Firm>,
options?: any,
): Promise<Firm> {
if(filter === undefined) {
filter = (new FilterBuilder()).build() as Filter<Firm>;
}
if(filter.where === undefined) {
filter.where = (new WhereBuilder({FirmID: id})).build();
} else {
filter.where = (new WhereBuilder(filter.where)).and({FirmID: id}).build();
}
const res = await this.findOne(filter, options);
if(!res) { console.log(id);
try {
await super.findById(id);
} catch (e) {
throw e;
}
throw new HttpErrors.Forbidden("You do not have permissions to view this item.");
}
return res;
}
this works but is ugly,
@bajtos, could you please help on this? Thanks.
IMO, the current behavior is intentional. We should fix TypeScript definitions and our API docs to make it clear which filter properties are accepted by findById function.
Having said that, I see how it could be useful to add additional restrictions to findById calls. Let's open a new issue (a feature request) for that please.
Fixed by https://github.com/strongloop/loopback-next/pull/4745