How do I use schema.graphql file as typeDefs?

Viewed 121

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!
}

and I am getting this Error. Error Image

2 Answers

Instead of directly passing the schema use:

typeDefs: fs.readFileSync(
    path.join(__dirname, 'schema.graphql'),
    'utf8'
)

Thanks this worked for me!

Just added this at the top of the file.

import { readFileSync } from 'node:fs';
import { join } from 'node:path';
Related