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
}
})
}
resolvers
中需要詳細聲明
parseValue(value) {...
客戶端輸入
serialize(value) {...
打印給客戶端
parseLiteral(value) {...
檢查類型
4. 合并 Schema
const schema = makeExecutableSchema({
typeDefs,
resolvers
})
參考