0

Here is a mutation to create a new Company:

mutation CompanyCreate($input: RegisterInput!) {
  companyCreate(input: $input) {
    ...CompanyFields
  }
}

Creating this company triggers also the creation of other entities, such as User These entities are then fetched through the CompanyFields fragment:

fragment CompanyFields on Company {
  id
  name
  employees {
    ...UserFields
  }
}

When called, my NestJS mutation creates the right entities:

@Mutation(() => Company, { name: 'companyCreate' })
async companyCreate(
  @Args('input', { type: () => RegisterInput })
  input: RegisterInput,
): Promise<Company> {
  const company = await this.companyRepository.create(input.company);
  await company.save();

  [user creation...]

  const fullCompany = await this.companyRepository.findOne({
    where: { id: company.id },
  });

  if (!fullCompany) {
    throw new NotFoundException(
      `Registration failed for company id=${company.id as string}`,
    );
  }

  return fullCompany;
}

BUT the returned entity is not matching what is was queried. To do so, I have to add manually the relations:

const fullCompany = await this.companyRepository.findOne({
  where: { id: company.id },
  relations: [
    'employees',
  ],
});

This is of course not ideal.

I should be able to fetch the asked relations, or better, GraphQL should deal with it automatically.

How can I, from the mutation, be assured that the returned entity loads the right relations?

frinux
  • 2,052
  • 6
  • 26
  • 47

0 Answers0