2
votes

The graphql-tools documentation mentions that:

You don’t need to specify resolvers for every type in your schema. If you don’t specify a resolver, GraphQL.js falls back to a default one, which does the following:

  1. Returns a property from obj with the relevant field name, or
  2. Calls a function on obj with the relevant field name and passes the query arguments into that function

My question is: how can I specify that function to change the default behavior?

For example, maybe instead of just returning object.title when the client asks for the title field, I would like to return object.title.en, or object.title.fr, etc. depending on the current language.

It would be nice to be able to specify this as the default behavior without having to spell out resolver functions for every single field?

2
I think you'll have to write a function and reuse that for all fields, the shortest way I guessDane
It does seem like there's a way to override the default resolver function: apollographql.com/docs/apollo-server/setup.html#other So far no luck in getting it to actually do anything though.Sacha

2 Answers

1
votes

to keep compatibility with graphql draft you make a schema like this:

# schema.gql (shortly)
type Post {
 id: ID!
 title: TranlationConnection
}
type TranslationConnection {
 count: Int
 nodes: [TranslationNode]
}
type TranslationNode {
 # eg. 'en' 
 lang: String!
 # translated title in this eg.
 msgstr: String!
}

#query eg.
query post (id:1) {
 id
 title(lang:'en') {
  nodes {
   lang
   msgstr
  }
 }
}
1
votes

You can pass a fieldResolver method into the options for the apollo-server instance:

const server = new ApolloServer({ typeDefs, resolvers,
  fieldResolver: function (source, args, context, info) {
    console.log("Field resolver triggered!")
    return null;
  }
});