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

sequelize-this

v3.4.0

Published

Enables schema definition via JavaScript Classes among other utility functions

Downloads

52

Readme

Installation

npm install --save sequelize-this

or

yarn add sequelize-this

The latest beta build

yarn add sequelize-this@beta

Test

npm install sequelize
npm run test
  • Note: sequelize is listed a peer dependency, which may not be installed automatically

Purpose of this Package

Utility functions for Sequelize

Note: This package was created to assist me in my projects, as such the features included may not be as cohesive as other packages. It was also created with MySQL in mind, but should work for any of the supported dialects. If you have any feature requests or suggestions, feel free to open an issue.

API

sequelize-this

classToSequelizeSchema(classDefinition, options: Sequelize.DefineOptions<any> = {}, sqtOptions: SqtOptions = {}): function(sequelize: Sequelize): Sequelize.Model

  • Converts a regular Javascript Class instance into a Sequelize Schema function, that can then be used to generate the Sequelize Schema upon initialization
  • If nameOverride is undefined (or any equivalent to false), then the class name is used
  • options is passed into schema.define
  • Known Issue: instance/class methods must be defined as a method, and not as a property on a class (as shown below)
  • Example:
    import Sequelize from 'sequelize'
    import { classToSequelizeSchema, property } from 'sequelize-this'
    import { hasMany } from 'sequelize-this/relationships'
    
    class Base {
        @property({
            type: Sequelize.UUID,
            primaryKey: true,
            defaultValue: Sequelize.UUIDV4,
            allowNull: false
        })
        id
    }
    
    @hasMany('Comment')
    class User extends Base {
        @property({ type: Sequelize.STRING })
        name
    
        doSomethingWithUser() {
            ...
        }
    }
    
    export default classToSequelizeSchema(User)
  • Note: User will have the property id via inheritance
    • All relationships and properties are inherited
    • (WIP) Custom logic to find subclasses if performing a find() or findAll() on a superclass
  • Note: Support for usage without decorators is no longer provided
  • Instead of a method called associate, you can define a static method called modifySchema, since you can do anything to the schema object in this method. This is relevant if you wish to initialize Sequelize yourself, instead of using the provided initializeSequelize function
    • Format of modifySchema method:
          static modifySchema(schema) {
              return (sequelize) => {
                  schema.hasMany(sequelize.models.Comment)
              }
          }
    • In fact, a method called associate is indeed created behind the scenes, but this may change in the future

SqtOptions

  • nameOverride: string

initializeSequelize(sequelize: Sequelize, schemaDir: string, options: InitializeSequelizeOptions = {}): Promise<Sequelize.Sequelize>

  • Allow support for custom filters for model files (TODO)
  • Will load all .js files in the defined schema directory (and subdirectories)
  • Will set an exportable singleton variable called connection that you can import from any file
  • Returns a promise once all schemas are loaded
  • Example:
    import express from 'express'
    import Sequelize from 'sequelize'
    import { initializeSequelize } from 'sequelize-this'
    
    const app = express()
    
    app.use('/', myRoutes)
    
    const port = process.env.PORT || 9000
    
    const sequelize = new Sequelize('dbname', 'user', 'password', {
        host: 'localhost',
        dialect: 'mysql',
        pool: {
            max: 10,
            min: 0,
            idle: 10000
        },
        logging: false
    })
    
    initializeSequelize(sequelize, __dirname + '/../common/mysql_schema')
    .then(() => sequelize.sync())
    .then(() => {
        app.listen(port, () => {
            console.log(`Server listening on port ${ port }!`)
        })
    })

InitializeSequelizeOptions

  • silent: boolean

setConnection(sequelize: Sequelize)

  • If you wish to initialize Sequelize yourself instead of using initializeSequelize, but still want to use the singleton pattern, you can set the connection variable using this method and use connection normally

getConnection(): Promise<Sequelize>

  • Returns when all schemas are loaded and connection is set
  • Throws an error if initializeSequelize was never run

connection: Sequelize

  • Singleton variable holding the sequelize instance
  • Use this to retrieve the value synchronously if you know connection will be set by the time this variable is used

property(defineAttributes: DefineAttribute)

  • Define a Sequelize property

type DefineAttribute = string | Sequelize.DataTypeAbstract | Sequelize.DefineAttributeColumnOptions

  • Note: This is exactly the same as Sequelize.DefineAttributes, except it is for a single property vs. an object containing multiple properties

relationships

  • Exports object relationships; see below for relationships API

sequelize-this/relationships

relationship(relationshipType: string, targetClass: string, options: Sequelize.AssociationOptions)

  • Use this to decorate a class to set a relationship
  • Valid types: 'hasOne', 'hasMany', 'belongsTo', 'belongsToMany'
  • options is passed directly to Seqeulize (for associations)

hasOne(targetClass: string, options: Sequelize.AssociationOptions, overrideOptions)

  • Wrapper for relationship('hasOne', targetClass, options)

hasMany(targetClass: string, options: Sequelize.AssociationOptions)

  • Wrapper for relationship('hasMany', targetClass, options)

belongsTo(targetClass: string, options: Sequelize.AssociationOptions)

  • Wrapper for relationship('belongsTo', targetClass, options)

belongsToMany(targetClass: string, options: Sequelize.AssociationOptions)

  • Wrapper for relationship('belongsToMany', targetClass, options)

EXPERIMENTAL

OverrideOptions: {
    [keyFromAssociationOptions: string] : (schema) => any
}
  • Note: This is exactly the same as Sequelize.AssociationOptions except you can define a function that is called after the schema is initialized, in case you need to use schema-specific information (perhaps to modify the relationship name due to foreign key conflicts?)
  • Pass this in as the 4th argument for relationship or 3rd argument for any of the wrapper functions

Changes

Version 3.1.0

  • Fixed the way methods were attached to the schema object
  • Included basic test suite (WIP)
  • Fixed some option types
  • Added SQT-specific options (i.e. silence output)

Version 3.0.0

  • Ported to TypeScript
  • Better documentation
  • Several breaking changes in API, including the way options are passed in