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

sequelize-find-unique

v1.2.0

Published

Query batching with dataloader for Sequelize models

Downloads

8

Readme

🦄 sequelize-find-unique

Test npm

Finder for retrieving a single Sequelize model entry by a unique column or a unique combination of multiple columns. Queries that occur in the same tick and have the same where, attributes, and include parameters are automatically batched using a dataloader and will result in a single database query. This is very useful, especially on a GraphQL server to avoid the N+1 Problem.

This library is heavily inspired by Prisma's findUnique method.

Install

With npm:

npm install sequelize-find-unique

With Yarn:

yarn add sequelize-find-unique

How to use?

A findUnique function can be built for a specific Sequelize model by using the makeFindUnique function:

const { Sequelize, DataTypes } = require('sequelize');
const { makeFindUnique } = require('sequelize-find-unique');

const sequelize = new Sequelize('sqlite::memory:');

const User = sequelize.define('user', {
  id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  username: { type: DataTypes.TEXT, unique: true },
});

const findUniqueUser = makeFindUnique(User);

// ...

// These queries have the same columns in the where parameter, so they are batched. Just one database query is executed
const users = await Promise.all([
  findUniqueUser({
    where: {
      username: 'john',
    },
  }),
  findUniqueUser({
    where: {
      username: 'mary',
    },
  }),
]);

The two findUniqueUser queries in the example are batched and only one database query is executed.

Using as model's static method

The findUnique (or name of your choice) static method can be defined for a model in the following way:

User.findUnique = makeFindUnique(User);

// ...

const user = await User.findUnique({
  where: {
    username: 'kalle',
  },
});

Attributes

Queries with the same attributes parameter are batched:

// These queries have the same attributes parameter, so they are batched. Just one database query is executed
const users = await Promise.all([
  User.findUnique({
    where: {
      username: 'john',
    },
    attributes: ['username'],
  }),
  User.findUnique({
    where: {
      username: 'mary',
    },
    attributes: ['username'],
  }),
]);

Note that, if the attributes parameter is provided, columns used in the where parameter must be present in the attributes parameter.

Associations

Queries with the same include parameter are batched:

// These queries have the same include parameter, so they are batched. Just one database query is executed
const users = await Promise.all([
  User.findUnique({
    where: {
      username: 'john',
    },
    include: { model: Comment },
  }),
  User.findUnique({
    where: {
      username: 'mary',
    },
    include: { model: Comment },
  }),
]);

Composite unique columns

Composite unique columns work just like a single unique column:

// These queries have the same columns in the where parameter, so they are batched. Just one database query is executed
const persons = await Promise.all([
  Person.findUnique({
    where: {
      firstName: 'Kalle',
      lastName: 'Ilves',
    },
  }),
  Person.findUnique({
    where: {
      firstName: 'John',
      lastName: 'Doe',
    },
  }),
]);

Custom serializers

Serializers can be used to customize the batching behavior. The serializeBatchKey option can be used to customize which queries go to the same batch. That is, queries that occur on the same tick will be batched based on the string key returned by the serializeBatchKey. The default serializeBatchKey serializer serializes the columns in the where parameter, the attributes parameter, and the include parameter.

The serielizeLoadKey option can be used to customize the DataLoader's cacheKeyFn function. The default serielizeLoadKey serializer serializes the where parameter.

Both functions receive the options provided for the findUnique function and should return a string. The serializeBatchKey and serializeLoadKey can be provided using the second argument, the options object, of the makeFindUnique function:

const customSerializeBatchKey = (options) => {
  return JSON.stringify(Object.keys(options.where));
};

const customSerializeLoadKey = (options) => {
  return JSON.stringify(options.where);
};

User.findUnique = makeFindUnique(User, {
  serializeBatchKey: customSerializeBatchKey,
  serializeLoadKey: customSerializeLoadKey,
});

Custom cache

The cache option can be used to provide a custom DataLoader cache implementation. The cache keys are string and values DataLoader instances. The cache implementation should implement get, set, and delete methods:

class CustomCache {
  get(key) {
    // ...
  }

  set(key, value) {
    // ...
  }

  delete(key) {
    // ...
  }
}

User.findUnique = makeFindUnique(User, {
  cache: new CustomCache(),
});

The default cache implementation is a simple wrapper around Map.

TypeScript

The library is written in TypeScript, so types are on the house!

If you are using a static method like in the previous examples, just declare the method on your model class:

import { makeFindUnique, FindUniqueOptions } from 'sequelize-find-unique';

export class User extends Model<
  InferAttributes<User>,
  InferCreationAttributes<User>
> {
  declare id: CreationOptional<number>;
  declare username: string;

  declare static findUnique: (
    options: FindUniqueOptions<Attributes<User>>,
  ) => Promise<User | null>;
}

// ...

User.findUnique = makeFindUnique(User);