GraphQL Apollo schema delegation: info.mergeInfo is undefined - graphql

I followed the official doc to delegate a graphql schema which indicates that in order to do so, one must use the method delegateSchema that can be found on the property mergeInfo of the argument info passed down to resolvers:
resolver: (parent, args, ctx, info) => {
return info.mergeInfo.delegateSchema({
// Schema delegation options...
})
}
But there is no property mergeInfo on the info argument ! And so I get this error message: GraphQL Error GraphQL error: Cannot read property 'delegateToSchema' of undefined which is normal considering these are the top-level properties of info:
console.log(Object.keys(info))
[
'fieldName',
'fieldNodes',
'returnType',
'parentType',
'path',
'schema',
'fragments',
'rootValue',
'operation',
'variableValues',
'cacheControl'
]
It even looks like that mergeInfo is not mentioned in the type definition of the GraphQLResolveInfo object
Is the doc outdated or am I missing something ?
Thanks

mergeInfo is only injected into the info object when you use mergeSchemas to stitch together two or more schemas. Additionally, it will only be injected into the resolvers for fields you add as part of the schema stitching -- resolvers for the schemas will not be impacted (it doesn't really make sense to delegate to another schema in the context of one of the existing schemas anyway).
Here's a simple example:
const { makeExecutableSchema, mergeSchemas } = require('graphql-tools')
const schemaA = makeExecutableSchema({
typeDefs: `
type Query {
foo: String
}
`,
})
const schemaB = makeExecutableSchema({
typeDefs: `
type Query {
bar: String
}
`,
})
const typeDefs = `
extend type Query {
foobar: String
}
`
const schema = mergeSchemas({
schemas: [schemaA, schemaB, typeDefs],
})
Here, the resolvers for foo and bar will not have access to mergeInfo, but the resolver for foobar will.

Related

Access context from Apollo GraphQL mutation field directive

I have an input type like this:
input PetGiraffe {
name: String #addUserLastName
}
Inside the directive, I need access to the request's context, so that I can add the user's last name to the giraffe's name. Here's the relevant part of what I've got so far:
const addUserLastNameDirective = {
typeDefs: gql`directive #addUserLastName on INPUT_FIELD_DEFINITION`,
transformer: (schema: GraphQLSchema, directiveName = 'addUserLastName') => {
return mapSchema(schema, {
[MapperKind.INPUT_OBJECT_FIELD]: (fieldConfig, fieldName, typeName, schema) => {
const directive = getDirective(schema, fieldConfig, directiveName)?.[0];
if (directive) {
// Need context in here because the user is in the context.
}
},
});
},
};
For queries, I understand you can override the fieldConfig.resolve method and get access to the context that way. But if I try that with this mutation, it throws: field has a resolve property, but Input Types cannot define resolvers.
The closest I could find was this from the graphql-tools docs, but that doesn't solve my problem of accessing the context.

grapql#16 dropped long-deprecated support for positional arguments, please pass an object instead

const { ApolloServer, gql } = require('apollo-server');
// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
const typeDefs = gql`
# Comments in GraphQL strings (such as this one) start with the hash (#) symbol.
# This "Book" type defines the queryable fields for every book in our data source.
type Book {
title: String
author: String
}
# The "Query" type is special: it lists all of the available queries that
# clients can execute, along with the return type for each. In this
# case, the "books" query returns an array of zero or more Books (defined above).
type Query {
books: [Book]
}
`;
const books = [
{
title: 'The Awakening',
author: 'Kate Chopin',
},
{
title: 'City of Glass',
author: 'Paul Auster',
},
];
// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
Query: {
books: () => books,
},
};
// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({ typeDefs, resolvers });
// The `listen` method launches a web server.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
So this is the code I copied from official Apollo GraphQL site. I use graphql 16.3 and apollo-server 2.25.3.
I don't know what the message told me what to fix. Help me please. Thank you guys so much!
From their documentation it seems that apollo-server 2 don't support graphql >15
https://www.apollographql.com/docs/apollo-server/migration/
I would either migrate to apollo-server 3 or downgrade graphql to version 15.

how to use enum in apollo-client?

the enum define in OrderTypesEnum.gql
enum OrderTypes {
full_buy
pink_buy
}
import OrderTypesEnum.gql file
import OrderTypes from '#/graphql/OrderTypesEnum.gql'`
but, How to get enum in code ?
I use OrderTypes.full_buy get some error:
self.$apollo.mutate({
mutation: createOrder,
variables: {
subjectId: self.subject.id,
types: OrderTypes.full_buy
}
})
Mutation createOrderMutation error: Invariant Violation: Schema type definitions not allowed in queries. Found: "EnumTypeDefinition"
the inspect of OrderTypes type enum
Prerequisites:
< SomeEnumType > is defined in GraphQL schema (server side, no client configuration needed)
Let's assume we have:
enum SomeEnumType {
OPTION1,
OPTION2,
OPTION3
}
Apollo Client should be configured appropriate way and connected with the GraphQL API.
Then on the client side:
export const OUR_MUTATION = gql`
mutation ourMutation($foo: SomeEnumType){
ourMutation(foo: $foo){
bar
}
}
`
Only by doing this, we can pass an enum as a variable in our query or mutation. For example, with useMutation hook we can now mutate as follows:
const [ourMutation] = useMutation(OUR_MUTATION, {
variables: {
foo: "OPTION2"
},
Since the type definition in gql tag equals the definition in Schema, GraphQL recognizes a variable as an enum type despite giving it as a string.
If we want to pass an enum to variables using typescript enums we can do it as follows:
enum SomeEnumType {
OPTION1 = 0,
OPTION2 = 1,
OPTION3 = 2
}
const [ourMutation] = useMutation(OUR_MUTATION, {
variables: {
foo: SomeEnumType[SomeEnumType.OPTION1]
},
UPDATE: String enums and type generation
Personally, I recommend using string enums if possible. The usage of string enums is more straightforward.
enum SomeEnumType {
OPTION1 = "OPTION1",
OPTION2 = "OPTION2",
OPTION3 = "OPTION3"
}
...
...
variables: {
foo: SomeEnumType.OPTION1
}
For next-level coding, enum types, and all other type definitions can be automatically generated to the frontend with graphql-codegen. I really recommend using this approach, since backend schema updates and additions directly can be directly reflected in your frontend code revealing bugs and helping you code faster and more reliable.
As the error message is suggesting, Schema type definitions not allowed in queries., you can't add an enum definition in an operation document (ExecutableDefinition). You can only have operations (query, mutation, or subscription), or fragments definitions. That is, this is invalid:
enum OrderTypes {
FULL_BUY
PINK_BUY
}
mutation createOrderMutation {
...
}
If you want to define a local enum on your client, you can use the typeDefs property during ApolloClient initialization:
const client = new ApolloClient({
cache,
typeDefs: gql`
enum OrderTypes {
FULL_BUY,
PINK_BUY
}
`,
});
And then you'll be able to see the OrderTypes enum on client-side introspection (i.e Apollo extension).
Pay attention to the client-side highlight: if you try to send a request with this enum for a non-client field (i.e without the #client directive) and it makes through your server, you'll get a schema error saying that the enum type does not exist, unless you define it on your backend.

Explanation for different implementations of resolver function in graphql

I've been reading through the graphQL docs and found that they've explained the implementation of the graphql server in 2 ways: one using graphql-yoga which is a fully featured graphql server and another one is using graphql, express-graphql and express. In both cases, we pass the schema and resolver functions while creating the server instance.
But the implementation of resolver function differs. While using graphql-yoga, the resolver function is provided with 4 arguments which contains information about the parent object, arguments received, context, info. whereas in the other case (using graphql), the resolver function only gets the arguments object.
Why is that so ? If I want the info, context objects, how do I get it ?
Using graphql-yoga example: https://graphql.org/learn/execution/
Using graphql example: https://graphql.github.io/graphql-js/mutations-and-input-types/
// Code example using graphql
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
var schema = buildSchema(`
type Query {
rollDice(numDice: Int!, numSides: Int): [Int]
}
type Mutation {
addDice(numDice: Int): String
}
`);
var root = {
rollDice({numDice, numSides}) {
return [1, 2];
},
addDice({numDice}) {
console.log("Adding something");
return "Added";
}
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
// Code example using graphql-yoga
let graphqlServer = require("graphql-yoga");
const typeDefs = `
type Query {
rollDice(numDice: Int!, numSides: Int): [Int]
}
type Mutation {
addDice(numDice: Int): String
}
`;
const resolvers = {
Query: {
rollDice(parent, args, context, info) {
console.log(args.numDice);
console.log(args.numSides);
return [1, 2];
}
},
Mutation: {
addDice(parent, args, context, info) {
console.log(args.numDice);
return "Added";
}
}
};
const server = new graphqlServer.GraphQLServer({
typeDefs,
resolvers
});
server.start(() => {
console.log("server started on localhost:4000");
});
Difference between these 2 code snippets:
The resolver functions are present inside appropriate types (i.e. Query, Mutation) in one case. In the other case, they are present inside one root object. This means that I can have methods with same name in Query and Mutation in the first case, whereas in the second case that's not possible since they are keys of a single object and keys should be unique.
Why is this so ? Am I basically missing something ? How can the implementation details differ from one package to another ?
REAL TALK: the GraphQL.js docs are not that great. In my opinion, they never should have used examples with buildSchema in the first place because it understandably leads to this kind of confusion.
GraphQL.js (i.e. the graphql package) is the JavaScript implementation of GraphQL. Building a schema in GraphQL.js is done programmatically, by constructing an instance of the GraphQLSchema class:
const userType = new GraphQLObjectType({
name: 'User',
fields: {
id: {
type: GraphQLID,
},
email: {
type: GraphQLString,
},
},
});
const queryType = new GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: userType,
resolve: () => ({ id: 1, email: 'john.doe#example.com' }),
},
},
});
const schema = new GraphQLSchema({
query: queryType,
})
If we print this schema in Schema Definition Language (SDL), it looks like this:
type Query {
user: User
}
type User {
id: ID
email: String
}
Working with SDL is much easier than having to write out all that code. However, GraphQL.js does not provide a way to build a fully-featured schema from SDL. It does provide a buildSchema function, but this utility constructs a schema without any resolvers (and a number of other features like union/interface type resolution).
The graphql-tools package provides a makeExecutableSchema function that lets you build a schema from SDL and a resolver map object. This is what's used under the hood by apollo-server and graphql-yoga. makeExecutableSchema constructs a schema from SDL using buildSchema and then mutates the resulting object, adding the resolvers in after the fact.
In GraphQL.js, the resolve function (or resolver) for a field takes four parameters -- the parent value, the field's arguments, the context and a GraphQLResolveInfo object. If we're creating a GraphQLObjectType like userType in the above example, this is the optional function we can provide for each of the fields in our object. This is the same function you define when you construct a resolver map to use with graphql-yoga. This is the only implementation of a field resolver.
So what's the deal with buildSchema??
The examples in the docs take advantage of GraphQL's default field resolver:
export const defaultFieldResolver: GraphQLFieldResolver<any, *> = function(
source,
args,
contextValue,
info,
) {
if (typeof source === 'object' || typeof source === 'function') {
const property = source[info.fieldName];
if (typeof property === 'function') {
return source[info.fieldName](args, contextValue, info);
}
return property;
}
};
As you can see, the default resolution logic looks for a property with the same name as the field on the source (parent) value. In our example above, the user resolver returns {id: 1, email: 'john.doe#example.com'} -- this is the value the field resolves to. The field is of the type User. We do not have a resolver defined for our id field, so the default resolver does its thing. The id field resolves to 1 because that's the value of the property named id on the parent object the resolver receives.
However, the parent value can also be a function instead of an object. If it's a function, it gets called first and then the return value is used. What does the function get called with? Well, it can't pass it a parent value (because of infinite recursion), but it can pass it the remaining three parameters (args, context and info). So that's what it does.
Now for the magic trick 🎩🐇
In our example, I can omit the resolver for the user field and pass a function to the root value instead.
const root = {
user: () => ({id: 1, email: 'john.doe#example.com'})
}
The root object is just an optional object that's passed down as the parent value to resolvers at the root level (like your Query or Mutation types). Otherwise, those resolvers would not have a parent value.
Query is an operational root type -- it serves as an "entry point" to the rest of your schema. Any fields on the Query type will be passed the root object as the parent value. If I omit a resolver for the user field, the default resolver will 1) examine the parent object for a property with the same name, 2) find a property and determine that it's a function, 3) call the function, 4) resolve the field to the return value of the function.
TADA!
However, because the function is called by the default resolver, and is not used as a resolver itself, it will only receive the three aforementioned parameters, instead of 4.
This is a neat way to work around not being able to actually provide custom resolvers for a schema, but it's very limited. It only works for root types, so we can't similarly provide fake resolvers for User fields or other types. We can't use interfaces or unions in our schema because we can't provide resolveType functions. And so on...
Hopefully that provides some clarity. And hopefully we can get the docs updated in the near future to avoid all this confusion in the first place.

How to pass existing GraphQLSchema object to Apollo makeExecutableSchema function

How can I pass an existing GraphQLSchema object like graphql-iso-date to the makeExecutableSchema function, to use it along with my string-defined types and resolver functions? Say in following type definition I want the date property to be GraphQLDate from the mentioned package.
import { GraphQLDate, GraphQLTime, GraphQLDateTime } from 'graphql-iso-date';
let typeDefs = [];
typeDefs.push(`
type MyType {
date: Date
}
`);
let resolvers = {
Query: () => { /* ... */ },
};
makeExecutableSchema({ typeDefs, resolvers });
It turns out the resolvers map, which is passed to the makeExecutableSchema does accept the GraphQLScalarType and the Date type is scalar. We still have to add the types into the typeDefs manually though...
typeDefs.push('scalar Date');
and
resolvers.Date = GraphQLDate;
So I've created a module of external scalars in my project and am doing
import externalTypes from './externalTypes';
import printType from 'graphql';
// Define my typeDefs and resolvers here
for (let externalType of externalTypes) {
let { name } = externalType;
typeDefs.push(printType(externalType));
resolvers[name] = externalType;
}
makeExecutableSchema({ typeDefs, resolvers });
I figured it by trial/failure and only then found it in the docs, thus posting. Also I still don't know how would I add a non-scalar type this way (well other than manually writing it's type definition).
Also the printType function, which prints schema definition from type object passed, becomes handy here (see this question for more detail).

Resources