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

@nest-yalc-2/api-strategy

v2.2.17

Published

<div align="center"> <h1>@nest-yalc-2/api-strategy</h1> <p><em>Core enterprise module for the @nest-yalc-2/api-strategy integration within the Ferrox/YALC ecosystem.</em></p>

Readme

npm version License

🚀 Installation

npm install @nest-yalc-2/api-strategy
# or
yarn add @nest-yalc-2/api-strategy
# or
pnpm add @nest-yalc-2/api-strategy

API Strategy, Multi-Protocol Adapters & Contract Versioning

The @nestjs-yalc/api-strategy package enforces standardized API design paradigms across REST, GraphQL, and Messaging protocols. It provides multi-protocol controller abstractions, automated URI versioning strategies, uniform response payload wrapping, and content-negotiation adapters.


1. What It Is & Architectural Purpose

In complex microservice ecosystems, frontends and third-party integrations interact with backend services across multiple protocols (REST endpoints, GraphQL queries/mutations, gRPC calls, and Kafka/RabbitMQ events). Without a unified API strategy, response formats become fragmented, error payloads vary per protocol, and breaking API changes disrupt client compatibility.

@nestjs-yalc/api-strategy provides a cohesive architectural abstraction layer. It ensures that regardless of whether a controller method is invoked via HTTP GET, GraphQL Query, or AMQP Message, the incoming DTO validation, context propagation, error mapping, and response envelopes follow identical enterprise standards.

                               ┌─────────────────────────────┐
                               │  @nestjs-yalc/api-strategy  │
                               └──────────────┬──────────────┘
                                              │
           ┌──────────────────────────────────┼──────────────────────────────────┐
           │                                  │                                  │
           ▼                                  ▼                                  ▼
┌─────────────────────┐            ┌─────────────────────┐            ┌─────────────────────┐
│  REST API Adapter   │            │ GraphQL API Adapter │            │  Event API Adapter  │
│  (/api/v1/users)    │            │ (Queries/Mutations) │            │ (Kafka / RabbitMQ)  │
└─────────────────────┘            └─────────────────────┘            └─────────────────────┘

2. What It Does & Key Capabilities

  • Unified Response Envelopes: Wraps all API responses in standardized { statusCode, success, data, errors, meta } payloads.
  • URI & Header Versioning: Provides @ApiVersion('v1') decorators supporting URI path versioning (/v1/...), header versioning (x-api-version), and media-type negotiation.
  • Multi-Protocol Controller Decorators: Provides @YalcController() and @YalcResolver() decorators that automatically attach correlation context and rate-limiting rules.
  • Pagination & Sorting Normalization: Standardizes request DTO contracts for limit/page offset and cursor-based pagination parameters.

3. How It Works Under the Hood

Request Pipeline Sequence

sequenceDiagram
    autonumber
    participant Client as Client App
    participant Strategy as ApiStrategyInterceptor
    participant Controller as ApiController
    participant Transformer as ResponseEnvelopeTransformer
    participant Out as Standard Response

    Client->>Strategy: Incoming Request (REST / GraphQL / Event)
    Strategy->>Strategy: Extract API Version & Request Context
    Strategy->>Controller: Route to Target Method Handler
    Controller->>Strategy: Return Domain Entity / DTO
    Strategy->>Transformer: Transform to Standard Envelope Structure
    Transformer->>Out: Return { success: true, data: [...], meta: {...} }
    Out-->>Client: Delivery across Transport Channel

4. Why It Was Designed This Way

| Metric / Scenario | Standard NestJS Rest | @nestjs-yalc/api-strategy | | :--- | :--- | :--- | | Response Uniformity | Controllers return raw arrays or plain objects inconsistently. | Every response is wrapped in a type-safe { success, data, meta } envelope. | | Protocol Parity | REST and GraphQL controllers require duplicate mapping logic. | Shared domain handler logic across REST, GraphQL, and RPC transports. | | API Deprecation | Hardcoded route strings break when upgrading API major versions. | Automated path/header version resolution with @ApiVersion(). |


5. Practical Usage Guide & Extended Code Examples

5.1 Standard REST Controller with Unified Response Envelope

import { Controller, Get, Param, Query } from '@nestjs/common';
import { ApiVersion, YalcController, ResponseEnvelope } from '@nestjs-yalc/api-strategy';
import { UserService } from './user.service';
import { UserDto } from './user.dto';

@YalcController({ path: 'users', version: '1' })
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get(':id')
  @ApiVersion('1')
  async getUserById(@Param('id') id: string): Promise<ResponseEnvelope<UserDto>> {
    const user = await this.userService.findById(id);
    return ResponseEnvelope.success(user, { cached: true });
  }
}

5.2 Multi-Protocol Service Handler Example

import { Injectable } from '@nestjs/common';
import { BaseApiStrategyService, PaginationDto } from '@nestjs-yalc/api-strategy';
import { UserEntity } from './user.entity';

@Injectable()
export class UserApiStrategyService extends BaseApiStrategyService<UserEntity> {
  async fetchPaginatedUsers(pagination: PaginationDto) {
    const [data, total] = await this.repository.findAndCount({
      skip: pagination.skip,
      take: pagination.take,
    });

    return this.createPaginatedResponse(data, total, pagination);
  }
}

6. Anti-Patterns: How NOT to Use It

[!CAUTION] Anti-Pattern 1: Returning Naked Objects in Controllers Bypassing the ResponseEnvelope wrapper by returning raw database entities exposes internal DB schemas directly to clients and breaks client SDK deserializers.

// ❌ WRONG: Naked entity return
@Get()
async getUsers() { return this.userRepository.find(); }

// ✅ CORRECT: Wrapped in ResponseEnvelope
@Get()
async getUsers() {
  const users = await this.userRepository.find();
  return ResponseEnvelope.success(users);
}

7. Pro-Tips & Best Practices

[!TIP] Pro-Tip 1: Automated Swagger Schema Generation When using @YalcController(), OpenApi schema documentation is automatically generated for both successful payload envelopes and standardized error models.


🔗 Cross-References

To see how this module integrates with the rest of the Ferrox architecture, refer to the following documentation:


📚 Ecosystem Documentation

This module is a core component of the Ferrox enterprise microservice architecture.

👉 Read the Full Documentation on Ferrox-Rust.dev