首页 > 解决方案 > graphQl - 全部返回 db

问题描述

我对graphQL真的很陌生

我在这里有一个简单的 graphQL 架构

const graphql = require('graphql');
const _ = require('lodash');

const {
  GraphQLObjectType,
  GraphQLString,
  GraphQLSchema,
  GraphQLID
} = graphql

const books = [
  { name: "book 1", genre: "book-1", id: "1" },
  { name: "book 2", genre: "book-2", id: "2" },
  { name: "book 3", genre: "book-3", id: "3" }
]

const BookType = new GraphQLObjectType({
  name: 'Book',
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    genre: { type: GraphQLString }
  })
})

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    book: {
      type: BookType,
      args: { id: { type: GraphQLID } },
      resolve(parent, args) {
        return _.find(books, { id: args.id })
      }
    }
  }
})

module.exports = new GraphQLSchema({
  query: RootQuery
})

我可以使用 id 退回一本书

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    book: {
      type: BookType,
      args: { id: { type: GraphQLID } },
      resolve(parent, args) {
        return _.find(books, { id: args.id })
      }
    }
  }
})  

我将如何归还所有书籍,我在想这样的事情:

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    book: {
      type: BookType,
      args: {},
      resolve(parent, args) {
        return _.find(books, {})
      }
    }
  }
})  

标签: graphql

解决方案


const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    book: {
      type: BookType,
      args: { displayall: { type: GraphQLID } },
      resolve(parent, args) {
        return _.find(books, { displayall: args.displayall })
      }
    }
    books:{
        type: new GraphQLList(BookType),
          resolve(parent, args) {
            return books
          }
        }
  }
})

推荐阅读