GithubHelp home page GithubHelp logo

catharism's Introduction

Catharism

Runtime type guards and checks for complex data structures.

Overview

Have you ever been in a situation when you can't trust the backend side of your application to send valid data? And you'd give up a bit of perfomance for a clue what on the Earth is wrong with that seeminly correct massive nested data structure that you had received? Start practicing catharism and your prayers will be answered!

The library provides a set of helpers that cast unknown data to the expected type warning when the data doesn't match the type when built for development, being silent otherwise.

Installation

npm install catharism
yarn add catharism

Type guards

Consider having a type defined as follows:

interface Student {
  name: string;
  age: number;
}

With catharism's primitve type guards and combinators you can define a type guard for an array of students in no time:

import type { Student } from "src/models/Student";
import { isNumber, isString, isArrayOf, isObjectOf } from "catharism";

const isListOfStudents = isArrayOf(
  isObjectOf({
    name: isString,
    age: isNumber,
  })
);

declare const data: unknown; // Received from untrusted source.

if (isListOfStudents(data)) {
  // `data` has pased all the checks,
  // so it is assignable to Student[] until the end of the 'if' block.
}

Type casting

Want to be warned if data doesn't match the expected format during debugging but don't want the app to stop working in production environment? Combine type cast helpers the same way you did with type guards:

import { number, string, arrayOf, objectOf } from "catharism";

const listOfStudents = arrayOf(
  objectOf({
    name: string,
    age: number,
  })
);

declare const data: unknown;

const list = listOfStudents(data);

If built not for production, listOfStudents will warn you if the list is malformed or any item in the list is malformed. Otherwise no check will be done.

Type casting doesn't modify data. When there's need for modifying data, type conversion comes in handy

Type conversion

Sometimes there's a need to actually modify incoming data so that it matches a type not supported by JSON, like Date, BigInt or a custom type. Unlike type casting, type conversion modifies incoming data so that it satisfies desired types. The only drawback is that for the compound types we need to use a different set of helpers, although their names follow the same pattern and signatures remain the same.

// types.ts

const Banana = Symbol("Banana");
const Orange = Symbol("Orange");
const Pineapple = Symbol("Pineapple");

type EdibleType = typeof Banana | typeof Orange | typeof Pineapple;

export interface Edible {
  type: EdibleType;
  count: number;
  expireAt: Date;
}
// cast.ts

// ...imports...

const toType: Cast<EdibleType> = (data: unknown, path = "") => {
  if (isString(data)) {
    switch (data) {
      case "banana":
        return Banana;
      case "orange":
        return Orange;
      case "pineapple":
        return Pineapple;
    }
  }

  warn(${data}» is not on the list, sorry`, path);
  return data as EdibleType; // We have to return something anyways.
};

// We used toArrayOf and toObjectOf instead of arrayOf and objectOf accordingly,
// so that on production it still runs all the needed conversions for the underlying data.
export const toEdibles: Cast<Edible[]> = toArrayOf(
  toObjectOf({
    type: toType,
    count: number,
    expiredAt: toDate,
  })
);
// somewhere in your-http-service.ts
// ...

async function getEdibles(): Promise<Edible[]> {
  return toEdibles(await httpClient.get("edibles"));
}

// ...

catharism's People

Contributors

ssipak avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.