nexus
nexus copied to clipboard
objectType level resolver #1045
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!
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:
- I created
objectType
calledUser
which defines the basic structure of my user model. - I included field called
totalFollowing
that is not nullable, showing the total number of people that user is following people. - I made
totalFollowing
field as a resolver by usingresolve()
Not pretty sure if this was thing that you were looking for.
@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.