I'm working on graphql-yoga/node
at the moment.
I've got an index.js file like below:
import { createServer } from "@graphql-yoga/node";
import { readFileSync } from "node:fs";
import Comment from "./resolvers/Comment";
import Query from "./resolvers/Query";
import Post from "./resolvers/Post";
import User from "./resolvers/User";
import Mutation from "./resolvers/Mutation";
import db from "./db";
const typeDefs = readFileSync("./src/schema.graphql", "utf-8");
const server = createServer({
schema: {
typeDefs,
resolvers: { Query, Mutation, Post, User, Comment },
context: { db },
},
});
server.start();
I have a separate files for schema and resolvers.
Schema file is as follows:
type Query {
posts(query: String): [Post!]!
users(query: String): [User!]!
comments(query: String): [Comment!]!
}
type Post {
id: ID!
title: String!
body: String!
isPublished: Boolean!
author: User!
comments: [Comment!]!
}
Resolver is as follow:
const Post = {
author(parent, args, { db }, info) {
return db.users.find((user) => {
return user.id === parent.author;
});
},
comments(parent, args, { db }, info) {
return db.comments.filter((comment) => {
return comment.post === parent.id;
});
},
};
export { Post as default}
I have a separate Query file
const Query = {
posts(parent, args, { db }, info) {
if (!args.query) {
return db.posts;
}
return db.posts.filter((post) => {
const isTitleMatch = post.title.toLowerCase().includes(args.query.toLowerCase());
const isBodyMatch = post.body.toLowerCase().includes(args.query.toLowerCase());
return isTitleMatch || isBodyMatch;
});
}
}
export { Query as default };
db is the file where static data is saved.
const posts = [
{
id: "4",
title: "The alchemist",
body: "There is only one thing that makes a dream impossible to achieve: the fear of failure.",
isPublished: true,
author: "1",
},
{
id: "5",
title: "Dear stranger",
body: "the truth is you are at war with yourself thats why you find yourself at war with others.",
isPublished: false,
author: "3",
},
{
id: "6",
title: "Warren buffet",
body: "The most important thing to do if you find yourself in a hole is to stop digging.",
isPublished: true,
author: "3",
},
];
There are no errors in the console. Everything appears to be in good working order. However, when I try to run the post query as described below, I get an error rather than a response.
query {
posts {
id
title
body
}
}
the Error:
{
"errors": [
{
"message": "Unexpected error.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"posts"
]
}
],
"data": null
}
I'm not sure what I'm doing wrong. Can anyone help me here?
CodePudding user response:
It seems like you're getting an error on the server side. Could you share your terminal/logs output?
Also, the context
option should be at the root level, not under schema.
Could you try the following?
const server = createServer({
schema: {
typeDefs,
resolvers: { Query, Mutation, Post, User, Comment },
},
context: { db },
});