加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 09:40:39 所属栏目:安全 来源:网络整理
导读:GraphQL 渐进学习 03-GraphQL-scalar-自定义类型 目标 编写自定义类型 代码 graphQL-example/features.js 步骤 1. 引用 graphql graphql/language const {GraphQLScalarType} = require('graphql')const {Kind} = require('graphql/language') GraphQLScalar

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

目标

  • 编写自定义类型

代码

  • graphQL-example/features.js

步骤

1. 引用 graphql graphql/language

const {GraphQLScalarType} = require('graphql')
const {Kind} = require('graphql/language')
  • GraphQLScalarType 用来声明 Scalar
  • Kind 类型检查

2. 编写 typeDefs

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

  type Notice {
    content: String!
    ###
    消息时间
    ###
    noticeTime: Date!
  }
`
  • ###...### 是注释
  • 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
    }
  })
}
  • resolvers 中需要详细声明
  • parseValue(value) {... 客户端输入
  • serialize(value) {... 打印给客户端
  • parseLiteral(value) {... 检查类型

4. 合并 Schema

const schema = makeExecutableSchema({
  typeDefs,resolvers
})

参考

  • graphql-tools

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读