我有一个节点,使用expressGraphql的Express服务器。我试图在.graphql.gql文件中声明graphql的类型定义,因为随着类型的增加,读取string变得很困难。

这是我所拥有的:

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,
    })
);

我的graphql文件。//test.graphql
type Book {
    message: String
}

我收到一个错误,因为 typescript



我见过有人这样做:
const { makeExecutableSchema } = require('graphql-tools');

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

const schema = makeExecutableSchema({ typeDefs });

这是这样做的方式吗?

所以我需要配置 typescript 才能导入和构建模式

最佳答案

AFAIK有两种导入模式文件的方法,一种是通过如上所述直接读取文件,另一种是2)通过将查询包装在导出的变量中。

// 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,
] });

10-05 20:51
查看更多