Skip to content

Commit

Permalink
refactor: improve array sanitizing
Browse files Browse the repository at this point in the history
* improve metadata store
* fix `each` sanitize decorators option
* add support di container
* other minor changes
  • Loading branch information
derevnjuk committed Aug 22, 2019
1 parent a2e3907 commit 1dfc886
Show file tree
Hide file tree
Showing 30 changed files with 12,520 additions and 6,835 deletions.
5 changes: 0 additions & 5 deletions .eslintrc.json

This file was deleted.

7 changes: 4 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
build/
node_modules/
*.log
build/
node_modules/
*.log
.idea/
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ src
__tests__
tslint.json
tsconfig.json
.prettierrc
.idea
9 changes: 9 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"tabWidth": 2,
"singleQuote": true,
"bracketSpacing": true,
"printWidth": 80,
"trailingComma": "none",
"arrowParens": "always",
"quoteProps": "consistent"
}
20 changes: 0 additions & 20 deletions .travis.yml

This file was deleted.

290 changes: 146 additions & 144 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,144 +1,146 @@
# `hollowverse/class-sanitizer` [![Build Status](https://travis-ci.org/hollowverse/class-sanitizer.svg?branch=master)](https://travis-ci.org/hollowverse/class-sanitizer)

Allows to use decorator and non-decorator based sanitization in your Typescript classes.
Internally uses [validator.js][1] to make sanitization.

## Installation

`npm install @hollowverse/class-sanitizer --save`

## Usage

Create your class and put some sanity decorators on its properties you want to sanitize:

```typescript
import { sanitize, Trim, Rtrim, Blacklist } from 'class-sanitizer';

export class Post {
@Trim() title: string;

@Rtrim(['.'])
@Blacklist(/(1-9)/)
text: string;
}

let post1 = new Post();
post1.title = ' Hello world ';
post1.text = '1. this is a great (2) post about hello 3 world.';

sanitize(post);
console.log(post);
// now post will look like this:
// Post {
// title: "Hello world",
// text: ". this is a great post about hello world"
// }
```

## Custom sanitization classes

If you have custom sanity logic you want to use as annotations you can do it this way:

1. First create a file, lets say `LetterReplacer.ts`, and create there a new class:

```typescript
import { SanitizerInterface, SanitizerConstraint } from 'class-sanitizer';

@SanitizerConstraint()
export class LetterReplacer implements SanitizerInterface {
sanitize(text: string): string {
return text.replace(/o/g, 'w');
}
}
```

Your class must implement `SanitizerInterface` interface and its `sanitize` method, which defines sanitization logic.

2. Then you can use your new sanitization constraint in your class:

```typescript
import { Sanitize } from 'class-sanitizer';
import { LetterReplacer } from './LetterReplacer';

export class Post {
@Sanitize(LetterReplacer) title: string;
}
```

Here we set our newly created `LetterReplacer` sanitization constraint for `Post.title`.

3. Now you can use sanitizer as usual:

```typescript
import { sanitize } from 'class-sanitizer';

sanitize(post);
```

## Using service container

Sanitizer supports service container in the case if want to inject dependencies into your custom sanity constraint
classes. Here is example how to integrate it with [typedi][2]:

```typescript
import { Container } from 'typedi';
import { Sanitizer } from 'class-sanitizer';

// do this somewhere in the global application level:
let sanitizer = Container.get(Sanitizer);
sanitizer.container = Container;

// now everywhere you can inject `Sanitizer` class which will go from the container
// also you can inject classes using constructor injection into your custom sanitizers.
```

## Manual sanitization

There are several methodw in the `Sanitizer` that allows to perform non-decorator based sanitization:

```typescript
import Sanitizer from 'class-sanitizer';

Sanitizer.blacklist(str, chars);
Sanitizer.escape(str);
Sanitizer.ltrim(str, chars);
Sanitizer.normalizeEmail(str, isLowercase);
Sanitizer.rtrim(str, chars);
Sanitizer.stripLow(str, keepNewLines);
Sanitizer.toBoolean(input, isStrict);
Sanitizer.toDate(input);
Sanitizer.toFloat(input);
Sanitizer.toInt(input, radix);
Sanitizer.toString(input);
Sanitizer.trim(str, chars);
Sanitizer.whitelist(str, chars);
Sanitizer.toUpperCase(str);
Sanitizer.toLowerCase(str);
```

## Sanitization decorators

| Decorator | Description |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@Blacklist(chars: RegExp)` | Remove characters that appear in the blacklist. |
| `@Escape()` | Replace <, >, &, ', " and / with HTML entities. |
| `@Ltrim()` | Trim characters from the left-side of the input. |
| `@NormalizeEmail()` | Canonicalize an email address. |
| `@Rtrim()` | Trim characters from the right-side of the input. |
| `@StripLow()` | Remove characters with a numerical value < 32 and 127, mostly control characters. |
| `@ToBoolean(isStrict?: boolean)` | Convert the input to a boolean. Everything except for '0', 'false' and '' returns true. In strict mode only '1' and 'true' return true. |
| `@ToDate()` | Convert the input to a date, or null if the input is not a date. |
| `@ToFloat()` | Convert the input to a float. |
| `@ToInt()` | Convert the input to an integer, or NaN if the input is not an integer. |
| `@ToString()` | Convert the input to a string. |
| `@Trim(chars?: string[])` | Trim characters (whitespace by default) from both sides of the input. You can specify chars that should be trimmed. |
| `@Whitelist(chars: RegExp)` | Remove characters that do not appear in the whitelist.\* The characters are used in a RegExp and so you will need to escape some chars, e.g. whitelist(input, '\\[\\]'). |
| `@ToUpperCase()` | (self-explanatory) |
| `@ToLowerCase()` | (self-explanatory) |

## Examples

Take a look at [the tests](./__tests__) for more examples of usages.

[1]: https://github.com/chriso/validator.js
[2]: https://github.com/pleerock/typedi
# neuralegion/class-sanitizer

Allows to use decorator and non-decorator based sanitization in your Typescript classes.
Internally uses [validator.js][1] to make sanitization.

## Installation

`npm install @neuralegion/class-sanitizer --save`

## Usage

Create your class and put some sanity decorators on its properties you want to sanitize:

```typescript
import { sanitize, Trim, Rtrim, Blacklist } from '@neuralegion/class-sanitizer';

export class Post {
@Trim() title: string;

@Rtrim(['.'])
@Blacklist(/(1-9)/)
text: string;
}

let post1 = new Post();
post1.title = ' Hello world ';
post1.text = '1. this is a great (2) post about hello 3 world.';

sanitize(post);
console.log(post);
// now post will look like this:
// Post {
// title: "Hello world",
// text: ". this is a great post about hello world"
// }
```

## Custom sanitization classes

If you have custom sanity logic you want to use as annotations you can do it this way:

1. First create a file, lets say `LetterReplacer.ts`, and create there a new class:

```typescript
import { SanitizerInterface, SanitizerConstraint } from '@neuralegion/class-sanitizer';

@SanitizerConstraint()
export class LetterReplacer implements SanitizerInterface {
sanitize(text: string): string {
return text.replace(/o/g, 'w');
}
}
```

Your class must implement `SanitizerInterface` interface and its `sanitize` method, which defines sanitization logic.

2. Then you can use your new sanitization constraint in your class:

```typescript
import { Sanitize } from '@neuralegion/class-sanitizer';
import { LetterReplacer } from './LetterReplacer';

export class Post {
@Sanitize(LetterReplacer) title: string;
}
```

Here we set our newly created `LetterReplacer` sanitization constraint for `Post.title`.

3. Now you can use sanitizer as usual:

```typescript
import { sanitize } from '@neuralegion/class-sanitizer';

sanitize(post);
```

## Using service container

Sanitizer supports service container in the case if want to inject dependencies into your custom sanity constraint
classes. Here is example how to integrate it with [typedi][2]:

```typescript
import {Container} from 'typedi';
import {useContainer, Sanitizer} from '@neuralegion/class-sanitizer';

// do this somewhere in the global application level:
useContainer(Container);
let sanitizer = Container.get(Sanitizer);

// now everywhere you can inject Sanitizer class which will go from the container
// also you can inject classes using constructor injection into your custom SanitizerConstraint-s
```

## Manual sanitization

There are several methodw in the `Sanitizer` that allows to perform non-decorator based sanitization:

```typescript
import Sanitizer from '@neuralegion/class-sanitizer';

Sanitizer.blacklist(str, chars);
Sanitizer.escape(str);
Sanitizer.ltrim(str, chars);
Sanitizer.normalizeEmail(str, isLowercase);
Sanitizer.rtrim(str, chars);
Sanitizer.stripLow(str, keepNewLines);
Sanitizer.toBoolean(input, isStrict);
Sanitizer.toDate(input);
Sanitizer.toFloat(input);
Sanitizer.toInt(input, radix);
Sanitizer.toString(input);
Sanitizer.trim(str, chars);
Sanitizer.whitelist(str, chars);
Sanitizer.toUpperCase(str);
Sanitizer.toLowerCase(str);
```

## Sanitization decorators

| Decorator | Description |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `@Blacklist(chars: RegExp)` | Remove characters that appear in the blacklist. |
| `@Escape()` | Replace <, >, &, ', " and / with HTML entities. |
| `@Ltrim()` | Trim characters from the left-side of the input. |
| `@NormalizeEmail()` | Canonicalize an email address. |
| `@Rtrim()` | Trim characters from the right-side of the input. |
| `@StripLow()` | Remove characters with a numerical value < 32 and 127, mostly control characters. |
| `@ToBoolean(isStrict?: boolean)` | Convert the input to a boolean. Everything except for '0', 'false' and '' returns true. In strict mode only '1' and 'true' return true. |
| `@ToDate()` | Convert the input to a date, or null if the input is not a date. |
| `@ToFloat()` | Convert the input to a float. |
| `@ToInt()` | Convert the input to an integer, or NaN if the input is not an integer. |
| `@ToString()` | Convert the input to a string. |
| `@Trim(chars?: string[])` | Trim characters (whitespace by default) from both sides of the input. You can specify chars that should be trimmed. |
| `@Whitelist(chars: RegExp)` | Remove characters that do not appear in the whitelist.\* The characters are used in a RegExp and so you will need to escape some chars, e.g. whitelist(input, '\\[\\]'). |
| `@ToUpperCase()` | (self-explanatory) |
| `@ToLowerCase()` | (self-explanatory) |

## Examples

Take a look at [the tests](./__tests__) for more examples of usages.

## External links

[1]: https://github.com/chriso/validator.js
[2]: https://github.com/pleerock/typedi
Loading

0 comments on commit 1dfc886

Please sign in to comment.