Home > Enterprise >  NestJS - Recover only the data of the connected user
NestJS - Recover only the data of the connected user

Time:05-10

I have users who have one or more companies. And each company can have one or more offices. I want to retrieve the list of offices linked to a company by its ID according to the user connected.

What I do in my code below, I come to retrieve the logged in user via a user's custom Decorator. Then I retrieve these companies to then retrieve the offices. But, I fail to retrieve the companies of a user. I have this error because in User, there is no companies property.

[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)

I'm a bit lost, any idea?

My codes

// 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;
  },
);

CodePudding user response:

I would suggest you to search the companies through a query builder with the userId of User ,instead of trying to get the companies directly from the get-user decorator.

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