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

@varasto/orm

v0.6.0

Published

Simple ORM which uses Varasto as it's backend

Downloads

42

Readme

@varasto/orm

npm

An attempt to build an ORM that uses Varasto as it's backend. It's still very basic and can store only simple data.

TODO list

This ORM implementation is still on very early stage. Some missing features that would make it more complete and usable are:

  • Support for arrays.
  • Support for enumerations. (Kind of already implemented.)
  • One-to-one and one-to-many relations.

Installation

Install the NPM package:

$ npm install --save @varasto/orm

Install reflect-metadata shim:

$ npm install --save reflect-metadata

And import it somewhere in the global place of your application.

And then make sure that decorator support has been enabled by adding following lines to your tsconfig.json:

"emitDecoratorMetadata": true,
"experimentalDecorators": true,

Usage

Define an model class by adding Model decorator to an class. Then decorate all the properties of that class that you wish to be persisted with Field decorator. Model class also needs an identifier / key property that is type of string and decorator with Key decorator.

Currently only boolean, number and string values are supported for fields.

import { Field, Key, Model } from '@varasto/orm';

@Model()
class User {
  @Key()
  id?: string;

  @Field()
  firstName: string;

  @Field()
  lastName: string;

  @Field()
  isActive: boolean;

  constructor(firstName: string, lastName: string, isActive: boolean = true) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.isActive = isActive;
  }
}

Retrieval

import { get, list } from '@varasto/orm';

// Retrieves an user instance from the storage, identified by given key. If an
// user with the given key does not exist, the promise will fail.
const user = await get(storage, User, 'c8d676f8-fb38-11ed-8fac-4fd6a4acc103');

// Retrieves all users from the storage.
const allUsers = await list(storage, User);

Insertion

import { save } from '@varasto/orm';

// Create new user instance without a key.
const user = new User('John', 'Doe', true);

// And store it into the storage. After this operation the user instance will
// have an automatically generated UUID key.
await save(storage, user);

Update

import { get, save, updateAll } from '@varasto/orm';

// Retrieve an user from the storage that we know already exists there.
const user = await get(storage, User, 'c8d676f8-fb38-11ed-8fac-4fd6a4acc103');

// Update some of it's properties.
user.isActive = false;

// And store it into the storage. Because the user instance already has an key,
// an update will be performed instead of insertion.
await save(storage, user);

// Perform an bulk update that deactives all users whose first name is not
// "John".
const deactivatedUsers = await updateAll(
  storage,
  User,
  { firstName: { $neq: 'John' } },
  { isActive: false }
);

Removal

import { get, remove, removeAll } from '@varasto/orm';

// Again let's retrieve an user from the storage.
const user = await get(storage, User, 'c8d676f8-fb38-11ed-8fac-4fd6a4acc103');

// And immediately remove it from the storage afterwards. After this operation
// the user instance will no longer have a key.
await remove(storage, user);

// Perform an bulk removal which deletes all users whose last name is "Doe".
const removedUserCount = await removeAll(storage, User, { lastName: 'Doe' });

Querying

import { count, find, findAll, keys } from '@varasto/orm';

// Retrieve the total number of users stored in storage.
const totalNumberOfUsers = await count(storage, User);

// Retrieve all keys of users stored in storage.
const allUserKeys = await keys(storage, User);

// Find the first user which `firstName` property is "John". If no such user
// exists in the storage, `undefined` will be returned instead.
const john = await find(storage, User, { firstName: 'John' });

// Retrieve all inactive users.
const allInactiveUsers = await findAll(storage, User, { isActive: false });

See simple-json-match for documentation on how the query schemas work. Notice that model keys cannot be included in the queries, as they are stored separately from the other model data.

Validation

Class level

If an model class has method called clean, it will be always called before an model is stored into the storage.

This method can be used to perform validation or modify values of the fields before they are inserted into the storage.

import { Field, Key, Model } from '@varasto/orm';

@Model()
class User {
  @Key()
  id?: string;

  @Field()
  firstName: string;

  @Field()
  lastName: string;

  @Field()
  isActive: boolean;

  constructor(firstName: string, lastName: string, isActive: boolean = true) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.isActive = isActive;
  }

  clean() {
    if (this.firstName.length === 0) {
      throw new Error('User must have a first name.');
    }

    // Limit maximum length of users last name to 5 just to annoy people.
    if (this.lastName.length > 5) {
      this.lastName = this.lastName.substr(0, 5);
    }
  }
}

Field level

Each field in the model class can be given an array of validator functions. These functions are called before the model instance is stored into the storage and they should throw instance of ValidationError if the given value is not valid.

import { Field, Model, ValidationError } from '@varasto/orm';

const validateX = (x: number) => {
  if (x < 0 || x > 100) {
    throw new ValidationError('Value of "x" must be between 0 and 100');
  }
};

const validateY = (y: number) => {
  if (y < 50) {
    throw new ValidationError('Value of "y" must be at least 50');
  }
};

@Model()
class Point {
  @Field({ validators: [validateX] })
  x: number;

  @Field({ validators: [validateY] })
  y: number;
}
Built-in validators

This package comes with 4 built-in validator function generators.

minValidator
minValidator(
  min: number,
  errorMessage: string
) => (value: any) => void

Creates an validator function that will throw an validation error with given error message if the value is less than the given minimum value.

maxValidator
maxValidator(
  max: number,
  errorMessage: string
) => (value: any) => void

Creates an validator function that will throw an validation error with given error message if the value is greater than the given maximum value.

minMaxValidator
minMaxValidator(
  min: number,
  max: number,
  errorMessage: string
) => (value: any) => void

Creates an validator function that will throw an validation error with given error message if the value is not in the range of given minimum and maximum values.

regexpValidator
regexpValidator(
  pattern: RegExp,
  errorMessage: string
) => (value: any) => void

Creates an validator function that will throw an validation error with given error message if the value does not match given regular expression.