Aleksei V.
Aleksei V.

Reputation: 21

Bookshelf.js withRelated TypeScript error

So, in my app I have categories and articles that are interrelated. At first I retrieve all of categories and there are articles inside each of them. The problem is I wanna filter both categories and articles inside it by userId but I don't know how to do it since I'm using TypeScript and getting error.

const articlesInCategories = (await (await ArticleCategory.fetchAll())
    .query((qb: QueryBuilder) => {
        qb.innerJoin(Table.ARTICLE_CATEGORY_RELATION, 'article_category_relation.category_id', 'article_category.id' );
        qb.innerJoin(Table.ARTICLE, 'article.id', 'article_category_relation.article_id');

        // Next condition is only for Categories not for Articles inside it
        if (roleId == Role.manager) {
            qb.where('user_id', userId);
        }

        qb.orderBy('id', 'desc');
      })
      .fetch({
          withRelated: [{'articles': function (qb: QueryBuilder) => qb.where('user_id', userId)}]
      }));

If userId for example would be 1, wanna get only those categories which contain articles written by user with id 1. MOREOVER, not all articles, but ONLY written by user with id 1.

I have TS error near withRelated: Type '{ articles: (qb: QueryBuilder) => QueryBuilder<any, any[]>; }' is not assignable to type 'string'.ts(2322)

Can you help me please with TypeScript in such case or suggest any alternative ways to achieve what I want?

Upvotes: 1

Views: 293

Answers (1)

Aleksei V.
Aleksei V.

Reputation: 21

Well, that was the wrong approach. If I do the following, it works brilliant:

const articlesInCategories = await new ArticleCategory().query((qb: QueryBuilder) => {
    .query((qb: QueryBuilder) => {
        qb.innerJoin(Table.ARTICLE_CATEGORY_RELATION, 'article_category_relation.category_id', 'article_category.id' );
        qb.innerJoin(Table.ARTICLE, 'article.id', 'article_category_relation.article_id');

        if (roleId == Role.manager) {
            qb.where('user_id', userId);
        }

        qb.orderBy('id', 'desc');
      })
      .fetch({
          withRelated: [{ 'articles': (qb: QueryBuilder) => qb.where('user_id', userId) }]
      }));

Upvotes: 1

Related Questions