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

@storehouse/sequelize

v1.1.0

Published

Sequelize manager for @storehouse/core.

Downloads

3

Readme

storehouse-sequelize

Sequelize (ORM) manager for @storehouse/core.

Note

In case you are familiar with sequelize, code in typescript and define your models by extending the class Model, we suggest you don't use this package as you will still need to import your models everytime. However we will still cover that case here.

Add a manager

import Storehouse from '@storehouse/core';
import { SequelizeManager } from '@storehouse/sequelize';

// register
Storehouse.add({
  local: {
    // type: '@storehouse/sequelize' if you called Storehouse.setManagerType(SequelizeManager)
    type: SequelizeManager, 
    config: {
      // Options
      options: {
        dialect: 'mysql',
        host: 'localhost',
        database: 'database',
        username: 'root',
        password: '',
        logging: false
      },

      // ModelSettings[]
      models: []
    }
  }
});

About config:

  • options? contains Sequelize's connection options.
  • models? is an object that will help define the models to sequelize. Each object may contain:
    • attributes: Model attributes.
    • options?: Model options. No need for a connection instance (sequelize) here.
    • model?: The model class extending Model.

Logging

If you don't apply logging option, you can enable the default logs with the package debug.

import debug from 'debug';
debug.enable('@storehouse/sequelize*');

Model definition

As for sequelize, there are 2 ways of defining models. We will give examples in typescript but the same could be done in javascript.

Simple usage

import { 
  DataTypes, 
  Model,
  ModelStatic, 
  ModelAttributes, 
  ModelOptions, 
  Optional 
} from 'sequelize';
import Storehouse from '@storehouse/core';
import { ModelSettings, SequelizeManager } from '@storehouse/sequelize';

interface MovieAttributes {
  id: number;
  title: string;
  rate?: number | null;
}

type MovieCreationAttributes = Optional<MovieAttributes, 'id'>;

interface MovieInstance
  extends Model<MovieAttributes, MovieCreationAttributes>, MovieAttributes { }

const movieSchema: ModelAttributes<MovieInstance, MovieAttributes> = {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  title: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  rate: {
    type: DataTypes.TINYINT,
    validate: {
      max: 5,
      min: 1,
      isInt: true
    }
  }
};

const movieOptions: ModelOptions<Model<MovieAttributes, MovieCreationAttributes>> = {
  modelName: 'movies', // We need to choose the model name
};

const movieSettings: ModelSettings<MovieAttributes, MovieCreationAttributes> = {
  attributes: movieSchema,
  options: movieOptions
};

Storehouse.add({
  local: {
    type: SequelizeManager, 
    config: {
      models: [
        // ModelSettings
        movieSettings
      ],
      options: {
        // ...
      }
    }
  }
});

// retrieve a model
const Movies = Storehouse.getModel<ModelStatic<MovieInstance>>('local', 'movies');
if (Movies) {
  const newMovie: MovieCreationAttributes = {
    title: `Last Knight ${Math.ceil(Math.random() * 1000) + 1}`,
    rate: 3
  };
  const r = await Movies.create(newMovie);
  console.log('added new movie', r.id, r.title);
}

// or retrieve the manager
const manager = Storehouse.getManager<SequelizeManager>('local');
if(manager) {
  // then retrieve the model as
  manager.getModel<ModelStatic<MovieInstance>>('movies');
  // or
  manager.getModel<MovieInstance>('movies');
}

Extending Model

import { 
  DataTypes, 
  Model, 
  ModelAttributes, 
  ModelOptions, 
  Optional  
} from 'sequelize';
import Storehouse from '@storehouse/core';
import { ModelSettings, SequelizeManager } from '@storehouse/sequelize';

interface MovieAttributes {
  id: number;
  title: string;
  rate?: number | null;
}

type MovieCreationAttributes = Optional<MovieAttributes, 'id'>;

class Movie extends Model<MovieAttributes, MovieCreationAttributes> implements MovieAttributes {
  id!: number;
  title!: string;
  rate?: null | number;

  // timestamps!
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  static createMovie(title: string, rate?: number): Promise<Movie> {
    return Movie.create({ title, rate });
  }

  get fullTitle(): string {
    return [this?.id, this?.title].join(' ');
  }
}

type MovieCtor = typeof Movie & { new(): Movie };

const movieSchema: ModelAttributes<Movie, MovieAttributes> = {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  title: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  rate: {
    type: DataTypes.TINYINT,
    validate: {
      max: 5,
      min: 1,
      isInt: true
    },
  }
};

const movieOptions: ModelOptions<Model<MovieAttributes, MovieCreationAttributes>> = {
  // If "modelName" is not specified, 
  // it will be the name of the class extending Model ("Movie")
  modelName: 'movies', 
  tableName: 'movies'
};

const movieSettings: ModelSettings<MovieAttributes, MovieCreationAttributes> = {
  model: Movie,
  attributes: movieSchema,
  options: movieOptions
};

Storehouse.add({
  local: {
    type: SequelizeManager, 
    config: {
      models: [
        // ModelSettings
        movieSettings
      ],
      options: {
        // ...
      }
    }
  }
});


// retrieve a model
const Movies = Storehouse.getModel<MovieCtor>('local', 'movies');
if (Movies) {
  const r = await Movies.createMovie('Movie title', 3);
  console.log('added new movie', r.fullTitle);
}

// or retrieve the manager
const manager = Storehouse.getManager<SequelizeManager>('local');
if(manager) {
  // then retrieve the model as
  manager.getModel<MovieCtor>('movies');
}

SequelizeManager

SequelizeManager extends the class Sequelize, so you have access to its properties and methods.

Example:

await Storehouse.getManager<SequelizeManager>('local')?.sync();
// or
await Storehouse.getConnection<Sequelize>('local')?.sync();
// or
await Storehouse.getManager<SequelizeManager>('local')?.getConnection().sync();

References