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

typeline

v0.0.1

Published

TypeLine is a simple ES6 class utility inspired by React.PropTypes, developed to handle inline and hairy type of validation/sanitization for any type of value, it was written to be used on both browser and server.

Downloads

9

Readme

TypeLine is a simple ES6 class utility to be used on both browser and server, it was developed to handle inline and hairy type of validation/sanitization for any value. Inspired by React.PropTypes.

TypeLine can cross validate the front and back-end of your apps with the same methods. With TypeLine you have validation and sanitization methods for specific types of value, even custom types.

This is still under development, behaviors of this module can change.

how it works

import TypeLine from 'typeline';

let body = {
  firstName: "  John",
  middleName: null,
  lastName: "  Doe  ",
  email: "  [email protected]",
  birthday: undefined,
  password: "123456",
  metadata: {
    timezone: "America/Sao_Paulo",
    extraKey: "something not to be parsed"
  }
};

TypeLine.Object.map({
  firstName: TypeLine.String.isRequired().trim().notEmpty().isAlpha(),
  middlename: TypeLine.toString().trim().isAlpha(),
  lastName: TypeLine.String.isRequired().trim().notEmpty().isAlpha(),
  email: TypeLine.String.isRequired().trim().notEmpty().isEmail(),
  password: TypeLine.String.isRequired().trim().notEmpty().isPassword(),
  birthday: TypeLine.oneOf(
    TypeLine.String.trim().toDate(),
    TypeLine.Date
  ), //if no isRequired mehtod than is optional
  password: TypeLine.String.isRequired().trim().notEmpty().isPassword(),
  registeredAt: TypeLine.Date.setDefault(() => new Date()).toString(),
  metadata: {
    timezone: TypeLine.String
  }
}).exec(value).then((bodySafe) => {
  console.log("value is now", bodySafe)
}, (errors) => {
  console.log("errors", errors);
})

------- stdout -------

Value is now {
  firstName: "John",
  middleName: "",
  lastName: "Doe",
  email: "[email protected]",
  password: "Abc@123-456",
  registeredAt: "2015-10-25 04:15:14",
  metadata: {
    timezone: "America/Sao_Paulo"
  }
}

How to extend existing types

import TypeLine, {TypeLineError} from 'typeline';

TypeLineError.extend({
  NumberOutOfRange(min, max) {
    return this.i18n `The value is out of range(${min}, ${max})`;
  }
})

TypeLine.extend('Number', {
  range(min, max) {
    if(typeof min !== 'number')
      throw new Error("The min argument must be a number");
    if(typeof max !== 'number')
      throw new Error("The max argument must be a number");
    if(max > min)
      throw new Error("The max argument should be bigger than min");
    return (value) => {
      if(value < min)
        throw new TypeLineError.NumberOutOfRange(min, max);
    }
  },
  ceil() {
    return (value) => {
      return Math.round(value);
    }
  }
})

How to extend new custom types

import TypeLine, {TypeLineError} from 'typeline';

const __DATA__ = Symbol('__DATA__')
    , __VALID__ = Symbol('__VALID__')
    , __PARSING__ = Symbol('__PARSING__');

class Model {

  static schema = {};

  constructor(data) {
    this[__DATA__] = new Map();
    this[__VALID__] = false;
    this[__PARSING__] = 0;
    if(data) {
      if(typeof data !== 'object' || Array.isArray(data))
        throw new Error("The first argument must be an object");
      Object.getOwnPropertyNames(data).forEach((propName) => {
        this[__DATA__].set(propName, data[propName]);
      })
    }
  }

  async parse() {
    const {schema} = this.constructor;
    this[__PARSING__]++;
    try {
      let data = await TypeLine.Object.map(schema).exec(this[__DATA__]);
    } catch(err) {
      this[__PARSING__]--;
      throw err;
    }
    this[__PARSING__]--;
    this[__DATA__] = new Map();
    this[__VALID__] = true;
    Object.getOwnPropertyNames(data).forEach((propName) => {
      this[__DATA__].set(propName, data[propName]);
      Object.defineProperty(this, propName, () => {
        enumerable: true,
        configurable: true,
        get() {
          return this[__DATA__].get(propName)
        },
        async set(value) {
          this[__PARSING__]++;
          try {
            value = await schema[propName].exec(value);
          } catch(err) {
            this[__PARSING__]--;
            throw err;
          }
          this[__PARSING__]--;
          this[__DATA__].set(propName, value);
        }
      });
    })
  }

  isParsing() {
    return this[__PARSING__].length > 0;
  }

  isValid() {
    return this[__VALID__];
  }

}

class User extends Model {

  static schema = {
    firstName: TypeLine.String.isRequired().trim().notEmpty().isAlpha(),
    middlename: TypeLine.toString().trim().isAlpha(),
    lastName: TypeLine.String.isRequired().trim().notEmpty().isAlpha(),
    email: TypeLine.String.isRequired().trim().notEmpty().isEmail(),
  };

}

TypeLineError.extend({
  UserDataNotAnObject() {
    return this.i18n `User data is not an object`;
  }
})

TypeLine.extend('User', {
  isType() {
    return (value) => {
      if(value instanceof User)
        return value;
      throw new TypeLineError.InvalidType;
    }
  },
  toType() {
    return (value) => {
      if(value instanceof User)
        return value;
      if(typeof value !== 'object' || Array.isArray(value))
        throw new TypeLineError.UserDataNotAnObject;
      return new User(value);
    }
  },
  parse() {
    return async (value) => {
      await value.parse();
      return value;
    }
  }
})