How do I use schema.graphql file as typeDefs?

How do I use schema.graphql file as typeDefs?


3

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.

How do I use schema.graphql file as typeDefs?

3 Answers
3


4

Instead of directly passing the schema use:

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


2

Thanks this worked for me!

Just added this at the top of the file.

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


0

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 https://localhost:4000/graphql");
});



Leave a Reply

Your email address will not be published. Required fields are marked *