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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dataffy/themis

v1.3.4

Published

<h1 align="center">Dataffy Themis - The advanced validation library</h1>

Downloads

19

Readme

About The Project

Themis is a flexible validation library built on 3 layers used for validation. Each upper layer is based on the previous layer and adds extra functionality.

Layers from top to bottom:

  • Schema + Fields - Used to validate and transform an entire object.
  • Processors - Used to validate and transform a value. Uses validators behind the scene
  • Validators - Used to validate a value against some requirements (e.g: max value, max length, etc.)

Getting Started

NPM

npm install @dataffy/themis

Yarn

yarn add @dataffy/themis

Usage

Schemas

Schemas are used to validate and transform an object to the desired representation

import {
  DateField,
  IntegerField,
  FloatField,
  Schema,
  StringField,
} from "@dataffy/themis";

export type CreateEventPayload = {
  name: string;
  price: number;
  date: Date;
  maxCapacity: number;
};

export class CreateEventSchema extends Schema<CreateEventPayload> {
  @StringField({
    maxLength: 100,
  })
  name: string;

  @FloatField({
    minValue: 5.5,
  })
  price: number;

  @DateField({
    formats: ["dd/MM/yyyy"],
  })
  date: Date;

  @IntegerField({
    required: false,
    nullable: true,
    fromField: "max_capacity",
  })
  maxCapacity: number;
}

const payload = {
  name: "Dataffy Themis",
  price: 0,
  date: "01/01/2022",
  max_capacity: 40,
};
const createUserSchema = new CreateUserSchema(payload);

createUserSchema
  .validate()
  .then(() =>
    console.log(
      "Validation was successful. Use .toData() to get the validated data"
    )
  )
  .catch((error) => console.log("Validation failed"));

const validatedData = createUserSchema.toData();

Fields

Fields are decorators used on Schema properties to annotate how the field needs to be processed. Behind the scenes, the fields specify which Processor is used for the field type.

Field Decorator Configuration:

  • fromField - Specifies from which field the value will be taken, processed and placed in the property name. e.g: Using a decorator with fromField: first_name on a property firstName will process the value and place it in the firstName property on the validated data

Example implementation of a Decorator. This example can be used for creating custom decorators:

export const StringField: ValidationField<StringFieldConfig> =
  (configuration?: DecoratorFieldConfig<StringFieldConfig>) =>
  (target: object, propertyKey: string): void => {
    registerField(target, propertyKey, configuration, StringFieldProcessor);
  };

Nested Fields

Nested fields allow specifying a Schema that is used for validating and transforming the nested object.

@NestedField({ schema: FileSchema })
profileImage: FileSchema;

Processors

Processors are used to validate and transform a specific value into the desired one.

Generic Field Configurations:

  • required - Specifies if the field is required. Default value is true
  • nullable - Specifies if the field is nullable. Default value is true
  • validators - Extra validators against which the value is checked

Each field can have extra field configurations.

| Field | Processor | Configuration | | ----------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | @StringField() | StringFieldProcessor | maxLength - The max length allowed for the field minLength - The min length allowed for the field | | @BooleanField() | BooleanFieldProcessor | | | @DateField() | DateFieldProcessor | formats - Array with the accepted string formats for the date | | @IntegerField() | IntegerFieldProcessor | maxValue - The max value allowed for the field minValue - The min value allowed for the field | | @FloatField() | FloatFieldProcessor | maxValue - The max value allowed for the field minValue - The min value allowed for the field | | @EmailField() | EmailFieldProcessor | | | @JsonField() | JsonFieldProcessor | | | @ArrayField() | ArrayFieldProcessor | child - The type of values the array has. It can be a Schema class or Processor class childConfig - Used to specify the config for the child, if the child is a processor class |

Creating a custom processor:

import { FieldProcessor, MinValueValidator } from "@dataffy/themis";

export type CustomFieldConfig = FieldConfig &
  Partial<{
    // Your field config
  }>;

export class CustomProcessor extends FieldProcessor<
  CustomFieldConfig,
  number,
  number
> {
  toInternalValue(data: number): number {
    // Validate value and transform it to expected response
  }

  initialiseValidators(): void {
    // Push validators into the validators property based on the configuration properties
    if (this.configuration.minValue) {
      this.validators.push(new MinValueValidator(this.configuration.minValue));
    }
  }
}

Validators

Validators are the basic unit for the library. They are used for checking if a value matches the expected requirements.

const maxLength = 50;
const validator = new MaxValueValidator(maxLength);
validator.validate(30);

License

Distributed under the ISC License. See LICENSE for more information.