npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@applifting-io/nestjs-dataloader

v1.1.5

Published

A NestJS decorator for dataloader

Downloads

1,923

Readme

NestJS Dataloader

Node.js CI Coverage Status

NestJS dataloader simplifies adding graphql/dataloader to your NestJS project. DataLoader aims to solve the common N+1 loading problem.

This is a fork of krislefeber/nestjs-dataloader with the following changes:

  • Replace generateDataLoader method in interface with getBatchFunction, reducing the need to import anything from the dataloader package and simplifying the code
  • Added sortDataLoaderResultsByKey convenience method, since some batching methods you can use (like SELECT * IN (...)) do not guarantee the order of the returned results to match the order of provided keys, which is essential for dataloader to work properly
  • Updated all dependencies to latest versions

Installation

npm i @applifting-io/nestjs-dataloader

Usage

NestDataLoader Creation

We start by implementing the NestDataLoader interface. This tells DataLoader how to load our objects.

import { Injectable } from '@nestjs/common';
import { NestDataLoader, DataLoaderBatchFunction } from '@applifting-io/nestjs-dataloader';
...

@Injectable()
export class AccountLoader implements NestDataLoader<string, Account> {
  constructor(private readonly accountService: AccountService) { }

  getBatchFunction(): DataLoaderBatchFunction<string, Account> {
    return (keys: string[]) => {
      const results = await this.accountService.findByIds(keys);
      return sortDataLoaderResultsByKey(keys, results, "id");
    };
  }
}

The first generic of the interface is the type of ID the datastore uses. The second generic is the type of object that will be returned. In the above instance, we want DataLoader to return instances of the Account class.

Providing the NestDataLoader

For each NestDataLoader we create, we need to provide it to our module.

import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { DataLoaderInterceptor } from 'nestjs-dataloader'
...

@Module({
  providers: [
    AccountResolver,
    AccountLoader,
    {
      provide: APP_INTERCEPTOR,
      useClass: DataLoaderInterceptor,
    },
  ],

})
export class ResolversModule { }

Using the NestDataLoader

Now that we have a dataloader and our module is aware of it, we need to pass it as a parameter to an endpoint in our graphQL resolver.

import * as DataLoader from 'dataloader';
import { Loader } from 'nestjs-dataloader';
...

@Resolver(Account)
export class AccountResolver {

    @Query(() => [Account])
    public getAccounts(
        @Args({ name: 'ids', type: () => [String] }) ids: string[],
        @Loader(AccountLoader) accountLoader: DataLoader<Account['id'], Account>): Promise<Account[]> {
        return accountLoader.loadMany(ids);
    }
}

The important thing to note is that the parameter of the @Loader decorator is the entity/class of the NestDataLoader we want to be injected to the method. The DataLoader library will handle bulk retrieval and caching of our requests. Note that the caching is stored on a per-request basis.

Contributing

Pull requests are always welcome. For major changes, please open an issue first to discuss what you would like to change.