open-index/open-npm huggingface dataset:
npm package: @softkit/exceptions
Description: This library provides a set of general exceptions and interceptors for exceptions to follow the same structure based on [RFC7807](https://www.rfc-editor.org/rfc/rfc7807#section-3.1)
Latest version: 0.1.7

# Exceptions Library 

This library provides a set of general exceptions and interceptors for exceptions to follow the same structure based on [RFC7807](https://www.rfc-editor.org/rfc/rfc7807#section-3.1)

It can be used outside Softkit projects

## Why we need it all? 

- To have a unified way to handle exceptions
- To have ability to document exceptions properly in swagger
- To have a unified way to handle exceptions on client side
- To have a unified way to handle exceptions on server side and even proxy them to client side if you call internal service
- To have a unified way to handle exceptions in logs
- To have a unified way to understand what is a real exception and what is a business logic error. This allows to create an efficient and proactive support for customers.

## Installation

```bash
yarn add @softkit/exceptions
```

You can also use [@softkit/bootstrap](https://www.npmjs.com/package/@softkit/bootstrap) to bootstrap your app with all default interceptors and filters.

This library is also tight to [nestjs-i18n](https://www.npmjs.com/package/nestjs-i18n), this allows us to easily change default messaging for the library or if you are ok with what we have just use default (*only english is available*)


## Usage


### Default interceptors

- **AnyExceptionFilter** - will catch any exception and return http status 500
- **HttpExceptionFilter** - will catch any exception which is instance of AbstractHttpException and return http status from exception
- **ForbiddenExceptionFilter** - will catch NestJS ForbiddenException and return http status 403, but with our **RFC** format
- **NotFoundExceptionFilter** - will catch NestJS NotFoundException and return http status 404, but with our **RFC** format

### Available exceptions




### You can create your own exception it will be handled by default interceptor, and returned in a unified format. See ErrorResponse class. 

```typescript
import { AbstractHttpException } from '@softkit/exceptions';

export class YourException extends AbstractHttpException {
  constructor(rootCause?: unknown) {
    super(
      i18nString('exception.YOUR_EXCEPTION.TITLE'),
      i18nString('exception.YOUR_EXCEPTION.GENERAL_DETAIL'),
      HttpStatus.FORBIDDEN,
      undefined,
      rootCause,
    );
  }
}
```

### Override wording

To override the default titles and details, you can take a localisation `exception.json` file from this library and inject it to your project

Load it with nestjs-i18n and substitution will be done automatically

You can also package this file to your localisation library to distribute across your organisation.


```
exception.json file is packaged to this repo and need to referenced and loadded in your app

if you won't load it you will see default keys for i18n
```
npm package: @softkit/file-storage
Description: This library is a default practical implementation for working with file, to cover most application default needs and do not deep dive in a generalized AWS SDK API, that sometimes is hard to follow and use, even if you know what to do. Also, it generalize
Latest version: 0.5.0

# File Storage module

This library is a default practical implementation for working with file, to cover most application default needs and do not deep dive in a generalized AWS SDK API, that sometimes is hard to follow and use, even if you know what to do.
Also, it generalized in a way that can be used and extended for other cloud storage, but now contains implementation only for S3, using the latest API V3.

## Features

- It provides S3FileStorageModule
- Exposed S3 client
- And high-level file service
- Use of default AWS credentials chain
- Pre-sign URL generation for POST and PUT methods for upload, and GET method for download
- Multipart upload with start/stop/complete methods 

TBD: 

- Add default controller for file upload and download
- Add a storage repository for optionally storing file metadata
- Add a cron job for cleaning up unused files
- Add encryption for securely passing information from frontend and do not store and expose any S3 information 

## Installation

```bash
yarn add @softkit/file-storage
```

## Usage

### Import S3FileStorageModule 

```typescript

import { Module } from '@nestjs/common';
import { S3FileStorageModule } from '@softkit/file-storage';

@Module({
  imports: [
    S3FileStorageModule.forRoot(),
  ],
})
export class YourAppModule {}

```
Note: 

If you have AWS cli configured locally, it will use your local credentials
You can override credentials in code 


```typescript

import { Module } from '@nestjs/common';
import { S3FileStorageModule } from '@softkit/file-storage';

@Module({
  imports: [
    S3FileStorageModule.forRoot({
      credentials: {
          accessKeyId: 'test',
          secretAccessKey: 'test',
      }
    }),
  ],
})
export class YourAppModule {}

```

Or use forRootAsync if you want to inject some config

```typescript

@Module({
  imports: [
    S3FileStorageModule.forRootAsync({
      useFactory: async (config: SomeS3Config) => {
        return config;
      },
      inject: [SomeS3Config],
    }),
  ],
})
export class YourAppModule {}

```

Or simply set environment variables: 

```bash
AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
AWS_DEFAULT_REGION=us-west-2
```


## Testing 

You can use @softkit/test-utils module that allow to easily start localstack and test your code with it. 

startLocalstack function setting TEST_LOCALSTACK_MAIN_PORT env variable, and you can substitute it in your config file. 

```typescript
@Module({
  imports: [
    S3FileStorageModule.forRoot({
      credentials: {
        accessKeyId: 'test',
        secretAccessKey: 'test',
      },
      forcePathStyle: true,
      endpoint: `http://localhost:${process.env['TEST_LOCALSTACK_MAIN_PORT']}`,
      region: 'us-west-1',
    }),
  ],
})
export class FileUploadAppModule {}
```
npm package: @softkit/health-check
Description: This library provides a healthcheck endpoint for the application.
Latest version: 0.0.12

# Health Check Library

This library provides a healthcheck endpoint for the application.

It's useful for kubernetes and other containerized or any environments that need healthcheck to validate that app is functioning ok.

This module is tight to Softkit ecosystem and there is no point to use it outside.

## Installation

```bash
yarn add @softkit/health-check
```

## Usage in your main app module: 


- Import HealthCheckModule and register it in imports array
- Add HealthConfig to your RootConfig class
```typescript
import { HealthConfig } from '@softkit/healthcheck';

export default class RootConfig implements PlatformClientConfig {

  @Type(() => HealthConfig)
  @ValidateNested()
  public readonly health!: HealthConfig;

}
```
- Add health config to your .env.yaml file. (*Check health config to find default and available configs*)

```yaml
health:
  disk:
    enabled: true
  db:
    enabled: true
```

- That's it health endpoint will be available at `/health` path for use. *If you have a basePath configured it also will be applied to health endpoint.*
npm package: @softkit/healthcheck
Description: This library provides a healthcheck endpoint for the application.
Latest version: 0.0.5

# Health Check Library

This library provides a healthcheck endpoint for the application.

It's useful for kubernetes and other containerized or any environments that need healthcheck to validate that app is functioning ok.

This module is tight to Softkit ecosystem and there is no point to use it outside.

## Installation

```bash
yarn add @softkit/health-check
```

## Usage in your main app module: 


- Import HealthCheckModule and register it in imports array
- Add HealthConfig to your RootConfig class
```typescript
import { HealthConfig } from '@softkit/healthcheck';

export default class RootConfig implements PlatformClientConfig {

  @Type(() => HealthConfig)
  @ValidateNested()
  public readonly health!: HealthConfig;

}
```
- Add health config to your .env.yaml file. (*Check health config to find default and available configs*)

```yaml
health:
  disk:
    enabled: true
  db:
    enabled: true
```

- That's it health endpoint will be available at `/health` path for use. *If you have a basePath configured it also will be applied to health endpoint.*
npm package: @softkit/i18n
Description: This library is a simple wrapper based on [nestjs-i18n](https://nestjs-i18n.com/)
Latest version: 0.4.5

# i18n library wrapper

This library is a simple wrapper based on [nestjs-i18n](https://nestjs-i18n.com/)

### It has a few additions:

- We highly encourage to use it in all apps and libraries, even if you do support only one language. The reason is simple, you can have all possible strings that your customers may see in one place, and this is awesome. Also you will be able to easily share general files across your teams if you have more than one, and your customers will have an amazing experience on your platform. Also one day you will receive a request from manager saying either we are expanding to new market or give me a list of all strings that we have in our app, and you will be able to do it in a few minutes.
- it has a default config for i18n, to use in other apps and libraries (libraries usually can use this lib only for testing)
- default response body formatter for exceptions, to follow [RFC7807](https://www.rfc-editor.org/rfc/rfc7807#section-3.1) standard

## Installation

```bash
yarn add @softkit/i18n
```

## Setup

### Load module

```typescript
import { setupI18nModule } from '@softkit/i18n';

@Module({
  imports: [setupI18nModule(__dirname)],
})
export class YourAppModule {}
```

### Update your RootConfig class

```typescript
import { I18nConfig } from '@softkit/i18n';

export default class RootConfig {
  @Type(() => I18nConfig)
  @ValidateNested()
  // field name doesn't matter, it only affect how you will configure it in your .env.yaml file
  public readonly i18n!: I18nConfig;
}
```

### Update your .env.yaml file

[//]: # 'todo add more info about how to reference files from libraries'

Paths are relative to your app module file location

```yaml
i18:
  paths:
    - i18n/
    - ../../../libs/validation/src/lib/i18n/
    - ../../../libs/exceptions/src/lib/i18n/
```

#### nestjs-i18n has a great client for types generation. Example will generate types to generated folder, this is super useful to do not miss any property in your translations

```bash
nestjs-i18n generate-types -t json -p ./src/lib/i18n -o ./src/lib/generated/i18n.generated.ts -w
```

#### TIP: Create utils file to use in your app, to get i18n typesafe and easy to use

```typescript
import {
  i18nValidationMessage,
  i18nValidationMessageString,
} from '@softkit/i18n';
import { Path } from '@softkit/i18n/dist/types';
import { I18nTranslations } from '../generated/i18n.generated';

export function i18nString(key: Path<I18nTranslations>) {
  return i18nValidationMessageString<I18nTranslations>(key);
}

export function i18n(key: Path<I18nTranslations>, args?: unknown) {
  return i18nValidationMessage<I18nTranslations>(key, args);
}
```

`This will make code cleaner and easier to read, you won't need to include types everytime when you want to use i18n`
npm package: @softkit/logger
Description: This library is based on pino logger and provides an opinionated logger for Softkit ecosystem.
Latest version: 0.1.7

# Logger Library

This library is based on pino logger and provides an opinionated logger for Softkit ecosystem.

By default it logs finish request, with request id and time, and also logs all exceptions with stack trace.

In general it is a pain to fine and setup a proper logger for nestjs application.

We solved most configuration problems that we had with logging in our projects.

Also leverage the use of ClsService to have a proper request id in logs.

## Installation

```bash
yarn add @softkit/logger
```

## Usage

### Default interceptors

- **LoggingInterceptor** - it will log all incoming requests


### Default configuration

```typescript

import { setupLoggerModule } from '@softkit/logger';

@Module({
  imports: [
    setupLoggerModule(),
  ]
})
export class YourAppModule {}

```

### Update your root config class

```typescript

export class RootConfig {
  @Type(() => LoggerConfig)
  @ValidateNested()
  public readonly logger!: LoggerConfig;
}

```

### Update your config files

`.env.yaml` file

```yaml
logs:
#  useful for development as well
  colorize: true
#  info should be used for production in most cases, unless you want to debug something
  level: info
#  pretty print usually needed only for development, so must be changed in .env-${env}.yaml files for deployment
  prettyPrint: true
```
npm package: @softkit/persistence-api
Description: This module contains the API for the persistence layer. It defines the interfaces that the persistence layer must implement.
Latest version: 0.1.1

# persistence-api

This module contains the API for the persistence layer. It defines the interfaces that the persistence layer must implement.

The main purpose is to provide a common interface for the persistence layer, so that the business layer can be decoupled from the actual implementation of the persistence layer 
and we can easily switch between different implementations and even ORMs.
npm package: @softkit/platform-client
Description: This library provides a simple http client for the platform application.
Latest version: 0.0.7

# Platform Http Client Library

This library provides a simple http client for the platform application.

It's auto generated using openapi-generator.

## Installation

```bash
yarn add @softkit/platform-client
```
---

## Usage

### Add to your env.yml file

```yaml
platformClient:
  url: http://localhost:9999
  serviceName: platform
```
---

### Update your root.config.ts, it needs to implement the appropriate config interface 


```typescript
import { HttpClientConfig } from '@softkit/server-http-client';
import { PlatformClientConfig } from '@softkit/platform-client';

export default class RootConfig implements PlatformClientConfig {

  @Type(() => HttpClientConfig)
  @ValidateNested()
  public readonly platformClient!: HttpClientConfig;

}
```

### Import `PlatformClientModule` in your main module

---

### That's it, api clients will be available in your DI container, you can simply inject it in constructor

```typescript

import { RolesApi } from '@softkit/platform-client';

@Injectable()
export default class MyServiceThatNeedRolesApi {

  constructor(
    private readonly rolesApi: RolesApi,
  ) {}

}

```
npm package: @softkit/resource-plugin
Description: ### Install
Latest version: 0.7.2

# This resource plugin has generators for convenient development of new resources and their CRUD operations 

### Install

```bash
yarn add @softkit/resource-plugin
```

### Available generators 

- `resource` - generates a new resource with CRUD operations
- `service` - generates a new service for a resource
- `controller` - generates a new controller for a resource
- `app` - generates a new app for a resource
- `http-client` - generates a new http client for an app
- `i18n` - adding support for i18n, creates a new folder with translations and adds it to the config
- `lib` - generates a new lib for a resource, can add i18n and config

### Usage

[//]: # todo document base usage of generators


### Development 

#### Add new generator

```bash
nx generate @nx/plugin:generator ${GENERATOR_NAME} --project=resource-plugin
```

#### Test generator

```bash
nx generate @softkit/resource-plugin ${GENERATOR_NAME} --project=resource-plugin
```
npm package: @softkit/server-http-client
Description: This library provides an advanced http client for nestjs applications.
Latest version: 0.0.13

# Server Http Client

This library provides an advanced http client for nestjs applications.

It designed to be used to communicate with other nestjs applications or any other http services.

It requires to have [Axios](https://axios-http.com/docs/intro) installed, and it relies on it

---


## Features

- It has built-in configurable retry mechanism (linear, static or exponential)
- It has built-in configurable circuit breaker mechanism
- Circuit breaker using a local memory cache to store state of the circuit
- Circuit breaker and retry mechanism can be configured per request and can be configured together, but you need to have a clear understanding how system will behave when both are configured
- This libraries provides InternalProxyHttpExceptionFilter that will convert any exception to InternalProxyHttpException

  This is useful for internal communication between services, so if you call another service, and it returns any error it will be converted to InternalProxyHttpException and you can handle it if you want to, but in most cases if any of your internal service returns an error you should just return it to the client, as is. It simplifies error handling for communication between microservices. 
- It has built-in configurable timeout mechanism, you don't want to hang for 30 seconds waiting for response from the server.
- It relies on ClsService for auth token and request id propagation between services, so you don't need to worry about it, it will be done automatically for you.  

Note: 

You quite rarely need to use this library directly, it is used by code generator, to create automatically generated http clients for your apps and libraries.

---

## Installation

```bash
yarn add @softkit/server-http-client
```

---

## Create http client


```typescript

@Module({

  providers: [
    {
      provide: 'AXIOS',
      useFactory: (cls: ClsService<UserRequestClsStore>) => {
        return createAxiosInstance(cls, {
          url: 'http://localhost:54345',
          timeout: 1000,
          serviceName: 'sample',
        });
      },
      inject: [ClsService],
    },
  ],
  imports: [ClsModule],
})
export class YourAppModule {}
```

## Inject and use 

```typescript

@Controller('sample')
export class SampleController {
  constructor(@Inject('AXIOS') private readonly axios: AxiosInstance) {}
}
```
npm package: @softkit/service-api
Description: This library has some useful utilities for @softkit/typeorm library, that expose useful base services to use in your application.
Latest version: 0.1.0

# Typeorm Service Library

This library has some useful utilities for @softkit/typeorm library, that expose useful base services to use in your application.

This library is also throwing standard exceptions from @softkit/exceptions library. So interceptors can handle everything properly.

## Installation

```bash
yarn add @softkit/service-api
```

## Examples:

- `BaseEntityService` - it has basic methods for creating, finding, updating, archiving, deleting entities. Simple CRUD based operations, and you can also extend it with your own methods.

```typescript
import { Injectable } from '@nestjs/common';
import { Transactional } from 'typeorm-transactional';
import { CustomUserRoleRepository } from '../../repositories';
import { BaseEntityService } from '@softkit/service-api';
import { IsNull } from 'typeorm';

@Injectable()
export class CustomUserRoleService extends BaseEntityService<CustomUserRole, CustomUserRoleRepository> {
  constructor(repository: CustomUserRoleRepository) {
    super(repository);
  }

  @Transactional()
  async findDefaultRole() {
    return await this.repository.findOne({
      where: {
        roleType: RoleType.REGULAR_USER,
        tenantId: IsNull(),
      },
    });
  }
}
```

- `BaseTenantEntityService` - it has basic methods for creating, finding, updating, archiving, deleting tenant base entities. Simple CRUD based operations, and you can also extend it with your own methods.

```typescript
@Injectable()
export class CustomUserRoleTenantService extends BaseTenantEntityService<CustomUserRole, CustomUserRoleTenantRepository> {
  constructor(repository: CustomUserRoleTenantRepository) {
    super(repository);
  }
}
```

Tip:

Each of these services has additional parameter in generics, after repository type, that is used for excluding auto generated types,
to keep service type safe and do not annoy you with type errors.

Example (_This will exclude 5 fields from base methods and types, because it will be populated by subscribers_):

```typescript
@Injectable()
export class CustomUserRoleTenantService extends BaseTenantEntityService<CustomUserRole, CustomUserRoleTenantRepository, Pick<CustomUserRole, 'id' | 'createdAt' | 'updatedAt' | 'deletedAt' | 'userId'>> {
  constructor(repository: CustomUserRoleTenantRepository) {
    super(repository);
  }
}
```