【问题标题】:How to create custom graphql scalars on Nestjs? Graphql Scalars如何在 Nestjs 上创建自定义 graphql 标量? Graphql 标量
【发布时间】:2022-08-05 00:16:01
【问题描述】:

我正在使用 GraphQL 在 Apollo Server 上使用 Nestjs 实现一个框架,我想使用一些自定义 GraphQL 标量。我发现了这个站点,https://www.graphql-scalars.dev/docs/quick-start,它有助于导入自定义标量,而无需像 https://docs.nestjs.com/graphql/scalars#create-a-custom-scalar 上所写的那样实际实现它们。具体来说,我想使用BigIntTimeURL

the quick start page 上的文档来看,我不确定代码属于哪里。我应该在app.module.ts 编码吗?


// or import specific typeDefs only with ES6 Import
import { ScalarNameTypeDefinition } from \'graphql-scalars\';
// or import specific typeDefs only with CommonJS
const { ScalarNameTypeDefinition } = require(\'graphql-scalars\');
// or import all typeDefs once with ES6 Import
import { typeDefs as scalarTypeDefs } from \'graphql-scalars\';
// or import all typeDefs once with CommonJS
const { typeDefs: scalarTypeDefs } = require(\'graphql-scalars\');

const typeDefs = [
  ...scalarTypeDefs,
  // other typeDefs
];
// or
const typeDefs = [
  ScalarNameTypeDefinition,
  // other typeDefs
];

我目前的 GraphQLModule:

GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  typePaths: [\'./**/**/**/*.graphql\'],
  definitions: {
    path: join(process.cwd(), \'src/graphql.ts\'),
    outputAs: \'class\',
  },  
}),

the resolver map 怎么样?代码应该在哪里? assets.resolver.ts?我也不明白this code属于哪里?

简而言之,如何在 Apollo Server 上的 Nestjs 框架中使用graphql-scalars 包?是否有任何开源 GitHub 存储库可供研究?

    标签: graphql nestjs apollo-server scalar


    【解决方案1】:

    看看这里NestJs Import a custom scalar

    这就是我的 app.module.ts 的样子:

    import { BigIntResolver, DateResolver, DateTimeResolver } from 'graphql-scalars';
    
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      typePaths: ['./**/*.graphql'],
      definitions: {
        path: join(process.cwd(), 'src/graphql/graphql-types.ts'),
        customScalarTypeMapping: {
          BigInt: 'bigint',
          DateTime: 'Date',
        },
      },
      resolvers: {
        BigInt: BigIntResolver,
        Date: DateResolver,
        DateTime: DateTimeResolver,
      },
      playground: true,
      debug: true,
    }),
    

    在我的 .graphql 文件中,我可以使用这些类型:

    scalar BigInt
    scalar Date
    scalar DateTime
    
    input WorkperiodContent {
      editedAt: DateTime
      startDate: Date
      endDate: Date
    }
    

    完成此操作后,我可以使用这些新标量在 GraphQL Playground 上成功运行查询。

    您甚至不需要创建自己的自定义标量。你可以只导入你需要的三个,你就可以开始了。

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2020-08-03
      • 2018-05-29
      • 2019-06-13
      • 2020-10-21
      • 2018-02-12
      • 2021-05-14
      • 2018-12-04
      • 2020-08-03
      相关资源
      最近更新 更多