Skip to content

A dataloader implementation for NestJS.

Notifications You must be signed in to change notification settings

double-spent/nestjs-dataloader

Repository files navigation

⚡️ NestJS Dataloader

A simple dataloader implementation for NestJS including request-scoped caching.

package npm version package license package weekly downloads

About

DataLoader is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

This library simplifies the integration of DataLoader within NestJS applications by providing a friendly wrapper around the original implementation. It also introduces a request-scoped DataLoader, enabling efficient data fetching while ensuring the isolation of requests, especially useful in GraphQL scenarios and services that doesn't support request-scope like NestJS CQRS.

// before:

import DataLoader from 'dataloader';

const userLoader = new DataLoader(async (keys) => {
  // load users ..
});

// after:

import { DataLoader } from '@double-spent/nestjs-dataloader';

@Injectable()
class UserLoader extends DataLoader<User['id'], User> {
  async batchLoad(ids): User[] {
    // load users ..
  }
}

Installation

npm install @double-spent/nestjs-dataloader

Usage

Default DataLoader

The default DataLoader base class offers all the functionality the original implementation does by accepting the same options in the constructor. To use it in a NestJS module, extend the base class, decorate it with @Injectable(), and add it to the module providers and exports:

// 💾 UserLoader.ts

import { DataLoader } from '@double-spent/nestjs-dataloader';

@Injectable()
export class UserLoader extends DataLoader<User['id'], User> {
  async batchLoad(ids): User[] {
    // load users ..
  }
}

// 💾 UserController.ts

@Controller()
export class UserController() {
  constructor(userLoader: UserLoader) {}

  @Get()
  async user(@Param('id') id: User['id']) {
    return this.userLoader.load(id);
  }
}

// 💾 UserModule.ts

@Module({
  providers: [UserLoader],
  controllers: [UserController],
})
export class UserModule {}

Request-scoped DataLoader

The default DataLoader uses a memoized cache by default that is shared across all requests. On the other hand, the request-scoped DataLoader leverages the AsyncLocalStorage class to initialize a cache that expires at the end of the request. This makes it safe to use in NestJS services that only supports global scope but must handle request-scoped (or user-scoped) data, like CQRS.

In order for this loader to work, you must import the RequestScopedDataLoaderModule into your application which initializes the cache storage. An error is thrown otherwise as there's no sense in using this DataLoader if no request-scoped storage is available.

// 💾 UserLoader.ts

import { RequestScopedDataLoader } from '@double-spent/nestjs-dataloader';

@Injectable()
export class UserLoader extends RequestScopedDataLoader<User['id'], User> {
  async batchLoad(ids): User[] {
    // load users ..
  }
}

// 💾 UserController.ts

@Controller()
export class UserController() {
  constructor(userLoader: UserLoader) {}

  @Get()
  async user(@Param('id') id: User['id']) {
    return this.userLoader.load(id);
  }
}

// 💾 UserModule.ts

@Module({
  providers: [UserLoader],
  controllers: [UserController],
  imports: [RequestScopedDataLoaderModule],
})
export class UserModule {}

Troubleshooting

I'm getting a runtime error when extending the RequestScopedDataLoader class.

Make sure you're importing the RequestScopedDataLoaderModule into your application.

License

MIT License © Andrea SonnY

About

A dataloader implementation for NestJS.

Resources

Stars

Watchers

Forks

Packages

No packages published