GraphQL 渐进学习 03-GraphQL-scalar-自

2018-05-13  本文已影响151人  会煮咖啡的猫咪

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

目标

代码

步骤

1. 引用 graphql graphql/language

const {GraphQLScalarType} = require('graphql')
const {Kind} = require('graphql/language')

2. 编写 typeDefs

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

  type Notice {
    content: String!
    ###
    消息时间
    ###
    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
    }
  })
}

4. 合并 Schema

const schema = makeExecutableSchema({
  typeDefs,
  resolvers
})

参考

上一篇下一篇

猜你喜欢

热点阅读