agentleFS
Hive-AcademyHive-Academy/ptah-extension/.claude/skills/nestjs-backend-patterns/SKILL.md

nestjs-backend-patterns

Skill29 starsChanged 2 months agoMITView on GitHub

NestJS backend architecture for multi-tenant SaaS. Use for third-party API providers, Prisma or ZenStack setup, multitenancy, authentication, RBAC or policies, and repositories. Not for retries, events or dynamic modules — use resilient-nestjs-patterns.

  • Reads credentials

The file

We split this skill into the rules it gives an agent

1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    All third-party integrations follow the same provider pattern:

    line 16

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

NestJS Backend Architecture Patterns

Patterns for building scalable, maintainable NestJS backends in an Nx monorepo.

Activation scope

This skill activates per-module during Stage B of the SaaS bootstrap. saas-workspace-initializer may scaffold thin tenant/auth primitives in the Stage A foundation, but full provider-pattern integrations, multitenancy enforcement, and Prisma/ZenStack policy work happen in dedicated Stage B sessions driven by individual roadmap items. Pull this skill in when implementing one such item, not to retrofit an entire backend.

Core Principle: Provider Pattern for External Services

All third-party integrations follow the same provider pattern:

// 1. Create a provider factory
export const ThirdPartyClientProvider = {
  provide: 'THIRD_PARTY_CLIENT',
  useFactory: (configService: ConfigService) => {
    return new ThirdPartySDK(configService.get('THIRD_PARTY_API_KEY'));
  },
  inject: [ConfigService],
};

// 2. Create a service that wraps the client
@Injectable()
export class ThirdPartyService {
  constructor(@Inject('THIRD_PARTY_CLIENT') private client: ThirdPartySDK) {}

  async doSomething() {
    return this.client.operation();
  }
}

// 3. Create a module that exports the service
@Module({
  imports: [ConfigModule],
  providers: [ThirdPartyClientProvider, ThirdPartyService],
  exports: [ThirdPartyService],
})
export class ThirdPartyModule {}

Quick Reference

PatternUse CaseReference
Provider PatternThird-party API integrationthird-party-integration.md
MultitenancyShared schema with tenant isolationmultitenancy.md
Prisma + ZenStackORM with declarative access controlprisma-zenstack.md
RBACRole-based authorizationauthorization.md
JWT AuthenticationStateless auth with Passportauthentication.md

Third-Party Integration Pattern

Step 1: Provider Factory

// libs/shared/payments/src/lib/payment-client.provider.ts
import { ConfigService } from '@nestjs/config';

export const PaymentClientProvider = {
  provide: 'PAYMENT_CLIENT',
  useFactory: (config: ConfigService) => {
    const provider = config.get('PAYMENT_PROVIDER'); // 'stripe', 'paddle', etc.
    const apiKey = config.get('PAYMENT_API_KEY');

    // Factory returns appropriate client based on config
    switch (provider) {
      case 'stripe':
        return new StripeClient(apiKey);
      case 'paddle':
        return new PaddleClient(apiKey);
      default:
        throw new Error(`Unknown payment provider: ${provider}`);
    }
  },
  inject: [ConfigService],
};

Step 2: Abstract Service Interface

// libs/shared/payments/src/lib/payment.interface.ts
export interface PaymentClient {
  createCustomer(data: CreateCustomerDto): Promise<Customer>;
  createSubscription(data: CreateSubscriptionDto): Promise<Subscription>;
  cancelSubscription(id: string): Promise<void>;
  handleWebhook(payload: Buffer, signature: string): Promise<WebhookEvent>;
}

Step 3: Service Implementation

// libs/shared/payments/src/lib/payment.service.ts
@Injectable()
export class PaymentService {
  constructor(@Inject('PAYMENT_CLIENT') private client: PaymentClient) {}

  async createCustomer(dto: CreateCustomerDto): Promise<Customer> {
    return this.client.createCustomer(dto);
  }

  async createSubscription(dto: CreateSubscriptionDto): Promise<Subscription> {
    return this.client.createSubscription(dto);
  }
}

Multitenancy Pattern (Shared Schema)

// Context-aware Prisma service using CLS (Continuation Local Storage)
@Injectable()
export class TenantAwarePrismaService {
  constructor(
    private prisma: PrismaService,
    private cls: ClsService,
  ) {}

  get client() {
    const tenantId = this.cls.get('tenantId');
    if (!tenantId) {
      throw new UnauthorizedException('No tenant context');
    }

    // Return enhanced client with tenant filter
    return enhance(this.prisma, { user: { tenantId } });
  }
}

Module Organization

libs/
├── shared/
│   ├── prisma-client/        # Prisma + ZenStack setup
│   │   ├── prisma.service.ts
│   │   ├── enhanced-prisma.service.ts
│   │   └── prisma-client.module.ts
│   ├── auth/                 # Authentication infrastructure
│   │   ├── strategies/
│   │   │   └── jwt.strategy.ts
│   │   ├── guards/
│   │   │   ├── jwt-auth.guard.ts
│   │   │   └── roles.guard.ts
│   │   └── auth.module.ts
│   └── [service-name]/       # Third-party integrations
│       ├── [name]-client.provider.ts
│       ├── [name].service.ts
│       └── [name].module.ts
└── [domain]/
    └── feature-api/
        ├── controllers/
        ├── dto/
        └── [domain].module.ts

Decision Matrix

NeedPatternReference
Payment processingProvider patternthird-party-integration.md
External auth (OAuth)Provider pattern + Passportauthentication.md
Email serviceProvider patternthird-party-integration.md
File storageProvider patternthird-party-integration.md
Tenant isolationZenStack policiesmultitenancy.md
Role-based accessGuards + decoratorsauthorization.md

References

Load these for detailed implementation guidance:

  • third-party-integration.md - Generic pattern for any external service
  • multitenancy.md - Multi-tenant architecture patterns
  • prisma-zenstack.md - ORM setup with access policies
  • authorization.md - RBAC and permission patterns
  • authentication.md - JWT and OAuth patterns

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.