我正在研究微服务应用程序。我有一个Node.js服务,它充当“数据服务”,并使用nestjs
和typeorm
模型运行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.ts
和profile.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
字段。
答案 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公开了它所构建的架构,所以您必须自己做。