非常教程

Nest参考手册

GRAPHQL

标量

为了定义自定义标量,我们还必须创建一个类型定义和一个专用的解析器。在这里(如在官方文档中),我们将把graphql-type-json包用于演示目的。这个npm包定义了JSONGraphQL标量类型。首先,让我们安装包:

$ npm i --save graphql-type-json

安装包后,我们必须将自定义解析器传递给forRoot()方法:

import * as GraphQLJSON from 'graphql-type-json';

@Module({
  imports: [
    GraphQLModule.forRoot({
      typePaths: ['./**/*.graphql'],
      resolvers: { JSON: GraphQLJSON },
    }),
  ],
})
export class ApplicationModule {}

现在我们可以JSON在类型定义中使用标量:

scalar JSON

type Foo {
  field: JSON
}

定义标量类型的另一种形式是创建一个简单的类。假设我们想用Date类型增强我们的模式。

import { Scalar } from '@nestjs/graphql';
import { Kind } from 'graphql';

@Scalar('Date')
export class DateScalar {
  description = 'Date custom scalar type';

  parseValue(value) {
    return new Date(value); // value from the client
  }

  serialize(value) {
    return value.getTime(); // value sent to the client
  }

  parseLiteral(ast) {
    if (ast.kind === Kind.INT) {
      return parseInt(ast.value, 10); // ast value is always in string format
    }
    return null;
  }
}

之后,我们需要注册DateScalar为提供者。

@Module({
  providers: [DateScalar],
})
export class CommonModule {}

现在我们可以Date在类型定义中使用标量。

Nest

Nest 是一个用于构建高效,可扩展的 Node.js 服务器端应用程序的框架

Nest目录

1.介绍
2.常见问题
3.CLI
4.方法
5.执行上下文
6.微服务
7.WEBSOCKETS
8.GRAPHQL
9.技术
10.基本内容
11.迁移指南