GraphQL 渐进学习 03-GraphQL-scalar-自定义类型

本文介绍如何在GraphQL中实现自定义标量类型,通过创建Date类型来处理日期字段。包括如何定义类型、解析客户端传来的值、序列化返回客户端的值及类型检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GraphQL

GraphQL 渐进学习 03-GraphQL-scalar-自定义类型

目标

  • 编写自定义类型

代码

步骤

1. 引用 graphql graphql/language

const {GraphQLScalarType} = require('graphql')
const {Kind} = require('graphql/language')
  • 1
  • 2
  • GraphQLScalarType 用来声明 Scalar

  • Kind 类型检查

2. 编写 typeDefs

const typeDefs = `
  ###
  自定义日期类型
  ###
  scalar Date

  type Notice {
    content: String!
    ###
    消息时间
    ###
    noticeTime: Date!
  }
`
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • ###...### 是注释

  • scalar Date 定义了自定义类型

  • Notice.noticeTime 字段使用自定义 Date 类型

3. 编写 resolvers

const resolvers = {
  Date: new GraphQLScalarType({
    name: 'Date',
    description: 'Date custom scalar type',
    parseValue(value) {
      return new Date(value) // value from the client
    },
    serialize(value) {
      // return new Date(value).getTime()
      return new Date(value) // 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
    }
  })
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • resolvers 中需要详细声明

  • parseValue(value) {... 客户端输入

  • serialize(value) {... 打印给客户端

  • parseLiteral(value) {... 检查类型

4. 合并 Schema

const schema = makeExecutableSchema({
  typeDefs,
  resolvers
})
  • 1
  • 2
  • 3
  • 4

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值