javascript - 将 .graphql 中的类型导入 .js 文件
问题描述
我搜索了一些关于从.graphql
文件中导入类型的内容。我发现graphql-import可以使用# import something from 'something-else'
. 这在.graphql
文件之间工作正常。
但我想做的是将一些types
从generated.graphql
Prisma 导入到.js
文件中。
例如:
我有这个generated.graphql
来自 Prisma 的文件
"""generated.graphql file"""
type ItemWhereInput { ... }
type ItemConnection { ... }
...
我想导入这两种类型ItemWhereInput
并ItemConnection
从generated.graphql
文件导入items-types.js
文件
// items-types.js file
import gql from 'graphql-tag';
// I would like to make some kind of import ItemWhereInput and ItemConnection here
// Something like `import { ItemWhereInput, ItemConnection } from 'generated.graphql'`
...
const ItemWhereUniqueInput = gql`
input ItemWhereUniqueInput {
id: String!
}
`;
...
// And export ItemWhereInput and ItemConnection here
export default [Item, ItemInput, ItemWhereUniqueInput, ItemUpdateInput];
这样我就可以在其他地方调用makeExecutableSchema
并graphql-tools
使用这些类型
// items-query.js file
import { forwardTo } from 'prisma-binding';
const schema = `
items: [Item]!
item (where: ItemWhereUniqueInput!): Item
# And use it here
itemsConnection (where: ItemWhereInput): ItemConnection!
`;
const resolvers = {
items: forwardTo(‘db’),
item: forwardTo(‘db’),
itemsConnection: forwardTo(‘db’),
};
export default {
schema,
resolvers,
};
如果它在其他地方或者有什么可以帮助的,请指出我。
谢谢。
解决方案
您应该能够执行以下操作:
在构建步骤中,首先,将generated.graphql
文件转换为 js 文件
- 添加
export default `
到文件的开头, `);
到文件的末尾,并且- 将其重命名为
generated.js
.
这样,您可以将文件作为开发代码中的 js 文件导入:
// some other js file
/*
* notice the lack of .js, this should make it easier for your
* IDE to understand you're referencing the 'generated.graphql' file.
* If this is not possible in your code, you actually have to say
* .js here, not .graphql, because the file will be called .js after
* build.
*/
import generated from './generated';
console.log(generated);
您将看到这schema
是文件预构建步骤的内容字符串。
它现在可以用作 typeDefs 用于makeExecutableSchema
:
import { makeExecutableSchema } from 'graphql-tools';
import typeDefs from './generated';
import resolvers from './resolvers';
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
如果您使用捆绑器和/或转译器,则必须完成一些额外的工作,以确保文件也可以通过这些工具运行。我使用这种方法的项目只使用了 babel,这是一个问题:
- 使用 npm-watch 代替 babel 的 --watch 选项来运行构建脚本
- (可以并行进行)
- 在所有源 .js 文件上运行 babel
- 在所有 .graphql 文件上运行自定义脚本,其中:
- 将相关代码添加到文件中,使其成为有效的 js(内存中)
- 以编程方式在结果上运行 babel
- 使用 .js 扩展名将其保存到构建目标
不过要小心大文件,因为它们是用这种方法加载到内存中的!
但请注意,因为这种方法不适用于捆绑器,为此您必须在运行捆绑器之前转换文件(并且以某种方式仍然保留旧版本,可能通过以不同的方式命名转换后的版本并在运行捆绑器后将其删除),或查找/创建一个插件为您完成这项工作。以下是我找到的一些选项(快速谷歌搜索):对于webpack和Parcel。
推荐阅读
- parallel-processing - 并行写入独立值的总和
- jpa - JPA 未在 WildFly 16 上保存到数据库
- excel - 从锁定的工作簿中提取宏
- c# - 有没有办法根据统一 2d 中的玩家位置旋转对象
- r - Keras 二进制分类准确率停留在 50%
- telegram-bot - 是否可以使用纯 Javascript 编写 Telegram 机器人?
- android - 从 Fragment 向 Widget 发送 Intent
- r - 符号而不是ggplot上的p值数字
- .net-core - 如何从 appsettings.json 为 .net 核心控制台应用程序设置环境变量?
- python - 尝试转换列表或摆脱列表编号周围的引号