[GraphQL] Use Arguments in a GraphQL Query

本文介绍如何在GraphQL中通过ID参数查询特定视频数据。演示了如何定义字段接收参数,并在解析器中使用这些参数来获取指定ID的视频信息。

In GraphQL, every field and nested object is able to take in arguments of varying types in order to do common operations like fetching an object by it's ID, filtering, sorting, and more. In this video, we'll update a field to take in an id argument and then learn how to use that argument in our resolve method to fetch a video by its id.

 

const express   = require('express');
const graphqlHttp = require('express-graphql');
const { getVideoById } = require('./data/index');
const server = express();
const port   = process.env.PORT || 3000;

const {
    GraphQLSchema,
    GraphQLObjectType,
    GraphQLString,
    GraphQLInt,
    GraphQLBoolean,
    GraphQLID
      } = require('graphql');

const videoType = new GraphQLObjectType({
    name: 'video',
    description: 'A video on Egghead.io',
    fields: {
        id: {
            type: GraphQLID,
            description: 'The id of the video'
        },
        title: {
            type: GraphQLString,
            description: 'The title of the video'
        },
        duration: {
            type: GraphQLInt,
            description: 'The duration of the video'
        },
        watched: {
            type: GraphQLBoolean,
            description: 'Whether or no the viewer watched the video'
        }
    }
})

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

const schema = new GraphQLSchema({
    query: queryType
});

server.use('/graphql', graphqlHttp({
                                     schema,
                                     graphiql  : true, // use graphiql interface
                                 }));

server.listen(port, () => {
    console.log(`Listening on http`)
})

 

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);
});

exports.getVideoById = getVideoById;

 

In the web interface, enter the query:

{
  video (id: "b"){
    id
    title
    duration
    watched
  }
}

 

转载于:https://www.cnblogs.com/Answer1215/p/6239012.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值