I am learning GraphQL with Node.js and I am currently using graphql-yoga
as a GraphQLServer. Now, I want to seperate Type Definitions and Resolvers so I have used schema.graphql
and in there I have all my types defined but now I have no Idea how to use that file as typeDefs in GraphQL Server. I have provided my files below.
index.js
const { createServer } = require('graphql-yoga');
const { resolvers } = require('./template1');
const server = createServer({
schema: {
resolvers,
typeDefs: 'src/schema.graphql'
}
});
server.start(() => {
console.log('GraphQL Server started.');
});
schema.graphql
type Query {
hello: String!
posts: [Post!]!
users: [User!]!
comments: [Comment!]!
}
type Mutation {
signUp(data: SignUpInput): User!
createPost(data: CreatePostInput): Post!
createComment(data: CreateCommentInput): Comment!
deleteUser(id: ID!): User!
deletePost(id: ID!): Post!
deleteComment(id: ID!): Comment!
}
input SignUpInput {
email:String!
username: String!
password: String!
}
input CreatePostInput {
title: String!
author: ID!
}
input CreateCommentInput {
text: String!
author: ID!
post: ID!
}
type Post {
id: ID!
title: String!
author: User!
comments: [Comment!]
}
type User {
id: ID!
email: String!
password: String!
username: String!
posts: [Post!]
comments: [Comment!]
}
type Comment {
id: ID!
text: String!
author: User!
post: Post!
}
For those facing ReferenceError: __dirname is not defined in ES module scope
, make sure to add const __dirname = path.resolve();
.
Full example:
import { createSchema, createYoga } from "graphql-yoga";
import fs from "fs";
import path from "path";
const __dirname = path.resolve();
const yoga = createYoga({
schema: createSchema({
typeDefs: fs.readFileSync(
path.join(__dirname, "./", "src", "schema.graphql"), // path will vary per each different project
"utf8"
),
}),
});
const server = createServer(yoga);
server.listen(4000, () => {
console.info("Server is running on http://localhost:4000/graphql");
});