GraphQL 渐进学习 04-graphql-resolvers-interfaces-接口的使用

本文详细介绍GraphQL中接口(interface)的使用方法,包括定义、实现及解析类型等关键步骤,并通过示例展示了如何利用接口特性实现灵活的数据查询。

GraphQL

GraphQL 渐进学习 04-graphql-resolvers-interfaces-接口的使用

目标

  • 使用 interfaces 接口

代码

步骤

1. 准备测试静态数据

const notices = [{id: 1, content: '这是 notice', noticeTime: 1524710641}]
const reminds = [{id: 1, content: '这是 remind', endTime: 1524710641}]
  • 1
  • 2
  • notices 通知

  • reminds 提醒

2. 编写 typeDefs

const typeDefs = `
  scalar Date

  interface Message {
    content: String
  }

  type Notice implements Message {
    content: String
    noticeTime: Date
  }

  type Remind implements Message {
    content: String
    endTime: Date
  }

  type Query {
    searchInterface (text: String!): Message!
  }
`
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • Message 接口对象

  • Notice Remind 对象履行接口 Message

  • searchInterface 供客户端查询使用方法

3. 编写 resolvers

const resolvers = {
  Query: {
    searchInterface: (_, {text}) => {
      if (text === 'notice') {
        return notices[0]
      } else {
        return reminds[0]
      }
    }
  },

  Message: {
    __resolveType(obj, context, info){
      console.log(obj, context, info)
      if(obj.noticeTime){
        return 'Notice'
      }
      if(obj.endTime){
        return 'Remind'
      }
      return null
    }
  },

  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
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • searchInterface 搜索方法实现,直接返回一条通知或提醒

  • __resolveType 返回类型定义

  • if(obj.noticeTime){ 如果含有 noticeTime 字段判定是通知

4. 合并 Schema

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

测试

1. 请求 searchInterface 方法

# 请求 query
query do($text: String!) {
  searchInterface(text: $text) {
    content
    ... on Notice {
      noticeTime
    }
    ... on Remind {
      endTime
    }
  }
}

# 变量 variables
{
  "text": "notice"
}

# 输出
{
  "data": {
    "searchInterface": {
      "content": "这是 notice",
      "endTime": "1970-01-18T15:31:50.641Z"
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 我们修改下请求 Query
# 请求 query
query do($text: String!) {
  searchInterface(text: $text) {
    ... on Notice {
      content
      noticeTime
    }
    ... on Remind {
      content
      endTime
    }
  }
}

# 变量 variables
{
  "text": "notice"
}

# 输出
{
  "data": {
    "searchInterface": {
      "content": "这是 remind",
      "endTime": "1970-01-18T15:31:50.641Z"
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 可以发现返回效果是一致的,这个和 union 还是有区别的

详细请移步 05-graphql-resolvers-union-联合的使用

2. 打印 __resolveType(obj, context, info) 参数

# obj
{ id: 1, content: '这是 notice', noticeTime: 1524710641 } 

# context
{}

# info
{ fieldName: 'searchInterface',
  fieldNodes:
   [ { kind: 'Field',
       alias: undefined,
       name: [Object],
       arguments: [Array],
       directives: [],
       selectionSet: [Object],
       loc: [Object] } ],
  returnType: Message,
  parentType: Query,
  path: { prev: undefined, key: 'searchInterface' },
  schema:
   GraphQLSchema {
     __allowedLegacyNames: undefined,
     _queryType: Query,
     _mutationType: Mutation,
     _subscriptionType: null,
     _directives: [ [Object], [Object], [Object] ],
     astNode: undefined,
     _typeMap:
      { Query: Query,
        Post: Post,
        Int: Int,
        String: String,
        Author: Author,
        Country: Country,
        Message: Message,
        MessageResult: MessageResult,
        Notice: Notice,
        Date: Date,
        Remind: Remind,
        Mutation: Mutation,
        AuthorInput: AuthorInput,
        __Schema: __Schema,
        __Type: __Type,
        __TypeKind: __TypeKind,
        Boolean: Boolean,
        __Field: __Field,
        __InputValue: __InputValue,
        __EnumValue: __EnumValue,
        __Directive: __Directive,
        __DirectiveLocation: __DirectiveLocation },
     _implementations: { Message: [Array] },
     __validationErrors: [],
     _possibleTypeMap: { Message: [Object] } },
  fragments: {},
  rootValue: undefined,
  operation:
   { kind: 'OperationDefinition',
     operation: 'query',
     name: { kind: 'Name', value: 'do', loc: [Object] },
     variableDefinitions: [ [Object] ],
     directives: [],
     selectionSet: { kind: 'SelectionSet', selections: [Array], loc: [Object] },
     loc: { start: 0, end: 160 } },
  variableValues: { text: 'notice' } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

参考

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值