Import build schema from .graphql file

Viewed 2991

I want to create a GraphQL API with the following schema

app.use(
  "/graphql",
  graphQlHttp({
    schema: buildSchema(`
    type Event {
        _id: ID!
        title: String!
        description: String!
        price: Float!
    }

    input EventInput {
        title: String!
        description: String!
        price: Float!
    }

    type QueryResolver {
        getEvents: [Event!]!
    }

    type MutationResolver {
        createEvent(eventInput: EventInput): [Event!]!
    }

    schema {
        query: QueryResolver
        mutation: MutationResolver
    }
    `),
    rootValue: {}
  })
);

Currently I am using it as a string in in the my main file. I want to separate it out in a graphql file. One way can be that we can read the file but I think it will not be efficient.

Can you please tell me how can I do this?

4 Answers

You can add this node module: https://github.com/ardatan/graphql-import-node

Then move your schema to something like mySchema.graphql.

Then, in JS:

const mySchema = require('./mySchema.graphql');

or in TypeScript:

import * as mySchema from './mySchema.graphql';

Just import all of your schemas using the gql module. Install it by:

npm i graphql-tag

I don't have the reputation to comment so I'll put this here.

If anyone following @Tim O'Connell's answer is wondering how to pass the imported Schema to BuildSchema(), since it's not a string anymore but a DocumentNode, you actually need to use the function BuildASTSchema().

Note that BuildSchema() is just a wrapper around BuildASTSchema() that parses the given string into a DocumentNode. (source)

So to recap, do something like this :

import 'graphql-import-node';
import { buildASTSchema } from 'graphql';
import * as mySchema from './schema.graphql';

export = buildASTSchema(mySchema);

You can use the graphql-tool.

const { loadSchemaSync } = require("@graphql-tools/load");
const { GraphQLFileLoader } = require("@graphql-tools/graphql-file-loader");
const { addResolversToSchema } = require("@graphql-tools/schema");
const { join } = require("path");

const schemaWithResolvers = addResolversToSchema({
  schema: loadSchemaSync(join(__dirname, "./(your graphql file).graphql"), {
    loaders: [new GraphQLFileLoader()],
  }),
  resolvers: {},
});

And, your graphql file is

type Event {
    _id: ID!
    title: String!
    description: String!
    price: Float!
}

input EventInput {
    title: String!
    description: String!
    price: Float!
}

type QueryResolver {
    getEvents: [Event!]!
}

type MutationResolver {
    createEvent(eventInput: EventInput): [Event!]!
}

schema {
    query: QueryResolver
    mutation: MutationResolver
}

Then, you just need to use schemaWithResolvers.builldSchema is unnecessary .

app.use(
  "/graphql",
  graphQlHttp({
    schema: schemaWithResolvers 
  })
);
Related