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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@damatjs/services

v0.6.0

Published

Damatjs services definition

Readme

@damatjs/services

The service layer for Damat modules: auto-generated CRUD per model, a shared connection pool, and typed, lazily-initialized module instances.

@damatjs/services turns a map of ORM model definitions into a fully-featured service class. ModuleService({ models }) returns an abstract base class with one camelCased accessor per model (service.user, service.account, ...), each exposing create / createMany / upsert / upsertMany / find / findById / findOne / findMany / update / updateOne / delete / softDelete / restore / count / exists plus transactions, cascade delete, and relation loading. PoolManager is the process-wide holder of the PostgreSQL pool and entity manager that those services bind to, and defineModule wraps a service class into a typed ModuleInstance whose service is a lazily-constructed Proxy.

It sits between the ORM packages (@damatjs/orm-pg, @damatjs/orm-model, @damatjs/orm-type) and @damatjs/framework, which wires the pool and registers modules at startup.

Part of the Damat monorepo · Full guide · Internals

Install

bun add @damatjs/services

Inside the monorepo it is referenced via the workspace protocol ("@damatjs/services": "*"). Note: @damatjs/framework re-exports this package's entire surface (export * from "@damatjs/services"), so apps that already use the framework typically import ModuleService / defineModule from @damatjs/framework.

When to use

Use it when:

  • You are defining a Damat domain module and want CRUD methods generated from your ORM models.
  • You need transactions that span several models in the module, or relation loading (include).
  • You need to share one PostgreSQL pool / entity manager across all services in the process (PoolManager).

Do not use it:

  • As a general-purpose ORM — model definitions come from @damatjs/orm-model; this package consumes them.
  • Without initializing a pool first — instantiating a generated service throws unless PoolManager.setup({ pool, logger, connectionManager }) has run (the framework does this for you when databaseUrl is configured).

Quick start

import { ModuleService, defineModule } from "@damatjs/services";
import { z } from "@damatjs/deps/zod";
import { UserModel, AccountModel } from "./models";

// 1. Map model name -> ModelDefinition
const models = { user: UserModel, account: AccountModel };

// 2. Generate the base class (optionally with a credentials schema)
export class UserModuleService extends ModuleService({
  models,
  credentialsSchema: z.object({ apiKey: z.string() }),
}) {
  // add custom methods that use the generated accessors:
  async createWithAccount(email: string) {
    return this.transaction(async () => {
      const user = await this.user.create({ data: { email } });
      await this.account.create({ data: { user_id: user.id } });
      return user;
    });
  }
}

// 3. Wrap it as a typed, lazily-initialized module instance
export default defineModule("user", {
  service: UserModuleService,
  credentials: (env) => ({ apiKey: env.API_KEY ?? "" }),
});

Generated accessors are camelCased from the model key (accountservice.account, Verificationservice.verification):

const svc = new UserModuleService({ apiKey: "..." });
const user = await svc.user.create({ data: { email: "[email protected]" }, returning: ["id"] });
const many = await svc.user.findMany({ where: { active: true }, take: 10, include: ["account"] });

// insert-or-update on a unique column, and update returning the single row
await svc.user.upsert({ data: { email: "[email protected]", name: "Ada" }, onConflict: ["email"] });
const updated = await svc.user.updateOne({ where: { id: user.id }, data: { name: "Grace" } });
const byId = await svc.user.findById(user.id);

// remove the user and everything reachable via hasMany/hasOne, atomically
await svc.user.delete({ where: { id: user.id }, cascade: true });

API

| Export | Kind | Summary | | --- | --- | --- | | ModuleService(config) | factory | Builds an abstract base class from { models, credentialsSchema? }. Returns a class with em, getModels, transaction(), and one ModelMethods accessor per model (camelCased key). | | ModelMethods<T> | class | The per-model CRUD surface: create, createMany, upsert, upsertMany, find, findById, findOne, findMany, update, updateOne, delete (optional cascade), softDelete (optional cascade), restore, count, exists, plus relation loading and transaction binding. | | PoolManager | static class | Process-wide holder of the Pool, PgEntityManager, and ConnectionManager. setup, getPool, getPgEntityManager, getConnectionManager, healthCheck, getStats, isInitialized, reset. State lives on globalThis so duplicate package copies share one pool. | | defineModule(name, definition) | factory | Wraps a service class + credentials loader into a ModuleInstance whose .service is a lazy Proxy. Returns { name, service, credentials, init }. | | ModuleDefinition<TService> | type | { service: new (credentials) => TService; credentials: (env) => any }. | | ModuleInstance<TService> | type | { name; service; credentials; init() }. | | ModuleRegistry | interface | Empty interface apps augment via declaration merging so getModule("user") (in the framework) is typed. | | ModuleServiceConfig, ModelsMap, FindOptions, CreateOptions, CreateManyOptions, UpsertOptions, UpsertManyOptions, UpdateOptions, DeleteOptions, SoftDeleteOptions, CountOptions, ExistsOptions, ToCamelCase | types | Configuration and per-method option types for the service layer. | | PoolManagerStats, ConnectionManagerLike | types | Pool statistics and the minimal connection-manager shape PoolManager accepts. | | toCamelCase(name) | internal util | Lowercases the first character only ("UserService""userService"); used internally to derive accessor names. Lives in src/util/string.ts and is not re-exported from @damatjs/services. |

This package has a single root export (@damatjs/services); there are no subpath exports.

Query safety & conventions

The ModelMethods read/write surface enforces a few guarantees so a request-derived options object can't reach the SQL layer with more authority than intended:

  • Pagination. take/skip map to SQL LIMIT/OFFSET. take is a non-negative integer capped at MAX_PAGE_SIZE (1000); a fractional or negative take/skip throws. (Passing no take still returns all matching rows — paginate explicitly for large tables.)
  • Option allow-listing. find/findMany/delete forward only their known option keys. Raw-SQL (whereRaw) and full-table (allowFullTable) escape hatches are not reachable through the service layer — use the underlying @damatjs/orm-pg repository directly when you deliberately need them.
  • orderBy validation. direction is restricted to ASC/DESC and nulls to NULLS FIRST/NULLS LAST (both string-interpolated in SQL, so they're whitelisted rather than trusted).
  • Soft-delete filtering. On a soft-delete model every read (find/findMany/count/exists) adds deleted_at IS NULL automatically. Pass withDeleted: true to include archived rows, or filter on the soft-delete column yourself to override.
  • updated_at maintenance. update/updateOne stamp the model's updated_at/updatedAt column with the current time unless you set it explicitly. Auto-timestamps are timestamp with time zone (sub-second), not date.

How it fits

  • Dependencies: @damatjs/orm-pg (PgEntityManager, PgRepository, transactions), @damatjs/orm-model (ModelDefinition), @damatjs/orm-type, @damatjs/orm-connector, @damatjs/deps (zod), @damatjs/types, @damatjs/logger.
  • In-repo dependents: @damatjs/framework depends on it and re-exports it; the framework's PoolManager.setup(...) (in services/database.ts) initializes the pool this package reads, and registerModule calls each module's init().

Documentation

License

MIT