GraphQL使用总结

陈开宇
2023-12-01

目录

Grahql 要点

定义数据类型

type XXX

  • example:
type Book {
    id: ID
    title: String
    author: Author // 自定义类型
    summary:String
    isbn: Int
    test: Boolean
    
}

定义查询 api

type Query

  • example:
type Query {
    // api名称(入参):返回类型
    findBook(id: String): Book  
    findAuthor(id: String): Author
}

定义修改/添加 api

type Mutation

  • example:
type Mutation {
    // API 名称(入参):返回值
    createAuthor(input: AuthorInput!): Author!
}

定义入参

input XXX

  • example:
input BookInput {
    title: String
    author: AuthorInput
}

input AuthorInput{
    first_name: String
    family_name: String
}

api 具体实现

  • 方法名(入参)返回值与 type Query 中定义的保持一致
// api 对应的具体实现方法的对象
var root = {
    hello: () => 'Hello world!',
    hello2: () => 'hello 2'
};

express-graphql 开启

app.use('/graphql', graphqlHTTP({
    schema: schema,   // 构建好的schema
    rootValue: root,  // api对应的具体实现方法的对象
    graphiql: true,  // graphql的开发调试页面
}));

样例

// 引入一些依赖
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

// 构建 schema
var schema = buildSchema(`
  type Query {
    hello: String
    hello2: String
  }
`);

// api 对应的具体实现方法的对象
// 方法名(入参)返回值与 type Query 中定义的保持一致
var root = {
    hello: () => 'Hello world!',
    hello2: () => 'hello 2'
};

var app = express();

// express-graphql 使用
app.use('/graphql', graphqlHTTP({
    schema: schema,   // 构建好的 schema
    rootValue: root,  // api 对应的具体实现方法的对象
    graphiql: true,  // graphql 的开发调试页面
}));

app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));
 类似资料: