Skip to content

Commit cc91273

Browse files
committed
Limit DataLoader cache to the Session within the current request.
This ensures cached data isn't shared between users when re-scoping the current user with `.asUser()`.
1 parent 6806312 commit cc91273

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/core/data-loader/data-loader.config.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
import { Injectable } from '@nestjs/common';
2-
import { type DataLoaderOptions } from '@seedcompany/data-loader';
2+
import {
3+
type DataLoaderOptions,
4+
lifetimeIdFromExecutionContext,
5+
} from '@seedcompany/data-loader';
36
import { NotFoundException } from '~/common';
7+
import { SessionHost } from '../../components/authentication';
48
import { ConfigService } from '../config/config.service';
59

610
@Injectable()
711
export class DataLoaderConfig {
8-
constructor(private readonly config: ConfigService) {}
12+
constructor(
13+
private readonly config: ConfigService,
14+
private readonly sessionHost: SessionHost,
15+
) {}
916

1017
create(): DataLoaderOptions<any, any> {
1118
return {
@@ -16,6 +23,15 @@ export class DataLoaderConfig {
1623
new NotFoundException(
1724
`Could not find ${String(typeName)} (${String(cacheKey)})`,
1825
),
26+
getLifetimeId: (context) => {
27+
// If we have a session, use that as the cache key.
28+
// It will always be created / scoped within the GQL operation.
29+
// This ensures the cached data isn't shared between users.
30+
const session = this.sessionHost.current$.value;
31+
if (session) return session;
32+
33+
return lifetimeIdFromExecutionContext(context);
34+
},
1935
cache: !this.config.isCli,
2036
};
2137
}

0 commit comments

Comments
 (0)