GraphQL resolvers often request the same entity many times while resolving one query. A DataLoader avoids the N+1 problem by collecting unique keys into a batch and caching keys that have already been dispatched.
Design a GraphQLDataLoader class:
GraphQLDataLoader() creates an empty loader.boolean load(int key) schedules a key and returns whether it was newly scheduled.int[] dispatch() returns the current batch in first-load order.boolean clear(int key) removes one key from the cache.
load returns true only when key is neither pending nor cached. A duplicate pending key or a cached key returns false and is not added again.
dispatch returns all pending keys in their first-load order, marks them cached, and clears the pending batch. Dispatching an empty batch returns an empty array.
clear removes a cached key and returns true. It returns false when the key is not cached. Clearing a pending key does not unschedule it.
Example 1:
Input:
Output:
Explanation: Key 7 is scheduled only once. Dispatch preserves the order in which 7 and 3 were first requested and caches both, so another load of 7 schedules nothing.
Example 2:
Input:
Output:
Explanation: Dispatch caches 4. Clearing that entry makes a later load schedule 4 again.
Constraints
0 <= key <= 10^9- At most
10^5 total method calls are made. dispatch must preserve first-load order within each batch.- Cache entries do not expire unless
clear removes them. - A returned batch must not be changed by later loader operations.