nexus icon indicating copy to clipboard operation
nexus copied to clipboard

objectType level resolver #1045

Open georgekrax opened this issue 3 years ago • 2 comments

I would like to create a field like this:

t.string("formattedLocation", {
  description: "Get the location of the #beach_bar formatted",
  resolve: async ({ id, ...hey }, __, { prisma }): Promise<string> => {
    const location = await prisma.beachBarLocation.findUnique({
      where: { beachBarId: +id },
      include: { region: true, city: true, country: true },
    });
    if (!location) return "";

      let formattedLocation: string[] = [];
      if (location.region) formattedLocation = [...formattedLocation, location.region.name];
      if (location.city) formattedLocation = [...formattedLocation, location.city.name]
      if (location.country) formattedLocation = [...formattedLocation, location.country.alpha2Code];
      return formattedLocation.join(", ");
  },
});

So, hey.location is not already filled. But the parent element does not have the location field already filled. What can I do? Should I create a local-only field in the Apollo Client and not on the server?

How can I create a format objectType resolver?

Every help is appreciated!

georgekrax avatar Feb 11 '22 17:02 georgekrax

I tried as below. I included the computed fields that does NOT go to DB, but rather server will calculate based on the data in my DB.

// Omitted 
t.nonNull.int("totalFollowing", {
      resolve({ id }) {
        return client.user.count({ where: { followers: { some: { id } } } });
      },
    });
// Omitted

So here's a workflow:

  1. I created objectType called User which defines the basic structure of my user model.
  2. I included field called totalFollowing that is not nullable, showing the total number of people that user is following people.
  3. I made totalFollowing field as a resolver by using resolve()

Not pretty sure if this was thing that you were looking for.

donghhan avatar Mar 13 '22 05:03 donghhan

@donghhan Thanks for your response!

Unfortunately, I know how to do this, and this is not my issue. Imagine there is a relation field, like an account one on an objectType called user. In the objectType of account, I want to have a calculated field, which is going to be of INT type, that is going to take the user parent object and resolve it in the INT field resolver.

I know it is confusing, but it is common with relations. Imagine an objectType called location, that is going to have fields of region, city & country, which are going to be models and be separate objectType with added information. Now, I want to have a string type of field called formattedLocation in the location objectType that is going to format the full location name for me. However, I cannot access the region, city & country fields on the formattedLocation resolver, because they are undefined.

georgekrax avatar Mar 17 '22 14:03 georgekrax