[笔记] A Beginner’s Guide to GraphQL

Published 05-07-2019 00:00:00

知识点

  • schema
  • types
  • Queries
  • Mutations
  • Subscriptions

schema

Schema Definition Language (SDL)

type Query {
  hello: String
}

Types

比如 Posts, Users, Likes, Groups 类型有 fields,比如 User 类型有 username email age

type User {
  id: ID!
  name: String!
  email: String!
  age: Int
}

! 表示这个field是 non-nullable 表示不可以为空 User类型可以为空的只有age

  • queries
  • mutations
  • subscriptions

Queries

GraphQL如何知道从哪获取数据呢? resolvers.js 处理怎么获取数据的问题

import { users } from "./db";

const resolvers = {
  Query: {
    user: (parent, { id }, context, info) => {
      return users.find(user => user.id === id);
    },
    users: (parent, args, context, info) => {
      return users;
    }
  }
};

export default resolvers;

query

query {
  users {
    id
    name
    email
    age
  }
}

有参数 单个user


query {
  user(id: 1) {
    id
    name
    email
    age
  }
}

Mutations

用于修改数据

便写 mutations 类型

schema.graphql

type Mutation {
  createUser(id: ID!, name: String!, email: String!, age: Int): User!
  updateUser(id: ID!, name: String, email: String, age: Int): User!
  deleteUser(id: ID!): User!
}

schema 有点想路由

Mutation 定义

  Mutation: {
    createUser: (parent, { id, name, email, age }, context, info) => {
      const newUser = { id, name, email, age };

      users.push(newUser);

      return newUser;
    },
    updateUser: (parent, { id, name, email, age }, context, info) => {
      let newUser = users.find(user => user.id === id);

      newUser.name = name;
      newUser.email = email;
      newUser.age = age;

      return newUser;
    },
    deleteUser: (parent, { id }, context, info) => {
      const userIndex = users.findIndex(user => user.id === id);

      if (userIndex === -1) throw new Error("User not found.");

      const deletedUsers = users.splice(userIndex, 1);

      return deletedUsers[0];
    }
  }

操作

mutation {
  createUser(id: 3, name: "Robert", email: "robert@gmail.com", age: 21) {
    id
    name
    email
    age
  }
}
mutation {
  deleteUser(id: 3) {
    id
    name
  }
}

Subscriptions

As I said before, subscriptions are the way you’re going to maintain a real-time connection with a server

维护实时连接到服务器, 客户端获得实时的数据更新

subscription {
  users {
    id
    name
    email
    age
  }
}

more https://hackernoon.com/from-zero-to-graphql-subscriptions-416b9e0284f3