bhofstaetter

payload repository

by bhofstaetter
APIs & SDKs
v3
>=3.82.0
MIT

Overview

Summary generated from the README

Provides CollectionOperations and GlobalOperations base classes that wrap Payload's Local API in a repository pattern. Types come from Payload's generated types, and the package requires payload 3.82.0 or newer. Defaults and transformers let you apply shared options or rewrite data, where clauses and options for each operation.

Features

  • Repository methods such as findOne, findAll, findByIds, exists, updateByIds and deleteByIds
  • Defaults for req, locale, depth, user and context applied to every operation
  • Transformers that modify data, where clauses and options per operation
  • mergeTransformers to chain transformers from layered repositories
  • Draft, version restore and disableErrors handling with typed return values
  • Custom repository subclasses for shared queries

Use cases

  • Encapsulate domain-specific data access for a collection in a typed operations class
  • Run several Local API calls inside a hook in the same transaction by passing req as a default
  • Inject a tenant condition into queries and writes through transformers

From the author

Opinionated repository and operations object wrapper around Payload's Local API.

Installation

npm i payload-repository

0

Stars

0

Forks

0

Open Issues

5 days ago

Last Updated

229

Weekly Downloads

v2.0.0

npm Version

54.1 KB

Unpacked Size

0

Dependencies

GitHub stars

00 since Sep 6

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20260
Dec 4, 20260
Dec 3, 20260
Dec 2, 20260
Dec 1, 20260
Nov 30, 20260
Nov 29, 20260
Nov 28, 20260
Nov 27, 20260
Nov 26, 20260
Nov 25, 20260
Nov 24, 20260
Nov 23, 20260
Nov 22, 20260
Nov 21, 20260
Nov 20, 20260
Nov 19, 20260
Nov 18, 20260
Nov 17, 20260
Nov 16, 20260
Nov 15, 20260
Nov 14, 20260
Nov 13, 20260
Nov 12, 20260
Nov 11, 20260
Nov 10, 20260
Nov 9, 20260
Nov 8, 20260
Nov 7, 20260
Nov 6, 20260
Nov 5, 20260
Nov 4, 20260
Nov 3, 20260
Nov 2, 20260
Nov 1, 20260
Oct 31, 20260
Oct 30, 20260
Oct 29, 20260
Oct 28, 20260
Oct 27, 20260
Oct 26, 20260
Oct 25, 20260
Oct 24, 20260
Oct 23, 20260
Oct 22, 20260
Oct 21, 20260
Oct 20, 20260
Oct 19, 20260
Oct 18, 20260
Oct 17, 20260
Oct 16, 20260
Oct 15, 20260
Oct 14, 20260
Oct 13, 20260
Oct 12, 20260
Oct 11, 20260
Oct 10, 20260
Oct 9, 20260
Oct 8, 20260
Oct 7, 20260
Oct 6, 20260
Oct 5, 20260
Oct 4, 20260
Oct 3, 20260
Oct 2, 20260
Oct 1, 20260
Sep 30, 20260
Sep 29, 20260
Sep 28, 20260
Sep 27, 20260
Sep 26, 20260
Sep 25, 20260
Sep 24, 20260
Sep 23, 20260
Sep 22, 20260
Sep 21, 20260
Sep 20, 20260
Sep 19, 20260
Sep 18, 20260
Sep 17, 20260
Sep 16, 20260
Sep 15, 20260
Sep 14, 20260
Sep 13, 20260
Sep 12, 20260
Sep 11, 20260
Sep 10, 20260
Sep 9, 20260
Sep 8, 20260
Sep 7, 20260
Sep 6, 20260
npm weekly downloads

211+187 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 2026211
Dec 4, 2026210
Dec 3, 2026189
Dec 2, 20263
Dec 1, 202614
Nov 30, 202614
Nov 29, 202612
Nov 28, 202612
Nov 27, 202612
Nov 26, 202612
Nov 25, 202612
Nov 24, 20261
Nov 23, 20261
Nov 22, 20264
Nov 21, 20264
Nov 20, 20264
Nov 19, 20265
Nov 18, 202614
Nov 17, 202614
Nov 16, 202615
Nov 15, 202612
Nov 14, 202612
Nov 13, 202613
Nov 12, 202623
Nov 11, 202614
Nov 10, 202617
Nov 9, 202616
Nov 8, 202617
Nov 7, 202617
Nov 6, 202615
Nov 5, 20264
Nov 4, 20265
Nov 3, 20264
Nov 2, 20266
Nov 1, 20267
Oct 31, 20268
Oct 30, 20268
Oct 29, 20268
Oct 28, 20267
Oct 27, 20266
Oct 26, 20264
Oct 25, 20263
Oct 24, 20264
Oct 23, 20264
Oct 22, 20266
Oct 21, 20266
Oct 20, 20265
Oct 19, 20265
Oct 18, 20264
Oct 17, 20263
Oct 16, 20263
Oct 15, 20262
Oct 14, 20262
Oct 13, 20262
Oct 12, 20264
Oct 11, 20265
Oct 10, 20264
Oct 9, 20265
Oct 8, 20264
Oct 7, 20264
Oct 6, 20264
Oct 5, 20262
Oct 4, 20261
Oct 3, 20261
Oct 2, 20265
Oct 1, 20265
Sep 30, 202612
Sep 29, 202627
Sep 28, 202635
Sep 27, 202648
Sep 26, 202654
Sep 25, 202651
Sep 24, 202658
Sep 23, 202652
Sep 22, 202647
Sep 21, 202643
Sep 20, 202631
Sep 19, 202625
Sep 18, 202625
Sep 17, 202619
Sep 16, 202620
Sep 15, 202610
Sep 14, 20268
Sep 13, 20267
Sep 12, 20267
Sep 11, 202620
Sep 10, 202619
Sep 9, 202618
Sep 8, 202623
Sep 7, 202624
Sep 6, 202624

Each point is npm's rolling 7-day download count.

Health Score

75/100Excellent

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1169584752-root.svg)](https://payloaddirectory.dev/plugins/1169584752-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1169584752-root"><img src="https://payloaddirectory.dev/badge/1169584752-root.svg" alt="Payload Directory"></a>
Updated Nov 30, 2026Created Feb 28, 2026Published Nov 30, 2026

README

Payload Repository and Operations

Opinionated repository and operations object wrapper around Payload's Local API.

Installation

npm install payload-repository

Requires payload >= 3.82.0.

Usage

Select, data and result types come from Payload's generated types, i.e. the augmentation declare module 'payload' { interface GeneratedTypes extends Config {} } that payload generate:types writes. Without it there is no type safety. Pass your generated Config type as the first type argument as well.

CollectionOperations

Extend CollectionOperations to encapsulate domain-specific operations logic for a collection:

import type {BasePayload} from 'payload';
import type {Config} from '@/payload-types';
import {CollectionOperations} from 'payload-repository';

class PostsOperations extends CollectionOperations<Config, 'posts'> {
    constructor(payload: BasePayload) {
        super(payload, 'posts');
    }

    create(title: string) {
        return this.repository.create({title});
    }

    findAll() {
        return this.repository.findAll({});
    }

    findById(id: number) {
        return this.repository.findById(id);
    }

    findBySlug(slug: string) {
        return this.repository.findOne({slug: {equals: slug}});
    }

    findPublished() {
        return this.repository.findAll({status: {equals: 'published'}});
    }

    publish(id: number) {
        return this.repository.updateById(id, {status: 'published'});
    }

    deleteById(id: number) {
        return this.repository.deleteById(id);
    }
}

// Usage
const postsOperations = new PostsOperations(payload);

const post = await postsOperations.create('Hello World');
const published = await postsOperations.findPublished();
await postsOperations.publish(post.id);

find returns Payload's paginated result (10 documents by default). For the common cases there are shortcuts that run through find or count and therefore use their transformers:

  • findOne(where) returns the first match or null.
  • findAll(where) returns all matching documents as an array (pagination: false).
  • exists(where) returns whether at least one document matches.

A find options transformer sees limit: 1 (findOne) and pagination: false (findOne, findAll) and can override limit.

findByIds sets limit to the number of ids by default, so all requested documents are returned. An explicit limit takes precedence.

joins is typed by the join fields of the collection.

Drafts

create without draft publishes the document (_status: 'published' is set for collections with drafts). create(data, {draft: true}) saves a draft and accepts partial data.

update and updateById without draft keep the status like Payload does: an open draft stays a draft. Set _status: 'published' in the data to publish, or pass draft: true to save as draft.

Bulk operations

update, updateByIds, delete and deleteByIds return Payload's BulkOperationResult unchanged. As in the Local API, per-document failures are collected in errors instead of being thrown, and the successful documents are written. Check errors (and compare docs with the requested ids) when partial success matters:

const {docs, errors} = await this.repository.updateByIds(ids, {status: 'archived'});

if (errors.length > 0) {
    // docs were updated, errors were not
}
Versions

restoreVersion(versionId) is available for collections and globals. draft is not available, because Payload's Local API ignores it. For globals, Payload returns the new version record (typed as TypeWithVersion), not the global; call find() afterwards if you need the restored global.

disableErrors

With disableErrors: true, findById, findVersionById and GlobalRepository.find return null instead of throwing, and the return type becomes nullable. The type is nullable only for a literal true; with a boolean variable or a disableErrors set by an options transformer it stays non-null, as with Payload's findByID.

GlobalOperations

Extend GlobalOperations to encapsulate domain-specific operations logic for a global:

import type {BasePayload} from 'payload';
import type {Config} from '@/payload-types';
import {GlobalOperations} from 'payload-repository';

class SettingsOperations extends GlobalOperations<Config, 'settings'> {
    constructor(payload: BasePayload) {
        super(payload, 'settings');
    }

    get() {
        return this.repository.find();
    }

    setSiteTitle(title: string) {
        return this.repository.update({siteTitle: title});
    }
}

// Usage
const settingsOperations = new SettingsOperations(payload);

const settings = await settingsOperations.get();
await settingsOperations.setSiteTitle('My Site');

Defaults

Pass defaults as the fourth argument to apply options to every operation. Allowed are req, locale, fallbackLocale, depth, overrideAccess, user and context. Explicit options win, and transformers see the merged result. An explicit undefined in the options keeps the default.

A typical use is passing req inside a hook, so all operations run in the same transaction:

import type {CollectionAfterChangeHook, PayloadRequest} from 'payload';

class AuthorsOperations extends CollectionOperations<Config, 'authors'> {
    constructor(req: PayloadRequest) {
        super(req.payload, 'authors', undefined, {req});
    }

    rename(id: number, name: string) {
        return this.repository.updateById(id, {name});
    }
}

const afterChange: CollectionAfterChangeHook = async ({doc, req}) => {
    await new AuthorsOperations(req).rename(doc.author, doc.authorName);
};

Payload mutates a passed req (locale, fallbackLocale, context, user, query.depth). A req shared via defaults therefore carries these values into later calls, just as with direct Local API use. If calls need different locales, set locale explicitly on each call.

Transformers

Transformers are optional middleware functions that intercept and modify arguments before they reach the Payload API. They can transform data, where clauses, and options on a per-operation basis.

Pass transformers as the third argument to CollectionOperations or GlobalOperations:

import type {BasePayload, Where} from 'payload';
import type {Config} from '@/payload-types';
import {CollectionOperations} from 'payload-repository';
import type {CollectionTransformers} from 'payload-repository';

const withTenant = (where: Where, tenantId: number): Where => ({and: [where, {tenant: {equals: tenantId}}]});

const tenantTransformers = (tenantId: number): CollectionTransformers<Config, 'posts'> => ({
    create: {
        data: data => ({...data, tenant: tenantId}),
    },
    find: {
        where: where => withTenant(where, tenantId),
    },
    count: {
        where: where => withTenant(where, tenantId),
    },
    update: {
        data: data => ({...data, tenant: tenantId}),
        where: where => withTenant(where, tenantId),
    },
    delete: {
        where: where => withTenant(where, tenantId),
    },
});

class PostsOperations extends CollectionOperations<Config, 'posts'> {
    constructor(payload: BasePayload, tenantId: number) {
        super(payload, 'posts', tenantTransformers(tenantId));
    }

    create(title: string) {
        return this.repository.create({title});
    }

    findAll() {
        return this.repository.findAll({});
    }
}

// Usage
const tenantPosts = new PostsOperations(payload, 42);

// tenant is automatically injected into the data
await tenantPosts.create('Hello World');

// tenant where clause is automatically applied
const posts = await tenantPosts.findAll();

Combine the caller's where with and instead of spreading it: {...where, tenant: …} silently overwrites a tenant condition the caller set, while and keeps every condition of the caller, including or.

Transformers support async functions and are available for all repository operations:

  • Options transformers run first, then where transformers. Options transformers receive the defaults, or {} when neither options nor defaults are given.
  • where slots exist for find, count, findDistinct, findVersions, countVersions, update and delete. findOne, findAll and exists use the find and count transformers; findByIds, updateByIds and deleteByIds use the find, update and delete where transformers.
  • For findVersions and countVersions, field conditions need the version. prefix; Payload's appendVersionToQueryKey converts an existing where.
  • Options (and options transformers) cannot override where, id, data, collection, slug or field; the repository sets them after the options. Bulk update and delete (including updateByIds and deleteByIds) drop an id from the options, so Payload cannot switch to the single-document operation and skip where.
  • Unknown operation names are rejected by the type.

[!WARNING] findById, updateById, deleteById, duplicate, findVersionById and restoreVersion have no where in Payload, so where transformers do not apply to them. Where transformers are a query convenience, not a security boundary. To enforce isolation, use access control: overrideAccess: false with a user (e.g. via defaults), or Payload's official multi-tenant plugin.

All public types (CollectionTransformers, FindOptions, GlobalSelectResult, RepositoryDefaults, …) are exported from payload-repository.

Merging Transformers

When building layered repositories where each layer contributes its own transformers, use mergeTransformers to combine them. Overlapping transformers on the same operation and argument are chained sequentially:

import type {BasePayload, TypedLocale} from 'payload';
import type {Config} from '@/payload-types';
import {CollectionOperations, mergeTransformers} from 'payload-repository';
import type {CollectionTransformers} from 'payload-repository';

const tenantTransformers = (tenantId: number): CollectionTransformers<Config, 'posts'> => ({
    find: {
        where: where => ({and: [where, {tenant: {equals: tenantId}}]}),
    },
});

const localeTransformers = (locale: TypedLocale): CollectionTransformers<Config, 'posts'> => ({
    find: {
        options: options => ({...options, locale}),
    },
});

class PostsOperations extends CollectionOperations<Config, 'posts'> {
    constructor(payload: BasePayload, tenantId: number, locale: TypedLocale) {
        super(payload, 'posts', mergeTransformers(
            tenantTransformers(tenantId),
            localeTransformers(locale),
        ));
    }

    findAll() {
        return this.repository.findAll({});
    }
}

mergeTransformers works with both CollectionTransformers and GlobalTransformers. When multiple transformer objects define the same leaf (e.g. both define find.where), they are chained in order — the second transformer receives the output of the first.

Custom repository

When several operations classes need the same query, or a query needs repository internals, extend the repository instead of repeating it in each operations class. Override repository in the operations class with your subclass:

import type {BasePayload, CollectionSlug} from 'payload';
import type {Config} from '@/payload-types';
import {CollectionOperations, CollectionRepository} from 'payload-repository';
import type {AnyCollectionConfig} from 'payload-repository';

class SluggedRepository<TConfig extends AnyCollectionConfig, TSlug extends CollectionSlug> extends CollectionRepository<
    TConfig,
    TSlug
> {
    findBySlug(slug: string) {
        return this.findOne({slug: {equals: slug}});
    }
}

class PostsOperations extends CollectionOperations<Config, 'posts'> {
    protected override readonly repository: SluggedRepository<Config, 'posts'>;

    constructor(payload: BasePayload) {
        super(payload, 'posts');
        this.repository = new SluggedRepository(payload, 'posts');
    }

    findBySlug(slug: string) {
        return this.repository.findBySlug(slug);
    }
}

Inside a repository subclass, this.payload is a Promise<BasePayload>. If you need several repositories or your own context in one class, write your own base class instead of extending CollectionOperations.

Migrating from 1.x

  • Import all types from payload-repository; the payload-repository/internal/types subpath was removed.
  • Version count result types are CollectionCountVersionsResult and GlobalCountVersionsResult.
  • Transformer maps reject unknown operation names; OperationsTransformerMap is no longer an index signature on CollectionTransformers and GlobalTransformers.
  • findByIds, updateByIds and deleteByIds apply the find, update and delete where transformers.
  • findByIds sets limit to the number of ids by default.
  • Collections with versions but without drafts no longer get _status on create.
  • Options transformers receive the defaults or {} instead of undefined.
  • With disableErrors: true the return type is nullable.
  • Select types come from Payload's GeneratedTypes augmentation instead of the Config type argument.
  • Options can no longer override where, id, data, collection, slug or field.
  • GlobalRepository.restoreVersion resolves to TypeWithVersion<…> (the new version record).
  • payload in repository subclasses is a Promise<BasePayload> (since 1.1.2).
  • Requires payload >= 3.82.0.

License

MIT

Similar plugins