[GraphQL] Use GraphQL's Object Type for Basic Types

本文介绍如何使用GraphQL的Object Types创建基本的GraphQL Schema组件。通过将相关字段分组到特定类型下,如Video或User,可以更清晰地组织数据结构,并在查询Schema时获取这些类型。文中还展示了代码重构过程,使代码更具可读性和意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

We can create the most basic components of our GraphQL Schema using GraphQL's Object Types. These types allow us to group related fields together under a specific type, such as a Video or a User, and then allows us to fetch these types when we query our schema. In this video, we'll learn how to write GraphQL Object Types in GraphQL's Schema language, as well as how to create resolvers for them, and ultimately how to query them.

 

We are going to refactor this code to make it more readable and meanful:

const { graphql, buildSchema } = require('graphql');

const schema = buildSchema(`
    type Query {
        id: ID,
        title: String,
        duration: Int,
        watched: Boolean
    }
    
    type Schema{
        query: Query
    }
`);

const resolvers = {
    id       : () => '1',
    title    : () => 'bar',
    duration : () => 180,
    watched  : true
};

const query = `
    query myFirstQuery {
        id,
        title,
        duration,
        watched
    }
`;

graphql(schema, query, resolvers)
.then((result) => console.log(result))
.catch(console.error)

 

'id', 'title', 'duration', 'watched' are video related. So we create a Video type.

const { graphql, buildSchema } = require('graphql');

const schema = buildSchema(`
    type Video {
        id: ID,
        title: String,
        duration: Int,
        watched: Boolean
    }
    
    type Query {
        video: Video
    }
    
    type Schema{
        query: Query
    }
`);

const resolvers = {
    video : () => ({
        id       : '1',
        title    : 'bar',
        duration : 180,
        watched  : true
    })
};

const query = `
    query myFirstQuery {
        video {
            id,
            title,
            duration,
            watched
        }
    }
`;

graphql(schema, query, resolvers)
.then((result) => console.log(result))
.catch(console.error)

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值