From ac66ef514c7ffe633870cdceb0716e115e42f4af Mon Sep 17 00:00:00 2001 From: Yuki Ito Date: Tue, 30 Apr 2024 18:46:06 +0900 Subject: [PATCH] Add description to isolate instance per request --- README.md | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/README.md b/README.md index 8a4da9c..1c2d56f 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,53 @@ const options = { const dynamodbDataLoader = new DynamodbDataLoader(tableSchemas, options); // All arguments are optional. ``` +### Propagate with Express Context + +Following best practices of DataLoader, a new instance of DynamodbDataLoader should be created per client request. + +This example inserts the dataLoader to the Request object in express middleware. + +```typescript +const app = express(); + +// Middleware to initialize DataLoader and store it in AsyncLocalStorage +app.use((req) => { + req.dataLoader = new DynamodbDataLoader(); +}); + +app.get('/user/:id', async (req, res) => { + const item = await req.dataLoader.getter.load({ + TableName: "Users", + Key: { userId: req.params.id }, + }); + res.send(item); +}); +``` + +### Store to AsyncLocalStorage + +The another way to isolate DataLoader per client request is using [AsyncLocalStorage](https://nodejs.org/api/async_context.html). + +```typescript +const app = express(); + +const dynamodbDataLoaderStorage = new AsyncLocalStorage(); + +app.use((req, res, next) => { + dynamodbDataLoaderStorage.run(new DynamodbDataLoader(), next); +}); + +app.get('/user/:id', async (req, res) => { + const item = await dynamodbDataLoaderStorage.getStore()!.getter.load({ + TableName: "Users", + Key: { userId: req.params.id }, + }); + res.send(item); +}); +``` + +### Usage + ## Fetching Data ### Get Operation