如何将“ typeorm”模型转换为graphql有效负载?

时间:2020-01-20 03:09:57

标签: typescript graphql nestjs typeorm typegraphql

我正在研究微服务应用程序。我有一个Node.js服务,它充当“数据服务”,并使用nestjstypeorm模型运行type-graphql。数据服务使用https://github.com/nestjs/graphql模块来启用graphql接口和游乐场。

我还有第二项服务,即客户也订阅的“网络套接字服务”。

“数据服务”使用axios库将HTTP请求发送到“ websocket服务”,然后通过websocket发送给客户端。从“数据服务”发送到“套接字服务”的消息包括typeorm模型。当通过axios typeorm发送时,模型将通过JSON.stringify传递。这里列出了问题。 stringify转换包含的字段不应该出现在最终输出中,并且还缺少graphql模式元数据。

我不想将模型进行分类,而是希望将它们转换为类似于graphql游乐场返回的graphql有效负载。据我所知,这个graphql转换已被深深抽象,并发生在nest/graphql模块中抽象apollo/server模块的某个位置。

这是一个复杂的系统,很难从中提取孤立的代码示例。如果需要澄清,请发表评论。以下是“数据服务”中的一些示例,我们有一个Profile实体,该实体具有profile.entity.ts profile.service.tsprofile.resolver.ts

Profile实体看起来像

import { Field, Int, ObjectType } from 'type-graphql'
import { Column, Entity, ManyToOne, OneToMany } from 'typeorm'
import { BaseEntity } from '../common/base/base.entity'


@ObjectType()
@Entity()
export class Profile extends BaseEntity {
  @Field()
  @Column({ unique: true })
  public username: string

  @Field()
  @Column()
  public name: string

  @Field({ nullable: true })
  @Column({ nullable: true })
  public birthday?: Date

  // Relations

  @Column()
  public accountId: string

  @ManyToOne(type => Account, account => account.profiles, { eager: true })
  public account: Account

  }

检索Profile引用并将其发送到套接字服务,例如

    const profileReference = await this.profileService.fetchById(profileId)
    await this.socketService.sendHomeEvent(profileReference)

在这里,我们要获取profileReference并将其序列化为graphql响应有效负载。 JSON.stringify上的profileReference结果包括不应该包括的字段,特别是Account字段。

1 个答案:

答案 0 :(得分:0)

鉴于GraphQL模式,您可以在服务器端执行任意查询。 type-graphql公开了buildSchema,用于根据解析器类构建架构,如here所示。

import { buildSchema } from 'type-graphql'
import { graphql } from 'graphql'

const schema = await buildSchema({
  resolvers: [ProfileResolver],
})
const query = `
  # your query here
`
const root = {}
const context = {...}
const variables = {...}
const { data, errors } = await graphql(schema, query, root, context, variables)

不幸的是,我不认为 nest.js公开了它所构建的架构,所以您必须自己做。