Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a node, express server using expressGraphql. I am trying to declare a type definition for graphql in a .graphql or .gql file, because as the type gets larger, it becomes difficult to read the string.

Here is what I have:

import testQuery from './test.graphql';

import routes from "./routes";

import { buildSchema } from "graphql";

const schema = buildSchema(testQuery);

// Root resolver
const root = {
    message: () => "Hello World!",
};

app.use(
    "/api/graphql",
    expressGraphQL({
        schema,
        graphiql: true,
    })
);

My graphql file. //test.graphql

type Book {
    message: String
}

I get an error because Typescript

Cannot find module './test.graphql'.

I have seen people doing this:

const { makeExecutableSchema } = require('graphql-tools');

const schemaFile = path.join(__dirname, 'schema.graphql');
const typeDefs = fs.readFileSync(schemaFile, 'utf8');

const schema = makeExecutableSchema({ typeDefs });

Is this the way of doing it?

So what do I need to to config typescript to be able to import, and build the schema

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

AFAIK, there are two ways to import schema files, either 1) by reading the file directly as you describe above, or 2) by wrapping the queries in exported variables.

// bookSchema.ts <- note the file extension is .ts instead of .graphql
export default `
  type Book {
    message: String
  }
`

// anotherSchema.ts <- note the file extension is .ts instead of .graphql
export default `
  type User {
    name: String
  }
`

// main.ts
import bookSchema from 'bookSchema';
import anotherSchema from 'anotherSchema';

const schema = makeExecutableSchema({ typeDefs: [
  bookSchema,
  anotherSchema,
] });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...