0.3.0 • Published 3 years ago

@davecode/structures v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

@davecode/structures [beta/wip]

Structures is a TypeScript library for easily building data structure classes that are

  • Serializable: Can convert rich objects to JSON objects or Uint8Arrays.
  • Validatable: All structures have built-in validation which can include custom validations.
  • Fully Typed: Custom structures' properties are fully typed, and even nullable ones are maked optional.

This library is custom-built for my website, davecode.net, where it is used to define all of the data structures in my database, validate API request bodies, and easily share logic across the stack using it's easy serialization system. You can view these structures as examples here

yarn add @davecode/structures

Usage

Let's take a look at defining a custom structure.

import { Structure, types } from '@davecode/structures';

const Person = new Structure('Person')
  .prop('name', types.String)
  .prop('age', types.Number)
  .prop('occupation', types.String.nullable)
  .method('sayHello', function () {
    console.log(`${this.name} says Hello.`);
  })
  .create();

// For TypeScript users
type Person = InstanceType<typeof Person>;

// Creating a structure
const dave = new Person({
  // name and age are REQUIRED here (will cause compile and runtime error)
  // however occupation is OPTIONAL here, since it is nullable
  name: 'dave caruso',
  age: 17,
});

Person, types.String, and many others are instances of DataType<T>, which provide serialization and validation.

Person.validate(person); // true

const json = Person.toJSON(person);
const person2 = Person.fromJSON(json);

types.ArrayOf(types.String).validate(['hello']); // true
types.ArrayOf(types.String).validate([124]); // false

See the nonexistant docs for more information on what is available.

0.3.0

3 years ago

0.2.1

3 years ago

0.2.0

3 years ago

0.2.3

3 years ago

0.2.2

3 years ago

0.1.3

3 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago