我不知道如何将app object传递给我的TypeGrapQL解析器。
我创建了我的类型和解析器,并使用express-graphql设置了graphql服务器。我能够运行该图,但没有幸运地传递app对象来使用注册的服务。
我的graphql.service.ts看起来像这样:
import { ServiceAddons } from '@feathersjs/feathers'
import { graphqlHTTP } from 'express-graphql'
import 'reflect-metadata'
import { buildSchemaSync } from 'type-graphql'
import { Container } from 'typedi'
import { Application } from '../../declarations'
import { Graphql } from './graphql.class'
import { ArticleResolver } from './resolvers/article.resolver'
// Add this service to the service type index
declare module '../../declarations' {
interface ServiceTypes {
graphql: Graphql & ServiceAddons<any>
}
}
export default async function (app: Application): Promise<void> {
const schema = buildSchemaSync({
resolvers: [__dirname + '/resolvers/*.resolver.ts'],
container: Container,
})
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
graphiql: true,
})
)
}这是我的一个解析器类article.resolver.ts
import { Arg, Query, Resolver } from 'type-graphql'
import { Service } from 'typedi'
import { Application } from '../../../declarations'
import { Category } from '../types/category.type'
@Service()
@Resolver(Category)
export class CategoryResolver {
constructor(private readonly app: Application) {}
@Query((returns) => [Category])
async categories() {
try {
const result = await this.app.service('category').find()
return (result as any).data // TODO: Refactor to return result with pagination details
} catch (err) {
console.log('Categories resolver error', err)
return []
}
}
}由于this.app未定义,因此无法执行this.app.service()
我对依赖注入在TypeGrapQL中的工作原理有点困惑,任何帮助都是非常感谢的。
谢谢
发布于 2021-05-05 16:43:21
我设法让它工作,这是我的解决方案,如果有人有同样的问题:
我创建了一个用来自typedi的@Service装饰的Graphql类,它接受这样的应用程序对象
import { Service } from 'typedi'
import { Application } from '../../declarations'
@Service()
export class Graphql {
app: Application
//eslint-disable-next-line @typescript-eslint/no-unused-vars
constructor(app: Application) {
this.app = app
}
}在我的graphql.service.ts中,我初始化了类,并将实例向下传递给typedi容器
import { buildSchemaSync } from 'type-graphql'
import { Container } from 'typedi'
import { Application } from '../../declarations'
import { Graphql } from './graphql.class'
export default async function (app: Application): Promise<void> {
const graphql = new Graphql(app)
Container.set('graphql', graphql)
const schema = buildSchemaSync({
resolvers: [__dirname + '/resolvers/category.resolver.ts'],
container: Container, // Pass the container to the resolvers
})
// Initialize our express graphql server
}最后,在我的解析器中,我用@Service装饰解析器,并将graphql实例注入到构造函数中:
import { Application } from '../../../declarations'
import { Graphql } from '../graphql.class'
import { Inject, Service } from 'typedi'
@Service()
@Resolver(Category)
export class CategoryResolver {
app: Application
constructor(@Inject('graphql') private readonly graphql: Graphql) {
this.app = this.graphql.app
}
// Queries and Mutations
}这解决了我的问题,希望对你有任何帮助,?
https://stackoverflow.com/questions/67380621
复制相似问题