HomeToolsAbout

Caching

Caching

DataLoader provides a memoization cache for all loads which occur in a single request to your application.

  • After .load() is called once with a given key, the resulting value is cached.

The cache only serves the purpose of not repeatedly loading the same data in the context of a single request to your Application.

Dataloader maintains a simple in-memory memoization cache.

  • more accurately: .load() itself is a memoized function.
// creating loader function createLoaders(authToken) { return { users: new DataLoader(ids => genUsers(authToken, ids)), }; } const app = express(); app.get('/', function (req, res) { const authToken = authenticateUser(req); const loaders = createLoaders(authToken); res.send(renderPage(req, loaders)); }); app.listen(); // caching example userLoader.prime(1, { bestFriend: 3 }); async function getBestFriend(userID) { const user = await userLoader.load(userID); return await userLoader.load(user.bestFriendID); } // In one part of your application getBestFriend(1); // Elsewhere getBestFriend(2);

Lifecycle

Typically, DataLoader instances are created when a Request begins, and are not used once the Request ends.

clear() and clearAll() invalidate the cached value at key(s).

AboutContact