Not able to understand what this error means - graphql

enter image description hereI am trying to create graphql schema directive and trying to add it in makeExecutableSchema and the following error is occurring. Is there anyone who can help me understand this error or solve it.
const templateDirective = require('../index');
// Define your schema and resolvers if needed
const typeDefs = `
type Query {
me(): Me #templateDirective
}
`;
const resolvers = {
Query: {
me: () => false,
},
};
module.exports = makeExecutableSchema({
typeDefs,
resolvers,
schemaDirectives: {
templateDirective,
},
});

You have a syntax error in your document. If a field takes no arguments, you have to omit the parentheses, you cannot just have an empty set of parentheses after the field name. The corrected document:
type Query {
me: Me #templateDirective
}

Related

How to apply validation in graphQL schema using graphql-constraint-directive

import { ApolloServer, makeExecutableSchema } from 'apollo-server-express';
const { constraintDirective, constraintDirectiveTypeDefs } = require('graphql-constraint-directive');
schema: mergeSchemas({
schemas: [
makeExecutableSchema({
resolvers: resolver,
typeDefs: [constraintDirectiveTypeDefs, typeDefs],
schemaTransforms: [constraintDirective()]
}),
],
})
I am referring this pacakge:
https://www.npmjs.com/package/graphql-constraint-directive.
I am getting this error in loading types on my console after implementing it:
Error: Directive "constraint" may not be used on ARGUMENT_DEFINITION.
How to apply validation at schema level?
Your problem is that you are trying to use makeExecutableSchema from apollo-server-express.
As stated in the docs, makeExecutableSchema from graphql-tools should be used.
Solution:
const { ApolloServer } = require('apollo-server-express')
const { makeExecutableSchema } = require('graphql-tools')

Passing a variable to GraphQL mutation using ApolloClient doesn't seem to work

I'm trying to figure out how to run mutations using Apollo Client.
Here's the mutation I'm trying to run:
export const CREATE_POST = gql`
mutation CreatePost($title: String) {
createPost(
title: $title
body: "Test body, whatever..."
) {
title
body
slug
}
}
`
Here's the functional component that renders a form, and tries to run this mutation once I submit the form:
export default function post() {
const [createPost] = useMutation(CREATE_POST)
async function handleSubmit(event) {
event.preventDefault()
const { data } = await createPost({
variables: { title: "test title" }
})
}
return (<rendering the form here>)
}
I'm getting an error:
[GraphQL error]: Message: Variable "$title" of type "String" used in position expecting type "String!".
If I remove the $title variable from here: mutation CreatePost($title: String) {, the error disappears. It seems like I'm failing to pass it the variable. But as far as I can tell, this part of the code is correct:
const { data } = await createPost({
variables: { title: "test title" }
})
That's how you're supposed to pass variables to mutations, right? What am I doing wrong? How can I debug this?
The full code for the component is here
Query code is here
Solved it thanks to #xadm.
Had to use mutation CreatePost($title: String!) instead of mutation CreatePost($title: String).

Error when building typedefs TypeError: Cannot read property 'some' of undefined

I am getting the following error when building Typedefs in Apollo Server:
return typeDef.definitions.some(definition => definition.kind === language_1.Kind.DIRECTIVE_DEFINITION &&
^
TypeError: Cannot read property 'some' of undefined
I tried to follow some solutions from here https://github.com/apollographql/apollo-server/issues/2961 but still, I am getting the error.
This is how I am creating the schema:
fs.readdirSync(__dirname)
.filter(dir => { console.log('dir', dir); return dir.indexOf('.') < 0 })
.forEach((dir) => {
const tmp = require(path.join(__dirname, dir)).default;
resolvers = merge(resolvers, tmp.resolvers);
typeDefs.push(tmp.types);
});
const schema = new ApolloServer({
typeDefs,
resolvers,
playground: {
endpoint: '/graphql',
settings: {
'editor.theme': 'light'
}
}
});
type.js
const Book = gql`
type Book {
title: String!
author: String!
}
`;
export const types = () => [Book];
export const typeResolvers = {
};
mutation.js
const Mutation = gql`
extend type Mutation {
addBook(book: BookInput): Book
}
`;
export const mutationTypes = () => [Mutation];
export const mutationResolvers = {
Mutation: {
addBook: async (_, args, ctx) => {
return []
}
}
};
index.js
export default {
types: () => [types, queryTypes, inputTypes, mutationTypes],
resolvers: Object.assign(queryResolvers, mutationResolvers, typeResolvers),
};
Any suggestions? What could I be missing?
I just had the same issue for the past 2 hours. I realized the file were i was instantiating my apollo server was being executed before the typedefs was created.
Simple way to test for this is to make a console.log(types, queryTypes, inputTypes, mutationTypes) right before the execution of const schema = new ApolloServer({ ....
One of them is undefined. Thanks.
After spending some time making changes, I finally got a working solution.
I had to make sure that typeDefs was an array of GraphQL Documents and not a type of [Function: types]. To do that, I removed unnecessary function syntax.
For example:
I replaced this export const types = () => [Book]; with this export const types = Book;
I replaced this types: () => [types, queryTypes, inputTypes, mutationTypes] with types: [types, queryTypes, inputTypes, mutationTypes]
... and pretty much every where I had () =>
Finally, before instantiating ApolloServer, instead of pushing tmp.types to the array of types, I used concat to use all defined graphql types in the I had defined the current file 'plus' the graphql types imported in every directory
typeDefs = typeDefs.concat(tmp.types);

How to define client side schema in `react-apollo` application?

I am using react-apollo in my react applicant and I can't figure out how to implement a client side schema.
I have below type definition:
export const alertTypeDefs = gql`
type Query {
alert: Alert
}
type Alert {
message: String!
type: String!
duration: Int!
}
`;
It defines a Query which returns an alert object.
Below is the code I want to use this query.
const cache = new InMemoryCache();
export const createClient = () => {
return new ApolloClient({
cache,
typeDefs: [alertTypeDefs]
});
};
First I initialised a ApolloClient instance with memory cache and alertTypeDefs defined above. Then below is the code to run the query:
const client = createClient();
const data = client.readQuery({query: gql`
{
alert #client
}
`});
console.log('data:', data);
But I got this error Missing selection set for object of type Alert returned for query field alert when run readQuery on the client instance. It seems that the Alert is not defined. But I already defined the Alert query in the typeDefs. It works fine if I change the query code to below which I have to specify what to be returned inside { message }. But it doesn't seem to use the schema. What I expect is that I don't need to specify the return fields if it returns all fields in the schema object. Do I mis-understand the schema?
const data = client.readQuery({query: gql`
{
alert #client {
message
}
}
`});
console.log('data:', data);
If I have to specify the return fields one by one, what the point to define the schema?
This is expected behavior with GraphQL. You always need to specify inside the query which fields you're expecting. So in order to receive all the data you add the fields to the query:
const data = client.readQuery({query: gql`
{
alert #client {
message
type
duration
}
}
`});
console.log('data:', data);
There is an open issue inside the GraphQL specs.
You can define a fragment with all the fields of the entity and then reuse it.
Like this
fragment AllAlertFields on Alert {
message
type
duration
}
And then in a query
query {
allAlerts {
...AllAlertFields
}
}
More details: https://www.apollographql.com/docs/react/data/fragments/

Apollo server 2.0. Type "Upload" not found in document

How to replicate:
server.js
const { ApolloServer, makeExecutableSchema, gql } = require('apollo-server');
const typeDefs = gql`
type Mutation {
uploadAvatar(upload: Upload!): String!
}
`;
const resolvers = {
Mutation: {
uploadAvatar(root, args, context, info) {
return 'test';
}
}
};
const schema = makeExecutableSchema({ typeDefs, resolvers });
const server = new ApolloServer({
schema,
});
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
package.json
"dependencies": {
"apollo-server": "^2.0.0-rc.6",
"graphql": "^0.13.2"
}
On node server.js we get the following error:
Type "Upload" not found in document.
Given the latest version of apollo server, am I supposed to add anything else to the query? According to this tutorial and few other sources that I currently cannot recall, one does not need to do anything more than just write Upload and it should work fine. Am I missing anything?
There are a couple of ways I've fixed this, in the example on the apollo docs:
https://www.apollographql.com/docs/guides/file-uploads.html
you can see he doesn't use makeExecutableSchema but passed the resolvers and schema to the apollo server this stopped the error:
Type "Upload" not found in document.
If you want to use makeExecutableSchema then import the scalar
const typeDefs = gql`
scalar Upload
type Mutation {
uploadAvatar(upload: Upload!): String!
}
type Query {
ping: String
}
`;
https://github.com/jaydenseric/apollo-upload-examples/blob/master/api/schema.mjs
if you look at some of the example source code for the at blog post you can see he uses a scalar
The reason it wasn't being added automatically is
Scalar Upload
The Upload type automatically added to the schema by Apollo Server resolves an object containing the following:
stream
filename
mimetype
encoding
UPDATE: Apollo have made it clearer that when you use makeExecutableSchema you need to define the scalar for it to work
In a situation where a schema is set manually using makeExecutableSchema and passed to the ApolloServer constructor using the schema params, add the Upload scalar to the type definitions and Upload to the resolver
https://www.apollographql.com/docs/guides/file-uploads.html#File-upload-with-schema-param

Resources