[英]Resolving auto-generated typescript-mongodb types for GraphQL output
I'm using the typescript-mongodb
plugin to graphql-codegen
to generate Typescript types for pulling data from MongoDB and outputting it via GraphQL on Node.我正在使用
graphql-codegen
typescript-mongodb
插件到graphql-codegen
来生成 Typescript 类型,用于从 MongoDB 中提取数据并通过 Node.js 上的 GraphQL 输出。
My input GraphQL schema looks like this我的输入 GraphQL 架构如下所示
type User @entity{
id: ID @id,
firstName: String @column @map(path: "first_name"),
...
The generated output Typescript types look correct生成的输出 Typescript 类型看起来正确
export type User = {
__typename?: 'User',
id?: Maybe<Scalars['ID']>,
firstName?: Maybe<Scalars['String']>,
...
And the corresponding DB object以及对应的DB对象
export type UserDbObject = {
_id?: Maybe<String>,
first_name: Maybe<string>,
...
The problem is when actually sending back the mongo document as a UserDbObject
I do not get the fields mapped in the output.问题是当实际将 mongo 文档作为
UserDbObject
发回时,我没有得到输出中映射的字段。 I could write a custom resolver that re-maps the fields back to the User
type, but that would mean I'm mapping the fields in two different places.我可以编写一个自定义解析器,将字段重新映射回
User
类型,但这意味着我要在两个不同的位置映射字段。
ie I do not get mapped fields from a resolver like this即我没有从这样的解析器中获取映射字段
userById: async(_root: any, args: QueryUserByIdArgs, _context: any) : Promise<UserDbObject> => {
const result = await connectDb().then((db) => {
return db.collection<UserDbObject>('users').findOne({'_id': args.id}).then((doc) => {
return doc;
});
})
...
return result as UserDbObject;
}
};
Is there a way to use the typescript-mongodb
plugin to only have to map these fields in the schema, then use the auto-generated code to resolve them?有没有办法使用
typescript-mongodb
插件只需要在模式中映射这些字段,然后使用自动生成的代码来解析它们?
You can use mappers
feature of codegen to map between your GraphQL types and your models types.您可以使用 codegen 的
mappers
功能在 GraphQL 类型和模型类型之间进行映射。 See:看:
Since all codegen plugins are independent and not linked together, you should do it manually, something like:由于所有 codegen 插件都是独立的并且没有链接在一起,因此您应该手动执行,例如:
config:
mappers:
User: UserDbObject
This will make typescript-resolvers
plugin to use UserDbObject
at any time (as parent value, or as return value).这将使
UserDbObject
typescript-resolvers
插件随时使用UserDbObject
(作为父值或返回值)。
If you wish to automate this, you can either use the codegen programmatically ( https://graphql-code-generator.com/docs/getting-started/programmatic-usage ), or you can also create a .js
file instead of .yaml
file that will create the config section according to your needs.如果您希望自动执行此操作,您可以以编程方式使用 codegen ( https://graphql-code-generator.com/docs/getting-started/programmatic-usage ),或者您也可以创建一个
.js
文件而不是.yaml
文件,它将根据您的需要创建配置部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.