NestJS - 仅恢复已连接用户的数据

NestJS - Recover only the data of the connected user

我有用户拥有一家或多家公司。每个公司可以有一个或多个办事处。 我想根据连接的用户通过 ID 检索链接到公司的办公室列表。

我在下面的代码中所做的,是通过用户的自定义装饰器来检索登录的用户。然后我检索这些公司,然后检索办公室。但是,我无法检索用户的公司。我有这个错误是因为在用户中,没有公司 属性.

[Nest] 59645 - 09/05/2022, 00:28:18 ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'find') TypeError: Cannot read properties of undefined (reading 'find') at OfficeRepository.getOffices (/Users/ismaelmohamed/Documents/projects/melivy_projects/melivy_api/src/office/office.repository.ts:16:40) at processTicksAndRejections (node:internal/process/task_queues:96:5)

我有点迷茫,有什么想法吗?

我的代码

// office.repository.ts
async getOffices(companyId: string, user: User): Promise<Office[]> {
    const query = this.createQueryBuilder('office');
    query.where('office.companyId = :companyId', { companyId });
    console.log(user);

    if (user) {
      const companies = await user.companies;

      const currentCompany = companies.find(
        (company) => company.id === companyId,
      );

      if (currentCompany) {
        query.andWhere('office.id IN (:...officeIds)', {
          officeIds: currentCompany.offices.map((office) => office.id),
        });
      }
    }

    return await query.getMany();
  }

// office.service.ts
async getOffices(companyId: string, user: User): Promise<Office[]> {
    return this.officeRepository.getOffices(companyId, user);
  }

// office.controller.ts
async getOffices(
    @Param('id') id: string,
    @GetUser() user: User,
  ): Promise<Office[]> {
    return this.officeService.getOffices(id, user);
  }

// get-user.decorator.ts
export const GetUser = createParamDecorator(
  (data: string | undefined, ctx: ExecutionContext) => {
    const request: Express.Request = ctx.switchToHttp().getRequest();
    if (data) {
      return request.user[data];
    }

    return request.user;
  },
);

我建议您使用 UserId 的查询生成器搜索公司,而不是尝试直接从 get-user 装饰器中获取公司。

const companies_query = this.createQueryBuilder('companies');
 companies_query.where('companies.user_id = :user_id', { user.id });