graphql/dataloaderを読んだときのメモ

Each DataLoader instance represents a unique cache. Typically instances are created per request when used within a web-server like express if different users can see different things.
ユーザーごとに見るものが違う場合はそれぞれDataLoaderのインスタンスが作成される。
NestJSならば Scope.REQUEST
を利用する。
参考:https://qiita.com/kyusyukeigo/items/b0c97c8e9ca6d84bf4f9

To uphold the constraints of the batch function, it must return an Array of values the same length as the Array of keys, and re-order them to ensure each index aligns with the original keys [ 2, 9, 6, 1 ]:
[
{ id: 2, name: 'San Francisco' },
{ id: 9, name: 'Chicago' },
null, // or perhaps `new Error()`
{ id: 1, name: 'New York' },
];
key: 6
に紐づくデータが無い時は一貫性を保つために無いことを示すデータを返さなければならない (mustなので)

Clearing Cache
In certain uncommon cases, clearing the request cache may be necessary.
The most common example when clearing the loader's cache is necessary is after a mutation or update within the same request, when a cached value could be out of date and future loads should not use any possibly cached value.
Here's a simple example using SQL UPDATE to illustrate.
// Request begins...
const userLoader = new DataLoader(...)
// And a value happens to be loaded (and cached).
const user = await userLoader.load(4)
// A mutation occurs, invalidating what might be in cache.
await sqlRun('UPDATE users WHERE id=4 SET username="zuck"')
userLoader.clear(4)
// Later the value load is loaded again so the mutated data appears.
const user = await userLoader.load(4)
// Request completes.
データ更新などをしたらcacheをclearしなければならないケースがある

LoaderをinitするときにTokenなどをkeyとして渡すと危険なcacheの仕組みを防ぐことが出来る

この記事を参考にもしている。とても参考になる。