open-index/open-npm huggingface dataset:
npm package: @getlarge/nestjs-tools-amqp-transport
Description: Custom Nest Transport classes for AMQP
Author: Edouard Maleix
Latest version: 0.7.1

# AMQP Transport

[![npm][npm-image]][npm-url]

[npm-image]: https://img.shields.io/npm/v/@getlarge/nestjs-tools-amqp-transport.svg?style=flat
[npm-url]: https://npmjs.org/package/@getlarge/nestjs-tools-amqp-transport

A custom AMQP strategy for Nest microservice transport, which extends NestJS AMQP [producer](https://github.com/nestjs/nest/blob/master/packages/microservices/client/client-rmq.ts) and [consumer](https://github.com/nestjs/nest/blob/master/packages/microservices/server/server-rmq.ts) by adding support for:

- exchanges
- reply queue assertion

By enabling exchanges you can broadcast messages to multiple queues, and by asserting reply queue you can ensure that reply queue with static name exists.

## Installation

```bash
npm install --save @getlarge/nestjs-tools-amqp-transport
```

## Example

The integration tests contain an [example consumer](./test/dummy-consumer.controller.mock.ts) and [example producer](./test/dummy-producer.service.mock.ts) that demonstrate how to use this library.
npm package: @getlarge/nestjs-tools-async-local-storage
Description: Node Async Hooks wrapper to store request context
Author: Edouard Maleix
Latest version: 0.3.1

# Async Local Storage

[![npm][npm-image]][npm-url]

[npm-image]: https://img.shields.io/npm/v/@getlarge/nestjs-tools-async-local-storage.svg?style=flat
[npm-url]: https://npmjs.org/package/@getlarge/nestjs-tools-async-local-storage

## Installation

```bash
npm install --save @getlarge/nestjs-tools-async-local-storage
```

## Usage

```ts
import assert from 'assert';
import { AsyncLocalStorage } from 'async_hooks';

// to provide type safety for the store map
declare module '@getlarge/nestjs-tools-async-local-storage' {
  interface RequestContext {
    type?: string;
  }
  interface ContextStoreProperties {
    id: number;
    username: string;
    profilePicture: string;
    name: string;
  }
}

import { AsyncLocalStorageService } from '@getlarge/nestjs-tools-async-local-storage';

const service = new AsyncLocalStorageService(new AsyncLocalStorage());

assert.throws(() => service.store.set('id', 1), new TypeError("Cannot read properties of undefined (reading 'set')"));
assert.throws(() => service.set('id', 1), new Error("Store is not initialized. Call 'enterWith' or 'run' first."));

service.enterWith(new Map());

// access store map directly
service.store.set('id', 1);
const id = service.store.get('id');
assert(typeof id === 'number');

// access store map via service which extends Map
service.set('username', 'john');
assert(typeof service.get('username') === 'string');

service.requestContext = { type: 'http' };
const requestContext = service.requestContext;
assert(typeof requestContext.type === 'string');

service.delete('username');
```

<!-- TODO: add app usage example -->
npm package: @getlarge/nestjs-tools-cluster
Description: Cluster and workers manager
Author: Edouard Maleix
Latest version: 0.15.7

# Cluster

[![npm][npm-image]][npm-url]

[npm-image]: https://img.shields.io/npm/v/@getlarge/nestjs-tools-cluster.svg?style=flat
[npm-url]: https://npmjs.org/package/@getlarge/nestjs-tools-cluster

This package provides a simple way to clusterize a NestJS application.
The `ClusterService` class is a wrapper around the native `cluster` module and provides a simple API to manage the workers' lifecycle.

## Installation

```bash
npm install --save @getlarge/nestjs-tools-cluster
```

## Example

```ts
import { Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { ClusterService, ClusterServiceConfig } from '@getlarge/cluster-service';
import { cpus } from 'node:os';

import { AppModule } from './app/app.module';

const GLOBAL_API_PREFIX = 'api';
const DEFAULT_PORT = 3000;
const CLUSTER_MODE = process.env.CLUSTER_MODE === 'true';
const MAX_WORKERS = +process.env.MAX_WORKERS || cpus().length;

async function bootstrap(
  opts: { workerId?: number } = {},
  disconnect: () => void = () => process.exit(1),
): Promise<void> {
  /**
   * This is a global variable that will be used to identify the worker id
   * in the application. This is useful for debugging purposes.
   */
  globalThis.__WORKER_ID__ = opts.workerId;

  try {
    const app = await NestFactory.create<NestFastifyApplication>(
      AppModule,
      new FastifyAdapter({
        trustProxy: true,
        bodyLimit: +process.env.MAX_PAYLOAD_SIZE || 1048576,
      }),
      { bufferLogs: true, abortOnError: false },
    );
    app.setGlobalPrefix(GLOBAL_API_PREFIX);
    const configService = app.get(ConfigService);
    const port = configService.get('PORT', { infer: true }) ?? DEFAULT_PORT;

    await app.listen(port, '0.0.0.0', () => {
      Logger.log(`Listening at http://localhost:${port}/${GLOBAL_API_PREFIX}`);
    });
  } catch (error) {
    Logger.error(error);
    disconnect();
  }
}

if (CLUSTER_MODE) {
  const clusterConfig: ClusterServiceConfig = {
    workers: MAX_WORKERS,
    delay: 2000,
    grace: 1000,
  };

  const clusterService = new ClusterService(clusterConfig);
  clusterService.clusterize(bootstrap).catch((e) => {
    clusterService.logger.error(e);
    process.exit(1);
  });
} else {
  void bootstrap({}, () => {
    process.exit(1);
  });
}
```

## Building

Run `nx build nestjs-tools-cluster` to build the library.

## Running unit tests

Run `nx test nestjs-tools-cluster` to execute the unit tests via [Jest](https://jestjs.io).
npm package: @getlarge/nestjs-tools-eslint-rules
Description: ESLint rules for NestJS applications
Author: Edouard Maleix
Latest version: 0.1.0

# eslint-rules

[![npm][npm-image]][npm-url]

[npm-image]: https://img.shields.io/npm/v/@getlarge/nestjs-tools-eslint-rules.svg?style=flat
[npm-url]: https://npmjs.org/package/@getlarge/nestjs-tools-eslint-rules

This set of ESLint rules is provided to enforce a consistent patterns and practices across all NestJS projects.

## Installation

```bash
npm install --save @getlarge/nestjs-tools-eslint-rules
```

## Usage

### return-class-instance

This rule enforces that all public Service methods return a class instance of the same return type.
The purpose of this rule is to ensure you return class instances instead of plain objects, which is essentials when using the [`ClassSerializerInterceptor`](https://docs.nestjs.com/techniques/serialization#class-serializer-interceptor).

```json
{
  "rules": {
    "@getlarge/nestjs-tools-eslint-rules/return-class-instance": "error"
  }
}
```
npm package: @getlarge/nestjs-tools-lock
Description: A distributed lock manager for NestJS
Author: Edouard Maleix
Latest version: 1.1.1

# Lock

[![npm][npm-image]][npm-url]

[npm-image]: https://img.shields.io/npm/v/@getlarge/nestjs-tools-lock.svg?style=flat
[npm-url]: https://npmjs.org/package/@getlarge/nestjs-tools-lock

The Lock Service produce distributed locks to prevent duplicated/conflicted actions to be executed in a distributed environment.
It is based on [Redlock](https://www.npmjs.com/package/redlock) module.

## Installation

```bash
npm install --save @getlarge/nestjs-tools-lock
```

## Usage

### Inside a CronJob service

```ts
import { LockService } from '@getlarge/nestjs-tools-lock';
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';

@Injectable()
export class TasksService implements OnModuleDestroy {
  constructor(private lockService: LockService) {}

  onModuleDestroy() {
    this.lockService.close();
  }

  // using returned unlock function
  @Cron('*/10 * * * * *')
  async doThis(): Promise<void> {
    const lockKey = 'doThis';
    const { unlock } = await this.lockService.lock(lockKey, 2000);
    if (typeof unlock !== 'function') {
      return;
    }
    unlock();
  }

  // using lock id
  @Cron('*/10 * * * * *')
  async doThat(): Promise<void> {
    const lockKey = 'doThat';
    await this.lockService.optimist(lockKey, 2000);
    const { lockId } = await this.lockService.lock(lockKey, 2000);
    this.lockService.unlock(lockKey, lockId);
  }
}
```