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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@tsalliance/rest

v2.0.75

Published

This library adds validation and error handling to NestJS applications

Readme

Alliance REST Library

This library basically adds validation and error handling to NestJS applications. However, the package also offers some bonus features that are explained below. For you to successfully use the package you have to understand the basics of NestJS and the basic concepts of typeorm, like the repository structure.

Installation

npm install @tsalliance/rest

Permissions

This package offers some tools to limit access to certain endpoints (@CanAccess()). This allows to define permissions on properties in your Entities (@CanRead()). You can either allow reading properties, forbid access completely or restrict to just certain types of requests by making authentication required or by setting permissions. Both decorator types work the same. For all use cases, this can look similar to the following examples:

// Using @CanAccess() on Controller routes
@Controller('invite')
export class InviteController {
    constructor(private readonly inviteService: InviteService) {}

    @Post()
    @CanAccess(PermissionCatalog.INVITES_WRITE)
    public create(@Body() createInviteDto: CreateInviteDto, @Authentication() authentication: RestAccount) {
        return this.inviteService.create(createInviteDto, authentication);
    }

    @Get(':id')
    public findOne(@Param('id') id: string) {
        return this.inviteService.findById(id);
    }

    @Put(':id')
    @CanAccess(PermissionCatalog.INVITES_WRITE)
    public update(@Param('id') id: string, @Body() updateInviteDto: UpdateInviteDto) {
        return this.inviteService.update(id, updateInviteDto);
    }

    @Delete(':id')
    @CanAccess(PermissionCatalog.INVITES_WRITE)
    public remove(@Param('id') id: string) {
        return this.inviteService.delete(id);
    }
}

// Using @CanRead() on Entity Properties
export class Invite {
    @PrimaryColumn("varchar", { length: 6 })
    public id: string;

    @CanRead([PermissionCatalog.INVITES_READ, PermissionCatalog.INVITES_WRITE])
    @Column({ nullable: false, default: 0 })
    public maxUses: number;

    @CanRead([PermissionCatalog.INVITES_READ, PermissionCatalog.INVITES_WRITE])
    @Column({ nullable: false, default: 0 })
    public uses: number;

    @CanRead([PermissionCatalog.INVITES_READ, PermissionCatalog.INVITES_WRITE])
    @CreateDateColumn()
    public createdAt: Date;

    @CanRead([PermissionCatalog.INVITES_READ, PermissionCatalog.INVITES_WRITE])
    @CreateDateColumn()
    public updatedAt: Date;

    @CanRead([PermissionCatalog.INVITES_READ, PermissionCatalog.INVITES_WRITE])
    @Column({ nullable: true })
    public expiresAt?: Date;
}

Using the RestRepository

The package provides some basic methods for typeorm's repository structure. To use all the methods you have to extend the RestRepository<T> class.

import { RestRepository } from "@tsalliance/rest"

@EntityRepository()
export class UserRepository extends RestRepository<T> {

}

Now you have access to following methods: | Method | Returned type | Description | | ------------------------------------------------ | ---------------------- | ----------------------------------------------------------------------------------------------- | | exists(options?: FindManyOptions<T>) | Promise<boolean> | This method counts entities in a table and if it count's more than 0 it evaluates to true | listAll(pageable: Pageable, options?: FindManyOptions<T>) | Promise<Page<T>> | This method retrieves a page from the database given the defined paging values | findById(id: string \| number \| Date \| ObjectID \| FindId, options?: FindManyOptions<T>) | Promise<T> | Better way of looking up database entries by their respective id. To search for an id with different column name you can pass an instance of FindId.

More will be added in the future

Validation

Using the validator as Object

The Validator class used to be a REQUEST scoped injectable. However this approach caused some performance issues which is why it must now be instantiated inside method calls. However there is still the possibility to inject the validator, but only as non-request-scoped injectable. Below is an example on how this looks in practice:

// Important part
import { Validator } from '@tsalliance/rest';

@Injectable()
export class ServiceClass {
    
    public doSomething() {
        const validator = new Validator();
        // Use validator to validate things...
        validator.text("message", data.title).alphaNum().minLen(3).maxLen(32).required().check();

        // and to throw errors on failure
        validator.throwErrors();
    }
}

Using the validator as Injectable

Additionally, the Validator can be used as an Injectable. To use it globally you can import the ValidatorModule in your app.module.ts. But keep in mind, that using the validator as an injectible, it becomes inefficient, because the Injectable that injects the validator becomes REQUEST scoped compulsorily in the nature of NestJS.

// Important part
import { Validator } from '@tsalliance/rest';

@Injectable()
export class ServiceClass {
    constructor(private validator: Validator)
    
    public doSomething() {
        // Use validator to validate things...
        this.validator.text("message", data.title).alphaNum().minLen(3).maxLen(32).required().check();

        // and to throw errors on failure
        this.validator.throwErrors();
    }
}

Validating required and optional values

The check() at the end of a line triggers the validation process and returns a boolean to check if something did successfully validate. Check the example below:

createHelloWorld(data: HelloWorldData) {
    // "message" represents the field name inside of the HelloWorldData object
    if(this.validator.text("message", data.title).alphaNum().minLen(3).maxLen(32).required().check()) {
        // Do something...
    }
    this.validator.throwErrors();
}

The example above show how to make fields inside of objects required. As you can see this is done by adding the required() rule to the chain. If you leave that rule out, the above example would still validate to false if the value (e.g.: data.title) is undefined or something similar. The only difference is, that when appending required(), internally an error is added to a list. So when calling this.validator.throwErrors() these collected errors are thrown. But leaving out the required rule does not throw such an ValidationException. This is especially useful for validating optional values. To give a better understanding, check out this example on how to validate optional values:

createHelloWorld(data: HelloWorldData) {
    // "message" represents the field name inside of the HelloWorldData object
    // Notice the missing required() here
    if(this.validator.text("message", data.title).alphaNum().minLen(3).maxLen(32).check()) {
        // Do something...
    }
    this.validator.throwErrors();
}

Exception Handling

To use the global exception handler you have to register its filter globally.

// Important part
import { ApiExceptionFilter } from '@tsalliance/rest';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Important part
  app.useGlobalFilters(new ApiExceptionFilter());

  await app.listen(3000);
}