Skip to main content
rule CX Codex

server-feature-conventions — Claude Code rule

server-feature-conventions is a rule that structures server feature libraries with NestJS modules, DynamoDB repositories, and services, and scaffolds new features from a template.

MIT ★ 372 updated 2026-09-10

Install into Claude Code · Plugin marketplace All methods and platforms ↓
/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-typescript@developer-kit
Open on GitHub

What server-feature-conventions does

Codifies patterns for server architecture: directory layout, naming conventions, dependency injection via tokens and forRootAsync. Each feature is a NestJS module with a repository interface (abstraction) and DynamoDB implementation, services for operations, controllers, exceptions, utils.

Includes file paths, naming table (service {Action}{Entity}Service, repository DynamoDb{Entity}Repository), code examples for module setup, options interface, token injection. Shows how forRoot and forRootAsync configure via factory functions, instantiate DynamoDB client with Lambda optimization, structure a service with logging and error checks.

Examples cover tenant creation, lookup by ID and VAT number, paginated fetch — typical CRUD operations. Requires TypeScript and NestJS in your project.

What it helps with

  • scaffold a new server feature without guesswork
  • name classes, files and tokens uniformly
  • set up DynamoDB client and injection once correctly
  • separate repository interface from implementation
  • add a service with logging and error handling

Example prompts for the agent

  • Create a new feature for orders following the server-feature-conventions structure
  • Write a FindOrderService with an execute method using the pattern from the rule
  • Generate a DynamoDB repository for Order with Inject and Logger from the template

How to install server-feature-conventions

1Plugin marketplace

/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-typescript@developer-kit

2Manually: put the files in place

.claude/rules/server-feature-conventions.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about server-feature-conventions

How do I install server-feature-conventions in Claude Code?

In Marketplace, run /plugin marketplace add giuseppe-trisciuoglio/developer-kit, then /plugin install developer-kit-typescript@developer-kit. The rule will be available at .claude/rules/server-feature-conventions.md.

What does server-feature-conventions do?

Defines a single pattern for server features: folder structure, class naming (services, repositories, tokens), examples of NestJS modules with forRootAsync and DynamoDB integration. The assistant uses this rule to generate new features and services consistently.

What dependencies do I need?

TypeScript, NestJS (modules, injection), AWS SDK (@aws-sdk/client-dynamodb, @aws-sdk/lib-dynamodb). The rule includes examples with Lambda-optimized DynamoDB client and marshalling setup.

Source text

server-feature-conventions.md · MIT
---
paths:
  - "**/*.ts"
---
# Rule: Server Feature Conventions

## Context
Enforce consistent patterns for server-side feature libraries in `libs/server/`. Features encapsulate domain logic with DynamoDB repositories, services, and NestJS modules following the forRootAsync pattern.

## Guidelines

### Feature Library Structure

```
libs/server/{feature-name}/
├── src/
│   ├── index.ts                         # Barrel export
│   └── lib/
│       ├── {feature-name}.module.ts    # Root module with forRoot/forRootAsync
│       ├── {feature-name}-options.ts   # Options interface + injection token
│       ├── tokens.ts                    # All injection tokens
│       ├── controllers/
│       │   ├── index.ts
│       │   └── {resource}.controller.ts
│       ├── services/
│       │   ├── index.ts
│       │   ├── {action}-{entity}.service.ts
│       │   ├── {action}-{entity}.service.spec.ts
│       │   └── index.ts
│       ├── repositories/
│       │   ├── index.ts
│       │   ├── {entity}.repository.ts    # Interface
│       │   ├── dynamodb-{entity}.repository.ts
│       │   └── dynamodb-{entity}.repository.spec.ts
│       ├── exceptions/
│       │   ├── index.ts
│       │   ├── {domain}-not-found.exception.ts
│       │   └── {domain}-already-exists.exception.ts
│       └── utils/
│           ├── index.ts
│           ├── counter.util.ts
│           └── counter.util.spec.ts
├── jest.config.ts
└── tsconfig.json
```

### Naming Conventions

| Element | Pattern | Example |
|---|---|---|
| Feature name | `{entity}-feature` | `tenant-feature` |
| Module | `{Feature}Module` | `TenantFeatureModule` |
| Service | `{Action}{Entity}Service` | `CreateTenantService` |
| Repository | `{Entity}Repository` / `DynamoDb` | `Tenant{Entity}RepositoryRepository` / `DynamoDbTenantRepository` |
| Options | `{Feature}Options` | `TenantFeatureOptions` |
| Token | `{SERVICE_NAME}_TOKEN` | `CREATE_TENANT_SERVICE` |

### Module Pattern — forRootAsync

```typescript
// src/lib/tenant-feature.module.ts
import {
  type DynamicModule,
  type InjectionToken,
  Module,
  type OptionalFactoryDependency,
  type Provider,
} from '@nestjs/common';
import type { ModuleMetadata } from '@nestjs/common';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
import { MY_FEATURE_OPTIONS, MY_SERVICE, MY_REPOSITORY } from './tokens';
import { DYNAMODB_CLIENT } from '@sibill-erp-gateway/server/dynamodb-utils';
import type { MyFeatureOptions } from './my-feature-options';
import { MyService } from './services';
import { MyRepository } from './repositories';
import { createLambdaOptimizedConfig } from '@sibill-erp-gateway/server/dynamodb-utils';

@Module({})
export class MyFeatureModule {
  private static createProviders(optionsProvider: Provider): Omit<DynamicModule, 'module'> {
    const repositoryProvider: Provider = {
      provide: MY_REPOSITORY,
      useClass: DynamoDbMyRepository,
    };

    const dynamoDbClientProvider: Provider = {
      provide: DYNAMODB_CLIENT,
      useFactory: (options: MyFeatureOptions) => {
        const dynamoClientConfig = createLambdaOptimizedConfig({
          region: options.region,
          endpoint: options.endpoint,
        });
        const client = new DynamoDBClient(dynamoClientConfig);
        return DynamoDBDocumentClient.from(client, {
          marshallOptions: {
            convertEmptyValues: false,
            removeUndefinedValues: true,
            convertClassInstanceToMap: true,
          },
          unmarshallOptions: {
            wrapNumbers: false,
          },
        });
      },
      inject: [MY_FEATURE_OPTIONS],
    };

    const serviceProvider: Provider = {
      provide: MY_SERVICE,
      useClass: MyService,
    };

    return {
      providers: [optionsProvider, repositoryProvider, dynamoDbClientProvider, serviceProvider],
      exports: [MY_SERVICE],
    };
  }

  static forRoot(options: MyFeatureOptions): DynamicModule {
    return {
      module: MyFeatureModule,
      providers: [{ provide: MY_FEATURE_OPTIONS, useValue: options }],
      ...MyFeatureModule.createProviders({ provide: MY_FEATURE_OPTIONS, useValue: options }),
    };
  }

  static forRootAsync<T extends Array<unknown> = []>(options: {
    imports?: ModuleMetadata['imports'];
    useFactory: (...args: T) => MyFeatureOptions | Promise<MyFeatureOptions>;
    inject?: Array<InjectionToken | OptionalFactoryDependency>;
  }): DynamicModule {
    const optionsProvider: Provider = {
      provide: MY_FEATURE_OPTIONS,
      useFactory: options.useFactory,
      inject: options.inject || [],
    };

    return {
      module: MyFeatureModule,
      imports: options.imports,
      ...MyFeatureModule.createProviders(optionsProvider),
    };
  }
}
```

### Options Interface

```typescript
// src/lib/my-feature-options.ts
export interface MyFeatureOptions {
  tableName: string;
  countersTableName?: string;
  region: string;
  endpoint?: string;
}
```

### Injection Tokens

```typescript
// src/lib/tokens.ts
import type { InjectionToken } from '@nestjs/common';

export const MY_FEATURE_OPTIONS: InjectionToken = 'MY_FEATURE_OPTIONS';
export const MY_SERVICE = 'MY_SERVICE';
export const MY_REPOSITORY = 'MY_REPOSITORY';
```

### Service Pattern

```typescript
// src/lib/services/create-tenant.service.ts
import { Inject, Injectable, Logger } from '@nestjs/common';
import type { TenantRepository } from '../repositories';
import { MY_REPOSITORY } from '../tokens';
import type { CreateTenantInput } from '@sibill-erp-gateway/shared/tenant-dto';
import type { TenantDto } from '@sibill-erp-gateway/shared/tenant-dto';

@Injectable()
export class CreateTenantService {
  private readonly logger = new Logger(CreateTenantService.name);

  constructor(
    @Inject(MY_REPOSITORY)
    private readonly tenantRepository: TenantRepository,
  ) {}

  async execute(input: CreateTenantInput, requestId: string): Promise<TenantDto> {
    this.logger.log({ requestId, input }, 'Creating tenant');

    const existing = await this.tenantRepository.findByVatNumber(input.vatNumber);
    if (existing) {
      throw new TenantAlreadyExistsException(input.vatNumber);
    }

    const tenant = await this.tenantRepository.create(input, requestId);
    return tenant;
  }
}
```

### Repository Interface

```typescript
// src/lib/repositories/tenant.repository.ts
import type { CreateTenantInput } from '@sibill-erp-gateway/shared/tenant-dto';
import type { TenantDto } from '@sibill-erp-gateway/shared/tenant-dto';

export interface TenantRepository {
  create(input: CreateTenantInput, requestId: string): Promise<TenantDto>;
  findById(tenantId: string): Promise<TenantDto | null>;
  findByVatNumber(vatNumber: string): Promise<TenantDto | null>;
  findAll(cursor?: string, limit?: number): Promise<{ data: TenantDto[]; nextCursor?: string }>;
}
```

### DynamoDB Repository Implementation

```typescript
// src/lib/repositories/dynamodb-tenant.repository.ts
import { Inject, Injectable, Logger } from '@nestjs/common';
import { DynamoDBDocumentClient, PutCommand, GetCommand, QueryCommand } from '@aws-sdk/lib-dynamodb';
import { DYNAMODB_CLIENT } from '@sibill-erp-gateway/server/dynamodb-utils';
import type { TenantRepository } from './tenant.repository';
import type { CreateTenantInput, TenantDto } from '@sibill-erp-gateway/shared/tenant-dto';
import { TenantStatus } from '@sibill-erp-gateway/shared/tenant-dto';

@Injectable()
export class DynamoDbTenantRepository implements TenantRepository {
  private readonly logger = new Logger(DynamoDbTenantRepository.name);
  private readonly tableName: string;

  constructor(
    @Inject(DYNAMODB_CLIENT)
    private readonly docClient: DynamoDBDocumentClient,
    @Inject('TENANT_FEATURE_OPTIONS')
    private readonly options: { tableName: string },
  ) {
    this.tableName = options.tableName;
  }

  async create(input: CreateTenantInput, requestId: string): Promise<TenantDto> {
    const tenantId = crypto.randomUUID();
    const now = new Date().toISOString();

    const item = {
      tenantId,
      tenantName: input.tenantName,
      vatNumber: input.vatNumber,
      adminEmail: input.adminEmail,
      status: TenantStatus.Created,
      createdAt: now,
      updatedAt: now,
    };

    await this.docClient.send(
      new PutCommand({
        TableName: this.tableName,
        Item: item,
      }),
    );

    return item;
  }

  async findById(tenantId: string): Promise<TenantDto | null> {
    const result = await this.docClient.send(
      new GetCommand({
        TableName: this.tableName,
        Key: { tenantId },
      }),
    );

    return result.Item ? (result.Item as TenantDto) : null;
  }

  async findByVatNumber(vatNumber: string): Promise<TenantDto | null> {
    const result = await this.docClient.send(
      new QueryCommand({
        TableName: this.tableName,
        IndexName: 'vatNumber-index',
        KeyConditionExpression: 'vatNumber = :vatNumber',
        ExpressionAttributeValues: { ':vatNumber': vatNumber },
      }),
    );

    return result.Items?.[0] ? (result.Items[0] as TenantDto) : null;
  }
}
```

### Custom Exceptions

```typescript
// src/lib/exceptions/tenant-already-exists.exception.ts
export class TenantAlreadyExistsException extends Error {
  constructor(vatNumber: string) {
    super(`Tenant with VAT number ${vatNumber} already exists`);
    this.name = 'TenantAlreadyExistsException';
  }
}
```

### Counter Utility Pattern

```typescript
// src/lib/utils/counter.util.ts
import { DynamoDBDocumentClient, UpdateCommand } from '@aws-sdk/lib-dynamodb';

export class CounterService {
  constructor(
    private readonly docClient: DynamoDBDocumentClient,
    private readonly countersTableName: string,
  ) {}

  async increment(counterId: string): Promise<number> {
    const result = await this.docClient.send(
      new UpdateCommand({
        TableName: this.countersTableName,
        Key: { counterId },
        UpdateExpression: 'SET #count = if_not_exists(#count, :zero) + :inc',
        ExpressionAttributeNames: { '#count': 'count' },
        ExpressionAttributeValues: { ':inc': 1, ':zero': 0 },
        ReturnValues: 'UPDATED_NEW',
      }),
    );

    return Number(result.Attributes?.count);
  }
}
```

### Barrel Exports

```typescript
// src/lib/services/index.ts
export * from './create-tenant.service';
```

```typescript
// src/lib/repositories/index.ts
export * from './tenant.repository';
export * from './dynamodb-tenant.repository';
```

```typescript
// src/index.ts
export * from './lib/tenant-feature.module';
export * from './lib/services';
export * from './lib/repositories';
export * from './lib/exceptions';
export { CreateTenantService, CREATE_TENANT_SERVICE } from './lib/services';
```

## Examples

### ✅ Good

```typescript
// Feature with forRootAsync for dynamic config
MyFeatureModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: (config: ConfigService) => ({
    tableName: config.get<string>('MY_TABLE')!,
    region: config.get<string>('AWS_REGION') || 'eu-central-1',
  }),
  inject: [ConfigService],
})
```

### ❌ Bad

```typescript
// Hardcoded table name in module
@Module({
  providers: [
    {
      provide: MY_REPOSITORY,
      useFactory: () => new DynamoDbRepository('hardcoded-table'),
    },
  ],
})
export class MyFeatureModule {}

// Direct AWS SDK without abstraction
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
const client = new DynamoDBClient({ region: 'eu-central-1' });
```

## Integration with Lambda Handlers

```typescript
// In Lambda handler
import {
  CREATE_TENANT_SERVICE,
  CreateTenantService,
} from '@sibill-erp-gateway/server/tenant-feature';

@Injectable()
export class CreateTenantHandler extends BaseLambdaHandlerService {
  constructor(
    @Inject(CREATE_TENANT_SERVICE)
    private readonly createTenantService: CreateTenantService,
  ) {
    super();
  }

  async handle(event, context) {
    const result = await this.createTenantService.execute(validatedInput, context.awsRequestId);
    return successResponse(HttpStatus.CREATED, result);
  }
}
```

© Giuseppe Trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar IDE rules

All IDE rules for Backend and APIs →
generic-feature-developer travisjneuman generic-feature-developer walks a feature from reading the codebase to picking patterns, shipping small commits and checking edge cases before you close it. CX Codex +1 142installs generic-fullstack-feature-developer travisjneuman generic-fullstack-feature-developer guides end-to-end feature development across Next.js App Router, NestJS, and Prisma. Use it when adding full-stack slices, updating schemas, or building API routes. CX Codex +1 180installs nestjs-hexagonal Softtor nestjs-hexagonal — a plugin for designing NestJS applications with Hexagonal Architecture, DDD, and CQRS patterns. Provides layer-specific skills, Opus and Sonnet agents, code checking, and TDD workflow. ★ 5repo stars nestjs-feature-audit amirtaherkhani The nestjs-feature-audit Claude Code skill checks a NestJS feature against its roadmap and produces a report backed by evidence. It runs on requests to verify feature coverage, migration progress, or differences from an acceptance plan. CX Codex +1 454installs nestjs-best-practices Kadajett nestjs-best-practices is a Claude Code skill for writing, reviewing, and refactoring NestJS code. It covers architecture, security, and performance tasks. CX Codex +1 32,000installs nestjs-architecture-principles amirtaherkhani The nestjs-architecture-principles Claude Code skill plans and reviews NestJS application architecture. It activates for module-boundary changes, dependency cycles, or decisions about CQRS and microservices. CX Codex +1 592installs

From the same set191

The whole set →
python-code-review-expert python-code-review-expert is a Claude Code subagent that checks Python code for bugs, security flaws, and quality issues. It joins code reviews and pull request assessments. CX Codex ★ 372repo stars aws-cloudformation-task-ecs-deploy-gh aws-cloudformation-task-ecs-deploy-gh — a skill that walks the agent through shipping containers to Amazon ECS from GitHub Actions: OIDC login, ECR push, task definition update, service deploy. CX Codex +1 ★ 372repo stars general-refactor-expert general-refactor-expert is a Claude Code subagent for refactoring code while preserving behavior. It finds code smells and applies SOLID patterns. CX Codex ★ 372repo stars aws-cloudformation-rds aws-cloudformation-rds guides Claude Code through AWS CloudFormation templates for Amazon RDS, Aurora, multi-AZ setups, and related network resources. Use it when shaping database infrastructure. CX Codex +1 ★ 372repo stars aws-cloudformation-lambda aws-cloudformation-lambda is a Claude Code skill with CloudFormation templates for AWS Lambda functions, S3 and SQS triggers, HTTP API Gateway, and CLI workflows. CX Codex +1 ★ 372repo stars devkit.github.create-pr devkit.github.create-pr — a Claude Code command that creates a branch, commits changes following Conventional Commits, and opens a GitHub pull request with a structured description. CX Codex +1 ★ 372repo stars aws-drawio-architecture-diagrams aws-drawio-architecture-diagrams — a Claude Code skill that produces AWS architecture .drawio files using the official aws4 icon library. Describe your infrastructure and the agent writes valid XML ready to open in diagrams.net. CX Codex +1 ★ 372repo stars devkit.java.code-review devkit.java.code-review reviews Java enterprise code in Spring Boot projects. Checks security against OWASP Top 10, inspects architecture and catches performance bottlenecks. CX Codex +1 ★ 372repo stars

Project sponsors

Companies that keep this analytics open