2.0.4 • Published 4 days ago

@scandinavia/nestjs-libs v2.0.4

Weekly downloads
-
License
MIT
Repository
-
Last release
4 days ago

nestjs-sc-libs

What does this package do?

This package is a collection of many utilities that help building REST applications rapidly.

What does this package contain?

  • MongoDb
    • Transaction Helper
    • Exception Filter
    • Search Extension
    • Softdelete Plugin
  • JWT Exception Filter
  • Coded Exception
  • CASL Foribdden Exception Filter
  • MongoId Parse Pipes
  • File Uploader
  • Global Chaching Interceptor

Transaction Helper

This plugin helper in managing transactions using cls-hooked and using decorators for transactional methods.

For usage, first intialize before anything else in your main.ts file:

import { initi alizeTransactionalContext } from "@scandinavia/nestjs-libs";
initializeTransactionalContext();

Then when intializing MongooseModule, remember to use attach these plugins as global plugins, and to set a connectionName

MongooseModule.forRootAsync({
    inject: [ConfigService],
    connectionName: 'default',
    useFactory: async (
        configService: ConfigService,
    ): Promise<MongooseModuleOptions> => ({
        uri: configService.get('MONGO_URI'),
        replicaSet: configService.get('REPLICA_SET'),
        connectionFactory: (connection: Connection) => {
          connection.plugin(mongooseTrxPlugin);
          connection.plugin(accessibleRecordsPlugin);
          return connection;
        },
    }),
}),

Remember then to setup the connection hooks for that TransactionHelper, the quickest way is to do it in the module constructor:

import { TransactionConnectionManager } from "@scandinavia/nestjs-libs";

export class AppModule {
  constructor(@InjectConnection("default") private appConnection: Connection) {
    appConnection.name = "default";
    TransactionConnectionManager.setConnection(
      this.appConnection,
      this.appConnection.name
    );
  }
}

In order to use transactions, do the following in a service method:

import { Transactional, Propagation } from "@scandinavia/nestjs-libs";

export class Service {
  @Transactional({ propagation: Propagation.Mandatory })
  save() {
    // code that uses any mongoose model
  }
}

There are many Propagation types for configuring transactions, these are:

MANDATORY: Support a current transaction, throw an exception if none exists.

NEVER: Execute non-transactionally, throw an exception if a transaction exists.

NOT_SUPPORTED: Execute non-transactionally, suspend the current transaction if one exists.

REQUIRED: Support a current transaction, create a new one if none exists.

SUPPORTS: Support a current transaction, execute non-transactionally if none exists.

Coded Exceptions

Provide functions to quickly generate Exception classes for usage within the app.

export class AccountDisabledException extends GenCodedException(
  HttpStatus.BAD_REQUEST,
  "ACCOUNT_DISABLED"
) {}

export class AdminNotFoundException extends ResourceNotFoundException(
  "ADMIN"
) {}

Exception Filters

Use all filters as global filters.

The CaslForbiddenExceptionFilter catches any forbidden error from CASL and sends an 403 response.

The CodedExceptionFilter catches CodedExceptions and formats the response accordingly.

The MongoExceptionFilter catches MongoErrors thrown from the MongoDb driver and formats the response accordingly.

Validation and Serialization

First things first, initialize the app to use the validation pipeline, and the serialization interceptor:

app.useGlobalPipes(
  new ValidationPipe({
    transform: true,
    whitelist: true,
  })
);
app.useGlobalInterceptors(
  new CustomClassSerializerInterceptor(app.get(Reflector))
);

ValidationPipe is used to validate any DTO classes annotated with class-validator.

CustomClassSerializerInterceptor is used to serialize any response DTOs returned from a controller method using class-transformer to convert results correctly.

Validation Example:

export class CreateCompanyDto {
  @IsString()
  name: string;

  @ValidateNested()
  @Type(() => CreateUserDtoWithoutCompany)
  mainUser: CreateUserDtoWithoutCompany;
}

Response DTO example:

import { BaseResponseDto } from "@scandinavia/nestjs-libs";
import { Exclude, Expose, Type } from "class-transformer";

@Exclude()
export class UserDto extends BaseResponseDto {
  @Expose()
  firstName: string;
  @Expose()
  lastName: string;
  @Expose()
  email: string;
  @Expose()
  phone: string;
  @Expose()
  activatedAt: Date;
  @Expose()
  type: UserType;
  @Expose()
  @Type(() => CompanyDto)
  company: CompanyDto;
}

Don't forget to decorate the class with @Exclude and decorate all properties with @Expose, also response DTOs should extend BaseResponseDto class.

Remember to transform a plain object to the appropriate DTO before returning it in a controller.

@Get()
async getItem() {
    const item = await this.service.getItem();
    return plainToInstance(ItemResponseDto, item.toObject());
    // always use toObject() on mongoose documents
}

If you want a controller to return a plain object (non DTO), annotate the controller method like so:

@CustomInterceptorIgnore()
returnPlainObj() {
    return {x: 4};
}

Search Plugin

This plugin has many utilties that help make its magic work, it works with casl, class-transformer, class-validator, and mongoose.

First things first, initialize the app to use the validation pipeline, and the serialization interceptor just like in the above section.

Model Definition

Starting with model definition, make your class model either extend StampedCollectionProperties or BaseCollectionProperties, Stamped one includes createdAt and updatedAt fields.

Then decorate properties with SearchKey decorator:

export class Device extends StampedCollectionProperties {
  @SearchKey({ sortable: true, filterable: true, includeInMinified: true })
  @Prop({ required: true })
  name: string;

  @SearchKey({ sortable: true, filterable: true })
  @Prop({ required: true })
  imei: string;

  @Prop({
    ref: SchemaNames.COMPANY,
    type: SchemaTypes.ObjectId,
    required: true,
  })
  @SearchKey({
    sortable: true,
    filterable: true,
    isId: true,
    pathClass: () => Company,
  })
  company: Types.ObjectId | CompanyDocument;
}

filterable: allows filtering on that field.

sortable: allows filtering on that field.

isId: set it to true when dealing with fields that store ObjectId

pathClass: a function that returns the class of that object once it is populated

includeInMinified: return this proprty when requesting a minified query, more on that later.

Controller

Use the SearchDto and the SearchPipe within controllers:

@Get()
async getByCriteria(@Query(new SearchPipe(Device)) searchdto: SearchDto) {
    let abilities;
    // code to assign abilities a value, these are an array of casl rules.
    return this.deviceService.getByCriteria(searchDto.transformedResult, abilities);
}

Use the DocAggregator class to execute the query within the service:

async getByCriteria(searchDto: TransformedSearchDto, abilities) {
    // Pass path description to DocAggregator
    // $ROOT$ is a special path which here points to the Device base document
    // LookupFlags are used when accessing refs, when SINGLE is used, the value of company is a single document, else it's an array.
    // When REQUIRED is used, it works just like an inner-join, else the query works just like a left-join.
    return new DocAggregator(this.deviceModel, DeviceDto).aggregateAndCount(searchDto, {
        $ROOT$: {
            accessibility: this.deviceModel.accessibleBy(abilities).getQuery()
        },
        company: {
            flags: LookupFlags.SINGLE | LookupFlags.REQUIRED
        }
    });
}

The query pipeline is then composed automatically and executed with Count query to fill up pagination info.

Filtering and Sorting

filter within the SearchDto should be passed as a json string which works as a mongo filter and supports some operators.

example: {"id":"618cca7a88d510dc802d3a27"}

sort should be multiple fields seperated with ; use hyphens before a property for descending sorting.

example: company;-createdAt

the above example sorts by company ascending, then by createdAt descending.

passing minfied=true within the query parameters returns only fields annotated with includeInMinfied. This is useful to populate Dropdown Menus with basic information only (id,name) without creating a seperate endpoint to execute such logic.

Uploader

This module uses @nestjs/serve-static, multer, and sharp.

It is used to upload files to be stored either locally on the server, or on AWS S3 cloud storage.

It also provided many validation tools and ways to define transformations on uploaded files like generating thumbnails for uploaded images.

First, initialize in the AppModule within imports:

UploadModule.forRoot({
  storageType: UploadModuleStorageType.LOCAL,
  localStorageOptions: {
    storageDir: "files",
    publicServePath: "assets",
  },
});

According to the above code snippet, any uploaded files will be stored under ./files/public or ./files/private directories. Public files are statically served, while private files are not. Public files will be accessible directly using /assets

As for controller code, where is an example:

@Post()
@UseInterceptors(
    UploadInterceptor({
        logo: {
          destination: 'logos',
          maxNumFiles: 1,
          minNumFiles: 1,
          isPrivate: false,
          pipeline: new ImagePipeline()
            .persist()
            .validate({
              aspectRatio: {
                min: 1,
                max: 1,
              },
            })
            .thumb('small', { width: 100, height: 100 }),
        },
      },
      {
        allowedMimeTypes: [MimeTypes.image],
      },
    ),
)
async upload(@UploadedSingleFileByField('logo') logo: UploadedFile) {
    const smallThumbnail: UploadedFile = logo.processFiles['small'];
    return logo;
}

Caching

Define the CustomCacheInterceptor globally in the app.module.ts file

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: CustomCacheInterceptor,
    },
  ],
})
export class AppModule {}

In order to cache a certain endpoint, use @CacheThisEndpoint decorator in GET controllers.

2.0.4

4 days ago

2.0.3

9 months ago

2.0.2

9 months ago

2.0.1

9 months ago

2.0.0

10 months ago

1.9.93

10 months ago

1.9.92

1 year ago

1.9.91

1 year ago

1.9.9

1 year ago

1.9.86

1 year ago

1.9.85

1 year ago

1.9.84

2 years ago

1.9.83

2 years ago

1.9.82

2 years ago

1.9.81

2 years ago

1.9.80

2 years ago

1.9.79

2 years ago

1.9.78

2 years ago

1.9.77

2 years ago

1.9.76

2 years ago

1.9.75

2 years ago

1.9.74

2 years ago

1.9.73

2 years ago

1.9.66

2 years ago

1.9.65

2 years ago

1.9.64

2 years ago

1.9.63

2 years ago

1.9.62

2 years ago

1.9.61

2 years ago

1.9.72

2 years ago

1.9.71

2 years ago

1.9.70

2 years ago

1.9.49

2 years ago

1.9.48

2 years ago

1.9.47

2 years ago

1.9.46

2 years ago

1.9.45

2 years ago

1.9.44

2 years ago

1.9.60

2 years ago

1.9.58

2 years ago

1.9.56

2 years ago

1.9.55

2 years ago

1.9.54

2 years ago

1.9.53

2 years ago

1.9.52

2 years ago

1.9.51

2 years ago

1.9.50

2 years ago

1.9.29

2 years ago

1.9.27

2 years ago

1.9.26

2 years ago

1.9.25

2 years ago

1.9.24

2 years ago

1.9.23

2 years ago

1.9.22

2 years ago

1.9.21

2 years ago

1.9.43

2 years ago

1.9.42

2 years ago

1.9.41

2 years ago

1.9.40

2 years ago

1.9.39

2 years ago

1.9.38

2 years ago

1.9.37

2 years ago

1.9.36

2 years ago

1.9.35

2 years ago

1.9.33

2 years ago

1.9.32

2 years ago

1.9.31

2 years ago

1.9.30

2 years ago

1.9.20

2 years ago

1.9.19

2 years ago

1.9.18

2 years ago

1.9.17

2 years ago

1.9.16

2 years ago

1.9.15

2 years ago

1.9.14

2 years ago

1.9.13

2 years ago

1.9.12

2 years ago

1.9.11

2 years ago

1.9.1

2 years ago

1.9.0

2 years ago

1.8.85

2 years ago

1.8.86

2 years ago

1.8.87

2 years ago

1.8.88

2 years ago

1.8.89

2 years ago

1.8.90

2 years ago

1.8.91

2 years ago

1.8.92

2 years ago

1.8.75

2 years ago

1.8.76

2 years ago

1.8.80

2 years ago

1.8.81

2 years ago

1.8.82

2 years ago

1.8.83

2 years ago

1.8.84

2 years ago

1.8.66

2 years ago

1.8.68

2 years ago

1.8.69

2 years ago

1.8.70

2 years ago

1.8.71

2 years ago

1.8.72

2 years ago

1.8.73

2 years ago

1.8.74

2 years ago

1.2.0

2 years ago

1.6.4

2 years ago

1.2.8

2 years ago

1.6.3

2 years ago

1.2.7

2 years ago

1.6.2

2 years ago

1.2.6

2 years ago

1.6.1

2 years ago

1.2.5

2 years ago

1.6.0

2 years ago

1.2.4

2 years ago

1.8.60

2 years ago

1.2.3

2 years ago

1.8.61

2 years ago

1.8.62

2 years ago

1.2.1

2 years ago

1.8.63

2 years ago

1.8.64

2 years ago

1.8.65

2 years ago

1.7.9

2 years ago

1.7.8

2 years ago

1.7.7

2 years ago

1.7.6

2 years ago

1.7.5

2 years ago

1.3.9

2 years ago

1.7.4

2 years ago

1.3.8

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.5.5

2 years ago

1.1.9

2 years ago

1.5.4

2 years ago

1.5.3

2 years ago

1.1.7

2 years ago

1.5.2

2 years ago

1.1.6

2 years ago

1.5.1

2 years ago

1.1.5

2 years ago

1.5.0

2 years ago

1.1.4

2 years ago

1.1.3

2 years ago

1.8.40

2 years ago

1.1.2

2 years ago

1.8.41

2 years ago

1.8.42

2 years ago

1.8.43

2 years ago

1.8.44

2 years ago

1.8.45

2 years ago

1.8.46

2 years ago

1.8.47

2 years ago

1.8.48

2 years ago

1.8.49

2 years ago

1.8.50

2 years ago

1.8.51

2 years ago

1.8.52

2 years ago

1.8.53

2 years ago

1.8.54

2 years ago

1.8.55

2 years ago

1.6.9

2 years ago

1.8.56

2 years ago

1.6.8

2 years ago

1.8.57

2 years ago

1.8.58

2 years ago

1.6.6

2 years ago

1.8.59

2 years ago

1.6.5

2 years ago

1.2.9

2 years ago

1.8.2

2 years ago

1.4.6

2 years ago

1.8.1

2 years ago

1.4.5

2 years ago

1.0.9

2 years ago

1.8.0

2 years ago

1.4.4

2 years ago

1.0.7

2 years ago

1.4.2

2 years ago

1.0.6

2 years ago

1.4.1

2 years ago

1.0.5

2 years ago

1.4.0

2 years ago

1.8.31

2 years ago

1.8.32

2 years ago

1.8.33

2 years ago

1.8.34

2 years ago

1.5.9

2 years ago

1.8.35

2 years ago

1.5.8

2 years ago

1.8.36

2 years ago

1.5.7

2 years ago

1.8.37

2 years ago

1.5.6

2 years ago

1.8.38

2 years ago

1.8.39

2 years ago

1.7.3

2 years ago

1.3.7

2 years ago

1.7.2

2 years ago

1.3.6

2 years ago

1.7.1

2 years ago

1.7.0

2 years ago

1.3.4

2 years ago

1.3.3

2 years ago

1.3.2

2 years ago

1.3.1

2 years ago

1.3.0

2 years ago

1.4.9

2 years ago

1.4.8

2 years ago

1.8.3

2 years ago

1.4.7

2 years ago

1.0.4

2 years ago