在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):calebmer/graphql-resolve-batch开源软件地址(OpenSource Url):https://github.com/calebmer/graphql-resolve-batch开源编程语言(OpenSource Language):JavaScript 100.0%开源软件介绍(OpenSource Introduction):GraphQL Batch ResolverA method for batching the resoluition of GraphQL fields as an alternative to import { GraphQLObjectType, GraphQLString } from 'graphql';
import { createBatchResolver } from 'graphql-resolve-batch';
const UserType = new GraphQLObjectType({
// ...
});
const QueryType = new GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: UserType,
resolve: createBatchResolver(async (sources, args, context) => {
const { db } = context;
const users = await db.loadUsersByIds(sources.map(({ id }) => id));
return users;
}),
},
},
}); For a complete examples with usage for both GraphQL.js and Installation
Why?GraphQL is a powerful data querying language for both frontend and backend developers. However, because of how GraphQL queries are executed, it can be difficult to define an efficient GraphQL schema. Take for example the following query: {
users(limit: 5) {
name
friends(limit: 5) {
name
}
}
} This demonstrates the power of GraphQL to select arbitrarily nested data. Yet it is a difficult pattern to optimize from the schema developer’s perspective. If we naïvely translate this GraphQL query into say, SQL, we get the following pseudo queries:
We have an N+1 problem! For every user we are executing a database query. This is noticably inefficient and does not scale. What happens when we have: {
users(limit: 5) {
name
friends(limit: 5) {
name
friends(limit: 5) {
name
friends(limit: 5) {
name
}
}
}
}
} This turns into 156 queries! The canonical solution to this problem is to use {
users(limit: 5) {
name
bestFriend {
name
}
}
} Is easy to optimize this GraphQL query with {
users(limit: 5) {
name
friends1: friends(limit: 5) {
name
}
friends2: friends(limit: 5, offset: 5) {
name
}
}
} All of a sudden the keys are not simple scalars. If we wanted to use This package offers an alternative to the {
users(limit: 5) {
name
friends(limit: 5) { # Batches 5 executions.
name
friends(limit: 5) { # Batches 25 executions.
name
friends(limit: 5) { # Batches 125 executions.
name
}
}
}
}
} Here we would only have 4 executions instead of 156. One for the root field, one for the first How?A batch resolver will run once per GraphQL field. So if we assume that you are using a batch resolver on your {
users(limit: 5) {
name
friends(limit: 5) {
name
friends(limit: 5) {
name
friends(limit: 5) {
name
}
}
}
}
} Every (source, args, context, info) => fieldValue To batch together calls to this function by field, The implementation is very similar to the To see how to optimize the above query with a batch resolver, be sure to check out the GraphQL.js example.
When do I use |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论