[GraphQL] Use GraphQLList with GraphQLObject Types

GraphQL列表类型实践
本文介绍如何使用GraphQLList从graphql包中结合GraphQLObject类型创建返回集合字段的模式。演示了如何通过GraphQLList获取列表对象,包括定义模式、解析器以及数据获取方法。

When working with collections of things in GraphQL, we'll always reach out for the GraphQLListType. In this video, we'll learn how to use GraphQLList from the graphql package in combination with a GraphQLObject Type to create a field that returns a collection in our Schema.

 

We can use GraphQLList to fetch list objects:

const queryType = new GraphQLObjectType({
    name: 'QueryType',
    description: 'The root query type',
    fields :{
        videos: {
            type: new GraphQLList(videoType),
            resolve: getVideos
        },
        video: {
            type: videoType,
            args: {
                id: {
                    type : new GraphQLNonNull(GraphQLID),
                    description: 'The id of the video'
                }
            },
            resolve: (_, args) => getVideoById(args.id)
        }
    }
});

 

Data:

const videoA = {
    id: 'a',
    title: 'Create a GraphQL Schema',
    duration: 120,
    watched: true,
};
const videoB = {
    id: 'b',
    title: 'Ember.js CLI',
    duration: 240,
    watched: false,
};
const videos = [videoA, videoB];
const getVideoById = (id) => new Promise((resolve) => {
    const [video] = videos.filter((video) => {
        return video.id === id;
    });

    resolve(video);
});

const getVideos = () => new Promise((resolve) => resolve(videos));

exports.getVideoById = getVideoById;
exports.getVideos = getVideos;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值