I have a custom repository for each entity/module (I'm working with NestJS). I know that this is a lot of repeated code and I may refactor it in order to use a generic repository later, but currently I'm focused on making a simple working MVP.
My current doubt is: I have some entity specific scenarios to get data. eg. get all articles associated to an user.
Should I implement a repository method like:
// In the repository
async getByUserId(userId: string): Promise<Article[]> {
...
}
Or should I implement this kind of logic in the service layer, using the getAll and filtering it within the service, eg:
// In the service
async getByUserId(userId: string) Promise<Article[]> {
const articles = await this.articleRepository.getAll();
const filteredArticles = articles.filter(article => article.userId == userId);
return filteredArticles;
}
There are multiple cases where this kind of 'domain' specific logic happens and I'd like to define a pattern that follows best practices and follow it throughout the codebase.
EDIT: After @Philip Kendall's answer, it is clear that leaving this kind of logic to the service is a bad idea, so my question has shifted: Should I create many specific gets, as described above, or should I pass options to a more general get, like the following:
export type GetArticleOptions = {
id?: string;
userId?: string;
};
async getAll(options?: GetArticleOptions): Promise<Article[]> {
const opt = { where: { ...options } };
return await this.articleRepository.find(opt);
}
options
object to the get method in the repository...