Catalogue / nestjs-drizzle-boundaries
nestjs-drizzle-boundaries
Older skill: source not recordedSignedBuilds NestJS applications on a typed Drizzle ORM data layer: module and provider boundaries, REST and GraphQL handlers, message patterns, validation pipes, JWT guards, interceptors, exception filters, configuration, migrations and isolated tests. Use when the user asks to "scaffold a Nest controlle…--- name: nestjs-drizzle-boundaries description: >- Builds NestJS applications on a typed Drizzle ORM data layer: module and provider boundaries, REST and GraphQL handlers, message patterns, validation pipes, JWT guards, interceptors, exception filters, configuration, migrations and isolated tests. Use when the user asks to "scaffold a Nest controller or service", "set up Drizzle ORM with Postgres", "add authentication guards or role checks", "write Nest unit or e2e tests", "generate and run database migrations", or "add a GraphQL resolver or microservice handler". Not for frontend frameworks, non-Nest Node servers, or ORM work outside Drizzle and TypeORM. ---
NestJS + Drizzle boundary kit
One application contract across transports and persistence: the boundaries to draw and the code patterns that recur in every Nest feature module.
Scope the work before writing files
Inspect the actual project: runtime and package manager, Nest/TypeScript versions, HTTP adapter, installed drivers, existing tests. Settle endpoint or message behaviour, ownership, side effects and the deployment target.
- Ask before installing packages, creating databases, generating or applying
migrations, starting servers, seeding, deleting or sending anything; a confirmed "implement this feature" covers that scope. Report evidence: tests run and unverified integration.
Choose the boundary for each piece
| Boundary | Owns | Evidence | |---|---|---| | Controller / resolver | Transport args, DTO conversion, status contract | Invalid-input and response tests | | Provider / service | Application decisions, coordinated operations | Unit tests, clear tokens | | Repository | Typed queries, owner predicates, transactions | SQL bindings, DB behaviour | | Module | Imports, providers, exports, instance scope | Tokens resolve in scope | | Cross-cutting component | One middleware/pipe/guard/interceptor/filter job | Ordering, exception behaviour | | Driver / configuration | Trusted target, pool lifetime, adapter version | Startup failure, cleanup | | Message handler | Authenticated envelope, request vs event semantics | Contract, timeout, ack meaning |
- Prefer constructor injection with explicit symbols or classes, not string tokens.
- Keep modules focused; export only intentional public providers; resolve circular
ownership instead of hiding it with global registration. Express is the default adapter; an Express-shaped filter or middleware is not adapter-neutral.
A typed PostgreSQL data layer with Drizzle
Example domain: workshop equipment, bookings, credit accounts; money is integer minor units, never floats.
// data.ts — schema, validation, repository, pool factory
import { pgTable, serial, text, integer, timestamp, check, index } from 'drizzle-orm/pg-core';
import { and, eq, isNull, isNotNull, asc, sql, inArray } from 'drizzle-orm';
import { drizzle, type NodePgDatabase } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
export class DomainError extends Error {
constructor(public status: number, message: string) { super(message); }
} // mappable to HTTP status
export const equipment = pgTable('workshop_equipment', {
id: serial('id').primaryKey(), owner: text('owner').notNull(),
label: text('label').notNull(), costMinor: integer('cost_minor').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
deletedAt: timestamp('deleted_at', { withTimezone: true }),
}, t => [index('equipment_owner_idx').on(t.owner),
check('cost_nonneg', sql`${t.costMinor} >= 0`)]);
// bookings: pgTable('workshop_bookings') — serial id, equipmentId references
// (() => equipment.id, { onDelete: 'cascade' }), purpose text, createdAt
// timestamp defaultNow, withTimezone throughout.
export const credits = pgTable('workshop_credits', {
id: serial('id').primaryKey(), owner: text('owner').notNull(),
balanceMinor: integer('balance_minor').notNull(),
}, t => [check('credits_nonneg', sql`${t.balanceMinor} >= 0`)]);
export const schema = { equipment, bookings, credits }; // bookings per comment above
export type WorkshopDb = NodePgDatabase<typeof schema>;
export type Equipment = typeof equipment.$inferSelect;
// Strict shape: unknown keys (a supplied owner included) are rejected; label is
// trimmed 1..120 chars; costMinor an integer 0..2147483647.
export function validateEquipment(value: unknown): { label: string; costMinor: number } {
const d = (value ?? {}) as Record<string, unknown>;
const good = ['label', 'costMinor'].every(k => k in d) && typeof d.label === 'string' &&
!!d.label.trim() && d.label.length <= 120 && Number.isInteger(d.costMinor) &&
(d.costMinor as number) >= 0 && (d.costMinor as number) <= 2147483647;
if (!good) throw new DomainError(400, 'Invalid equipment');
return { label: (d.label as string).trim(), costMinor: d.costMinor as number };
}
export const boundedPage = (limit = 24, offset = 0) => {
if (!Number.isInteger(limit) || limit < 1 || limit > 80 || !Number.isInteger(offset) ||
offset < 0 || offset > 100000) throw new DomainError(400, 'Invalid pagination');
return { limit, offset };
};
const ownActive = (owner: string, id?: number) => {
if (!owner) throw new DomainError(401, 'Principal required');
if (id !== undefined && (!Number.isSafeInteger(id) || id < 1))
throw new DomainError(400, 'Invalid identifier');
return and(eq(equipment.owner, owner), isNull(equipment.deletedAt),
id === undefined ? undefined : eq(equipment.id, id));
};
const gone = () => new DomainError(404, 'Equipment unavailable');
export class EquipmentRepository {
constructor(readonly db: WorkshopDb) {}
list(owner: string, limit = 24, offset = 0) {
const p = boundedPage(limit, offset);
return this.db.select().from(equipment).where(ownActive(owner))
.orderBy(asc(equipment.id)).limit(p.limit).offset(p.offset);
}
async get(owner: string, id: number) {
const [row] = await this.db.select().from(equipment)
.where(ownActive(owner, id)).limit(1);
if (!row) throw gone();
return row;
}
async create(owner: string, value: unknown) {
if (!owner) throw new DomainError(401, 'Principal required');
const [row] = await this.db.insert(equipment)
.values({ ...validateEquipment(value), owner }).returning();
if (!row) throw new DomainError(500, 'Creation failed');
return row;
} // list(): boundedPage + ownActive(owner), order by id asc.
async archive(owner: string, id: number) { // soft delete
const [row] = await this.db.update(equipment).set({ deletedAt: new Date() })
.where(ownActive(owner, id)).returning();
if (!row) throw gone();
return row;
} // purgeArchived(owner, id, confirmed): hard delete — require the explicit
// confirmation flag and a safe id, DELETE where owner + id + isNotNull
// (deletedAt), else 404 'Archived equipment unavailable'.
async transferCredit(owner: string, from: number, to: number, amount: number) {
if (!owner || !Number.isSafeInteger(from) || from < 1 || !Number.isSafeInteger(to) ||
to < 1 || from === to || !Number.isInteger(amount) || amount < 1 ||
amount > 2147483647) throw new DomainError(400, 'Invalid transfer');
return this.db.transaction(async tx => {
const rows = await tx.select().from(credits)
.where(and(eq(credits.owner, owner), inArray(credits.id, [from, to])))
.orderBy(asc(credits.id)).for('update'); // stable order avoids deadlocks
const src = rows.find(r => r.id === from), dst = rows.find(r => r.id === to);
if (!src || !dst) throw new DomainError(404, 'Credit account unavailable');
if (src.balanceMinor < amount || dst.balanceMinor > 2147483647 - amount)
throw new DomainError(409, 'Balance constraint');
for (const [id, delta] of [[from, -amount], [to, +amount]] as const)
await tx.update(credits)
.set({ balanceMinor: sql`${credits.balanceMinor} + ${delta}` })
.where(eq(credits.id, id));
return { transferredMinor: amount };
});
}
}
export const openWorkshopDatabase = (config: PoolConfig) => {
const pool = new Pool({ ...config, max: config.max ?? 6,
connectionTimeoutMillis: config.connectionTimeoutMillis ?? 4000 });
return { pool, db: drizzle({ client: pool, schema }), close: () => pool.end() };
}; // PoolConfig import elided- The owner comes from the verified principal, never a writable DTO field;
update, archive and delete predicates combine ID, owner and active status in one statement. A prior existence check is racy, and a 404 hides others' data.
- The full-input
update(owner, id, value)setsvalidateEquipment(value)where
ownActive matches, else gone(). For PATCH define an explicit partial DTO with deliberate null semantics, not Partial of every column. withBookings(owner) left-joins bookings on equipmentId and filters with ownActive(owner).
purgeArchiveddeletes one identified, already-archived, owned record after
confirmation; review its cascade first. No public purge endpoint is exposed.
- Never message or email inside a transaction expecting rollback; use an outbox
or after-commit hook. Creating a Pool proves nothing — pair creation with cleanup, and never print connection strings or weaken TLS.
HTTP layer: guards, DTOs, cache, filters
// identity.ts — claim-shape decisions; crypto verification stays in the verifier
import { DomainError } from './data';
export type Principal = { subject: string; roles: string[] };
export const parseBearer = (header: unknown) => {
if (typeof header !== 'string' || !/^Bearer [^\s]+$/i.test(header))
throw new DomainError(401, 'Bearer token required');
return header.slice(7);
};
export function principalFrom(value: unknown): Principal {
const d = (value ?? {}) as Record<string, unknown>;
const rolesOk = Array.isArray(d.roles) && d.roles.length <= 32 &&
d.roles.every(r => typeof r === 'string' && r.length > 0 && r.length <= 64);
if (typeof d.sub !== 'string' || !d.sub || d.sub.length > 256 || !rolesOk)
throw new DomainError(401, 'Invalid identity');
return { subject: d.sub, roles: d.roles as string[] };
}
export const roleAllowed = (user: Principal | undefined, required: string[]) =>
!!user && (!required.length || required.some(r => user.roles.includes(r)));// http.ts (selections; imports from @nestjs/common, @nestjs/core, @nestjs/jwt,
// @nestjs/swagger, class-validator, rxjs)
type RequestLike = { headers: { authorization?: string }; user?: Principal; method: string; url: string };
export const REPOSITORY = Symbol('equipment-repository');
export const AUTH_POLICY = Symbol('auth-policy');
export type AuthPolicy = { issuer: string; audience: string };
export const Roles = (...roles: string[]) => SetMetadata('workshop.roles', roles);
@Injectable() export class AuthenticationGuard implements CanActivate {
constructor(private readonly jwt: JwtService,
@Inject(AUTH_POLICY) private readonly policy: AuthPolicy) {}
async authenticate(request: RequestLike) {
try {
const verified = await this.jwt.verifyAsync(parseBearer(request.headers.authorization),
{ algorithms: ['RS256'], ignoreExpiration: false,
issuer: this.policy.issuer, audience: this.policy.audience });
return (request.user = principalFrom(verified)), true;
} catch { throw new UnauthorizedException('Authentication required'); }
}
canActivate(ctx: ExecutionContext) { return this.authenticate(ctx.switchToHttp().getRequest()); }
}
@Injectable() export class AuthorizationGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(ctx: ExecutionContext) {
const roles = this.reflector.getAllAndOverride<string[]>('workshop.roles',
[ctx.getHandler(), ctx.getClass()]) ?? [];Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 40.0 kB | 85046a5f1376 |
| examples.json | 2.0 kB | 01da58084b0f |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.1 Current | Not recorded | 6 Oct 2026 | |
| 1.0.0 | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.