在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):robrichard/graphql-fields开源软件地址(OpenSource Url):https://github.com/robrichard/graphql-fields开源编程语言(OpenSource Language):JavaScript 100.0%开源软件介绍(OpenSource Introduction):Deprecation NoticeThere are many use-cases that are not supported by this library, it is recommended to use something else like graphql-parse-resolve-info graphql-fieldsTurns GraphQLResolveInfo into a map of the requested fields. Flattens all fragments and duplicated fields into a neat object to easily see which fields were requested at any level. Takes into account any UsageSchema Type definition const graphqlFields = require('graphql-fields');
const graphql = require('graphql')
const UserType = new graphql.GraphQLObjectType({
name: 'User',
fields: {
profile: {type: new graphql.GraphQLObjectType({
name: 'Profile',
fields: {
firstName: {type: graphql.GraphQLString},
lastName: {type: graphql.GraphQLString},
middleName: {type: graphql.GraphQLString},
nickName: {type: graphql.GraphQLString},
maidenName: {type: graphql.GraphQLString}
}
}),
email: {type: graphql.GraphQLString},
id: {type: graphql.GraphQLID}
}
});
module.exports = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: () =>
Object.assign({
user: {
type: UserType,
resolve(root, args, context, info) {
console.log(
JSON.stringify(graphqlFields(info), null, 2)
);
...
}
}
})
})
}) Query {
user {
...A
profile {
...B
firstName
}
}
}
fragment A on User {
...C
id,
profile {
lastName
}
}
Fragment B on Profile {
firstName
nickName @skip(if: true)
}
Fragment C on User {
email,
profile {
middleName
maidenName @include(if: false)
}
} will log {
"profile": {
"firstName": {},
"lastName": {},
"middleName": {}
},
"email": {},
"id": {}
}
subfields argumentsTo enable subfields arguments parsing, you'll have to provide an option object to the function. This feature is disable by default. const graphqlFields = require('graphql-fields');
const fieldsWithSubFieldsArgs = graphqlFields(info, {}, { processArguments: true }); For each subfield w/ arguments, a [
{
arg1Name: {
kind: ARG1_KIND,
value: ARG1_VALUE,
},
},
{
arg2Name: {
kind: ARG2_KIND,
value: ARG2_VALUE,
}
}
] The kind property is here to help differentiate value cast to strings by javascript clients, such as enum values. Exclude specific fieldsMost of the time we don't need const graphqlFields = require('graphql-fields');
const fieldsWithoutTypeName = graphqlFields(info, {}, { excludedFields: ['__typename'] }); WhyAn underlying REST api may only return fields based on query params. {
user {
profile {
firstName
},
id
}
} should request /api/user?fields=profile,id while {
user {
email
}
} should request /api/user?fields=email Implement your resolve method like so:
Tests
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论