# @theorchard/field-validator

A class utility that lets you do simple and fast type checks on object properties. Very handy in formatters where the response is "unknown" from an external service.

There are two kinds of validator methods, `optional` and `mandatory`.
Using the mandatory validators (e.g. `FieldValidator.str`) will throw exceptions if the property is undefined. The optional validators will not throw, but return undefined.

There's a quick overview video [here](https://drive.google.com/file/d/1GRCZf6JnJlR3ViYQMQ5Kjuve2KVApATE/view?usp=sharing).

## Usage

```ts
import { FieldValidator, FieldValidator as Field } from '@theorchard/field-validator';

interface FormatterOutput {
    id: number;
    name: string;
    tags: string[];
    imageUrl?: string;
    type: string;
}

// Usage of static functions
const MyFormatter = (payload: unknown): FormatterOutput => ({
    id: Field.int(payload, 'id'),
    name: Field.str(payload, 'name'),
    tags: Field.arrayStr(payload, 'tags'),
    imageUrl: Field.optStr(payload, 'imageUrl'),
    type: Field.str(payload, 'type', 'defaultType'),
});

// Usage of instance methods
const MySecondFormatter = (payload: unknown): FormatterOutput => {
    const wrapper = FieldValidator.from(payload);

    return {
        id: wrapper.int('id'),
        name: wrapper.str('name'),
        tags: wrapper.arrayStr('tags'),
        imageUrl: wrapper.optStr('imageUrl'),
        type: wrapper.str('type', 'defaultType'),
    };
};

// Example of using it for environment vars
const EnvVars = new FieldValidator(process.env);
const config = {
    mandatoryString: EnvVars.str('SOME_VAR_1'),
    optionalBoolean: EnvVars.optBool('SOME_VAR_2'),
};
```
