apollo server 基础--类型系统

标量:

  • Int 32位整型
  • Float 双精度浮点型
  • String utf-8型字符串
  • ID 可序列化为字符串的唯一的标识,一般被作为id
  • 对象类型,例如:
    type Book {
    title: String
    author: Author
    }
    
    type Author {
      name: String
      books: [Book]
    }
    
  • Query类型:query类型定义了确切的GrapyQL查询方式,写法和对象类型的相似,但是他的名字总是Query。Query类型的每个字段都定义了一个名字和返回类型,每个字段都是一个查询。例如:
# 服务端
type Query {
  getBooks: [Book] # 查询book列表
  getAuthors: [Author] # 查询用户列表
}
# 客户端
query {
  getBooks {
    title
    author {
      name
    }
  }
}
  • Mutation类型:和Query类型类似,只不过Query类型是为了获取数据,但Mutatiion类型是执行更改。Mutation类型的每个字段都是定义了一个签名和返回值类型,每个字段都是一个更改。例如:
# 服务端
type Mutation {
  addBook(title: String, author: String): Book
}

# 客户端
mutation {
  addBook(title: "Fox in Socks", author: "Dr. Seuss") {
    title
    author {
      name
    }
  }
}
  • 自定义标量。示例:
# 声明
scalar CustomScalar

定义:

const { ApolloServer, gql } = require('apollo-server');
const { GraphQLScalarType, Kind } = require('graphql');

const customScalarType = new GraphQLScalarType({
  name: 'CustomScalar',
  description: 'Description of my custom scalar type',
  serialize(value) {
    let result;
    // ... 一系列操作后返回
    return result;
  },
  parseValue(value) {
    let result;
    // 同上
    return result;
  },
  parseLiteral(ast) {
    switch (ast.kind) {
      case Kind.Int:
      // 返回一个字面值, 比如 1 或者 '静态字符串'
    }
  }
});

// 定义resolver
const resolvers = {
  customScalar: customScalarType
}

Input类型

在查询、更改操作中(Query和Mutation)可以传递一些参数,这些参数就是输入(Input)类型,必须使用input声明。例如:

type Mutation {
  createPost(post: PostAndMediaInput): Post
}

input PostAndMediaInput {
  title: String
  body: String
  mediaUrls: [String]
}

枚举类型

类似于其他语言的枚举类型。例子:

enum Colors {
  RED
  GREEN
  BLUE
}
type Query {
  favoriteColor: Colors # 使用枚举类型
  avatar(borderColor: Colors): String # 作为参数
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容