将 .gql 文件解析为 TypeScript 中的 DocumentNode

Parsing .gql files as DocumentNode in TypeScript

我在 type-defs.gql 中有以下 typeDefs:

type A {
  name: String
}

type Query {
  a: A
}

如果我以这种方式设置我的 apollo 服务器,那么我会得到 SyntaxError: Unexpected identifier for the gql file:

import { ApolloServer} from "apollo-server";
import typeDefs from "./type-defs.gql";

const resolvers = {};

const config = {
  resolvers: resolvers,
  typeDefs: typeDefs,
};
const server = new ApolloServer(config);
server.listen().then(({ url }) => console.log(`Server running at: ${url}`));

但是如果我按照以下方式设置服务器,一切都会正常工作:

import { ApolloServer, gql} from "apollo-server";

const resolvers = {};
const typeDefs = gql`
  type A {
    name: String
  }

  type Query {
    a: A
  }
`;

const config = {
  resolvers: resolvers,
  typeDefs: typeDefs,
};
const server = new ApolloServer(config);
server.listen().then(({ url }) => console.log(`Server running at: ${url}`));

我的 gql.d.ts 包含以下内容:

declare module "*.gql" {
  import { DocumentNode } from "graphql";

  const value: DocumentNode;
  export default value;
}

我更愿意使用 gql 文件而不是直接在我的 server.ts 文件中编写 typeDef。 谁能帮我解决这个问题?

我设法通过使用来自@graphql-tools 的 loadSchemaSync 制定了一个可行的解决方案。

import { ApolloServer } from "apollo-server";
import { loadSchemaSync } from "@graphql-tools/load";
import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader";
import { addResolversToSchema } from "@graphql-tools/schema";

const resolvers = {};
const schema = loadSchemaSync("./src/**/*.gql", {
  loaders: [new GraphQLFileLoader()],
});

const config = {
  schema: addResolversToSchema({schema, resolvers}),
};
const server = new ApolloServer(config);
server.listen().then(({ url }) => console.log(`Server running at: ${url}`));