How to add multiple resolvers in a type (Apollo-server) - graphql

I have used express-graphql and there i used to do something like this.
const SubCategoryType = new ObjectType({
name: 'SubCategory',
fields: () => ({
id: { type: IDType },
name: { type: StringType },
category: {
type: CategoryType,
resolve: parentValue => getCategoryBySubCategory(parentValue.id)
},
products: {
type: List(ProductType),
resolve: parentValue => getProductsBySubCategory(parentValue.id)
}
})
});
Here I have multiple resolvers, id and name are fetched directly from the result. and the category and products have there own database operation. and so on.
Now I am working on apollo-server and I can't find a way to replicate this.
for example I have a type
type Test {
something: String
yo: String
comment: Comment
}
type Comment {
text: String
createdAt: String
author: User
}
and in my resolver I want to split it up, for example something like this
text: {
something: 'value',
yo: 'value',
comment: getComments();
}
NOTE: this is just a representation of what I need.

You can add type-specific resolvers to handle specific fields. Let's say you have the following schema (based on your example):
type Query {
getTest: Test
}
type Test {
id: Int!
something: String
yo: String
comment: Comment
}
type Comment {
id: Int!
text: String
createdAt: String
author: User
}
type User {
id: Int!
name: String
email: String
}
Let's also assume you have the following DB methods:
getTest() returns an object with fields something, yo and
commentId
getComment(id) returns an object with fields id, text, createdAt and userId
getUser(id) returns an object with fields id, name and email
Your resolver will be something like the following:
const resolver = {
// root Query resolver
Query: {
getTest: (root, args, ctx, info) => getTest()
},
// Test resolver
Test: {
// resolves field 'comment' on Test
// the 'parent' arg contains the result from the parent resolver (here, getTest on root)
comment: (parent, args, ctx, info) => getComment(parent.commentId)
},
// Comment resolver
Comment: {
// resolves field 'author' on Comment
// the 'parent' arg contains the result from the parent resolver (here, comment on Test)
author: (parent, args, ctx, info) => getUser(parent.userId)
},
}
Hope this helps.

Related

What is a correct return type of a GraphQL resolve function?

I faced with an issue that can't resolve on my own. Let's go through it step by step to point out the problem.
I have a mutation bookAppointment which returns an Appointment object
GraphQL schema says that this object should return 4 properties: id, date, specialist, client.
To follow the GraphQL-style the specialist and client properties should be a field level resolvers
To fetch this objects I need pass specialistId to the specialist field level resolver, as well as clientId to the client field level resolver.
At this point a problem arises.
The field level resolvers of client, specialist expects that root mutation returns fields like clientId and specialistId. But GraphQL syntax and types that were generated by that syntax doesn't include this props (make sense).
How to "extend" the return type of the resolver and its interface BookAppointmentPayload to make me and TypeScript happy?
This is my GraphQL schema
type Client {
id: ID!
name: String!
}
type Specialist {
id: ID!
name: String!
}
type Appointment {
id: ID!
date: Date!
client: Client!
specialist: Specialist!
}
input BookAppointmentInput {
date: Date!
userId: ID!
specialistId: ID!
}
type BookAppointmentPayload {
appointment: Appointment!
}
type Mutation {
bookAppointment(input: BookAppointmentInput!): BookAppointmentPayload!
}
This is TypeScript representation of GraphQL schema
interface Client {
id: string
name: string
}
interface Specialist {
id: string
name: string
}
interface Appointment {
id: string
date: Date
client: Client
specialist: Specialist
}
interface BookAppointmentPayload {
appointment: Appointment
}
Here I define my resolvers objects
const resolvers = {
...
Mutation: {
bookAppointment: (parent, args, context, info): BookAppointmentPayload => {
return {
appointment: {
id: '1',
date: new Date(),
clientId: '1', // This prop doesn't exist in the TypeScript interface of Appointment, but is required for the field-level resolver of a `client` prop
specialistId: '1' // This prop doesn't exist int he TypeScript interface of Appointment, but is required for the field-level resolver of a `specialist` prop
}
}
}
},
Appointment: {
client: (parent, args, context, info) => {
// I need a clientId (e.g. args.clientId) to fetch the client object from the database
return {
id: '1',
name: 'Jhon'
}
},
specialist: (parent, args, context, info) => {
// I need a specialistId (e.g. args.specialistId) to fetch the specialist object from the database
return {
id: '1',
name: 'Jane'
}
}
}
}
Solution that come to my mind:
Create an interface which represent "actual" return type of the resolver
...
interface Apppointment {
id: string
date: Date
clientId: string // instead of `client: Client`
specialistId: string // instead of `specialist: Specialist`
}
interface BookAppointmentPayload {
appointment: Appointment
}
...
But this doesn't reflect the GraphQL type. Also tools like graphql-generator generates the type with actual objects that should be included in the response, not the fields that are going to be used by field-level resolvers. (Am I wrong?)
I would like to know how you're solving such issue?
I've been investigating this problem quite a lot and have come to the following conclusion.
Create an interface which represent "actual" return type of the resolver
Most of the time the return type of the resolver function (in JavaScript) doesn't match the type that was declared in the GraphQL SDL
For instance,
# GraphQL SDL
type Appointment {
id: String!
client: User!
specialist: Specialist!
}
type BookAppointmentInput { ... }
type BookAppointmentPayload {
appointment: Appointment!
}
type Mutation {
bookAppointment: (input: BookAppointmentInput!): BookAppointmentPayload!
}
interface AppointmentDatabaseEntity {
id: string
clientId: string // In GraphQL-world this prop is an object, but not in JS. Use this prop in field-level resolver to fetch entire object
specialistId: string // In GraphQL-world this prop is an object, but not in JS. Use this prop in field-level resolver to fetch entire object
}
interface BookAppointmentPayload {
appointment: AppointmentDatabaseEntity // The return type SHOULDN'T be equal to the GraphQL type (Appointment)
}
const resolvers = {
Mutatiuon: {
bookAppointment: (parent, args, context, info) => {
const appointment = { id: '1', specialistId: '1', clientId: '1' }
return {
id: appointment.id,
specialistId: appointment.specialistId, // Pass this prop to the child resolvers to fetch entire object
clientId: appointment.clientId // Pass this prop to the child resolvers to fetch entire object
}
}
},
Appointment: {
client: (parent: AppointmentDatabaseEntity, args, context, info) => {
const client = database.getClient(parent.clientId) // Fetching entire object by the property from the parent object
return {
id: client.id,
name: client.name,
email: client.email
}
},
specialist: (parent: AppointmentDatabaseEntity, args, context, info) => {
const specialist = database.getSpecialist(parent.specialistId) // Fetching entire object by the property from the parent object
return {
id: specialist.id,
name: specialist.name,
email: specialist.email
}
}
}
}
But this doesn't reflect the GraphQL type
As far as I understand it is okay
Also tools like graphql-generator generates the type with actual objects that should be included in the response, not the fields that are going to be used by field-level resolvers. (Am I wrong?)
Yes. I was wrong. The graphql-generator has a configuration file that can be used to replace default generated types with the types that you expect your resolvers to return. This option is called mappers.
plugins
config:
mappers:
User: ./my-models#UserDbObject # User is GraphQL object, which will be replaced with UserDbObject
Book: ./my-modelsBook # Same rule goes here
I don't want to go into details of how to configure it and use, but you can check the links that helped me to understand this
Documentation (check the mappers chapter)
Great explanation by
Jamie Barton (YouTube)
If you disagree with my conclusions or you have a better understanding of how to handle it feel free to leave a comment

graphql: single mutation or one mutation per type

I have a GraphQL schema like this:
type User {
id: ID
name: String
email: String
addresses: [UserAddress]
}
type UserAddress {
id: ID
city: String
country: String
}
I always have doubts about how to make the best design for mutations. (I'm using apollo + prisma)
These are my options:
1) One single mutation
I need to create this mutation and input type:
input userAddressInput {
id: ID
city: String
country: String
}
mutation updateUser (
id: ID
name: String
email: String
addresses: UserAddressInput
): User
Then I execute mutations like this:
mutation updateUserData($id: ID, $name: String, $email: String) {
updateUser(id: $id, name: $name, email: $email) {
id
name
email
}
}
mutation updateUserAddress($id: ID, $userAddress: UserAddressInput) {
updateUser(id: $id, userAddress: $userAddress) {
id
addresses {
id
city
country
}
}
}
And resolvers like this:
Mutation: {
updateUser: (_, args) => {
if (args.name || args.email) {
// update model User by args.userData.id
}
if (args.userAddress) {
// update model UserAddress by args.userAddress.id
}
}
}
2) One mutation per type
I don't need to create any input type but I need two mutations:
mutation updateUser (
id: ID
name: String
email: String
): User
mutation updateUserAddress (
id: ID
city: String
country: String
): UserAddress
Then mutations like this:
mutation updateUser($id: ID, $name: String, $email: String) {
updateUser(id: $id, name: $name, email: $email) {
id
name
email
}
}
mutation updateUserAddress($id: ID, $city: String, $country: String) {
updateUserAddress(id: $id, city: $city, country: $country) {
id
city
country
}
}
And resolvers like this:
Mutation: {
updateUserAddress: (_, args) => {
// update model UserAddress by args.id
}
updateUser: (_, args) => {
// update model User by args.id
}
}
What is the best way to deal with such cases?
It depends what your use case is.
Does your GUI allow for update of a user's addresses without also updating the user info? If so you will likely need a separate mutation for updating only the addresses.
If you are allowing user and addresses to be edited and saved as one operation then individual mutations would require you to send multiple HTTP requests (one per mutation).
Do you need to update the user and addresses as an atomic transaction (i.e. all or nothing)? If so then you should use a single mutation.

graphql conditional subquery based on parent field

What is the approach when your subquery needs some field from parent to resolve?
In my case owner_id field from parent is needed for owner resolver, but what should i do if user will not request it?
Should i somehow force fetch owner_id field or skip fetching owner when owner_id is not in request?
Problematic query:
project(projectId: $projectId) {
name
owner_id <--- what if user didn't fetch this
owner {
nickname
}
}
Graphql type:
type Project {
id: ID!
name: String!
owner_id: String!
owner: User!
}
And resolvers:
export const project = async (_, args, ___, info) => {
return await getProjectById(args.projectId, getAstFields(info))
}
export default {
async owner(parent, __, ___, info) {
return await getUserById(parent.owner_id, getAstFields(info))
},
}
Helper functions that doesn't matter:
export const getUserById = async (userId: string, fields: string[]) => {
const [owner] = await query<any>(`SELECT ${fields.join()} FROM users WHERE id=$1;`, [userId])
return owner
}
export const getAstFields = (info: GraphQLResolveInfo): string[] => {
const { fields } = simplify(parse(info) as any, info.returnType) as { fields: { [key: string]: { name: string } } }
return Object.entries(fields).map(([, v]) => v.name)
}
You can always read owner_id in project type resolver.
In this case ... modify getAstFields function to accept additional parameter, f.e. an array of always required properties. This way you can attach owner_id to fields requested in query (defined in info).
I was thinking that resolver will drop additional props internally.
It will be removed later, from 'final' response [object/tree].

How to define graphql query in schema with exactly one of two parameters required [duplicate]

I'm just getting to grips with GraphQL,
I have set up the following query:
​
type: UserType,
args: {
id: { name: 'id', type: new GraphQLNonNull(GraphQLID) },
email: { name: 'email', type: new GraphQLNonNull(GraphQLString) }
},
resolve: (root, { id, email }, { db: { User } }, fieldASTs) => {
...
}
I would like to be able to pass either an 'id' or 'email' to the query, however, with this setup it requires both an id and email to be passed.
Is there a way to set up the query so only one argument is required, either id or email, but not both?
There's no built-in way to do that in GraphQL. You need to make your arguments nullable (by removing the GraphQLNonNull wrapper type from both of them) and then, inside your resolver, you can just do a check like:
resolve: (root, { id, email }, { db: { User } }, fieldASTs) => {
if (!id && !email) return Promise.reject(new Error('Must pass in either an id or email'))
if (id && email) return Promise.reject(new Error('Must pass in either an id or email, but not both.'))
// the rest of your resolver
}
Define an interface credentials and have that implemented as id or email.

How do I set up GraphQL query so one or another argument is required, but not both

I'm just getting to grips with GraphQL,
I have set up the following query:
​
type: UserType,
args: {
id: { name: 'id', type: new GraphQLNonNull(GraphQLID) },
email: { name: 'email', type: new GraphQLNonNull(GraphQLString) }
},
resolve: (root, { id, email }, { db: { User } }, fieldASTs) => {
...
}
I would like to be able to pass either an 'id' or 'email' to the query, however, with this setup it requires both an id and email to be passed.
Is there a way to set up the query so only one argument is required, either id or email, but not both?
There's no built-in way to do that in GraphQL. You need to make your arguments nullable (by removing the GraphQLNonNull wrapper type from both of them) and then, inside your resolver, you can just do a check like:
resolve: (root, { id, email }, { db: { User } }, fieldASTs) => {
if (!id && !email) return Promise.reject(new Error('Must pass in either an id or email'))
if (id && email) return Promise.reject(new Error('Must pass in either an id or email, but not both.'))
// the rest of your resolver
}
Define an interface credentials and have that implemented as id or email.

Resources