Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ehacke/validated-base
Abstract validated base class for Typescript models
https://github.com/ehacke/validated-base
modeling validation
Last synced: 20 days ago
JSON representation
Abstract validated base class for Typescript models
- Host: GitHub
- URL: https://github.com/ehacke/validated-base
- Owner: ehacke
- License: mit
- Created: 2020-05-31T16:44:17.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2023-01-11T22:27:58.000Z (almost 2 years ago)
- Last Synced: 2024-03-23T01:23:03.745Z (8 months ago)
- Topics: modeling, validation
- Language: TypeScript
- Homepage: https://asserted.io/posts/type-safe-models-in-node
- Size: 2.31 MB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# validated-base
![npm](https://img.shields.io/npm/v/validated-base)
![install size](https://badgen.net/packagephobia/install/validated-base)
![Codecov](https://img.shields.io/codecov/c/gh/ehacke/validated-base)
![GitHub](https://img.shields.io/github/license/ehacke/validated-base)Abstract validated base class using [class-validator](https://github.com/typestack/class-validator).
## Install
```bash
npm i -S validated-base
```## Usage
Extend to create a class that will validate the object passed in with whatever class-validator decorators you've added.
From that point forward, the instance of the model can be considered valid as it's passed around, and further validation
checks are not necessary.```typescript
import { enumError, ValidatedBase } from "validated-base";
import { IsEnum, IsNumber, IsString, MaxLength, Min } from "class-validator";enum ENUM_THINGS {
FIRST= 'first',
SECOND='second',
}interface ValidatedClassInterface {
foo: string;
bar: number;
things: ENUM_THINGS;
}class ValidatedClass extends ValidatedBase implements ValidatedClassInterface {
constructor(params: ValidatedClassInterface, validate = true) {
super();
this.bar = params.bar;
this.foo = params.foo;
this.things = params.things;
if (validate) {
this.validate();
}
}@IsNumber()
@Min(0)
readonly bar: number;
@IsString()
@MaxLength(10)
readonly foo: string;
@IsEnum(ENUM_THINGS, { message: enumError(ENUM_THINGS) })
readonly things: ENUM_THINGS;
}// Validates class as it's constructed
const validatedModel = new ValidatedClass({ bar: 10, foo: 'something', things: ENUM_THINGS.FIRST });// Throws exception if property is invalid
const boom = new ValidatedClass({ bar: -1, foo: 'this-is-too-long', things: 'not-enum' });
```