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-plus

v1.2.1

Published

A chain programming tool for sequelize.

Downloads

7

Readme

Sequelize Plus

查看中文文档

Get started

Introduction

Sequelize Plus encapsulate Sequelize, and provides a set of chain programming call methods.

Create a SequelizePlus instance

// define a sequelize model
const UserInfo = sequelize.define('User', {
  // ... attributes
});

let userInfoModel

// create an instance by new SequelizePlus()
const SequelizePlus = require('sequelize-plus')
userInfoModel = new SequelizePlus(UserInfo)

// create an instance by plus() (recommended)
const { plus } = require('sequelize-plus')
userInfoModel =  plus(UserInfo)

Autoload

Import all models of sequelize to ModelManager(for association)

const { ModelManager } = require('sequelize-plus')
ModelManager.autoload(sequelize)	// sequelize instance

Quick example

const collector = await userInfoModel
	.fileds(['id', 'user_name', 'birth'])	// SELECT `id`, `user_name`, `birth`
    .where('user_name', 'like', '%J%')		// WHERE `user_name` LIKE '%J%'
    .where('age', 'gt', 18)					// WHERE `age` > 18
    .page(10, 2)							// LIMIT 10, 1
    .findAll()
const resultSet = collector.items

// code above equals to 
const resultSet = await UserInfo.findAll({
    attributes: ['id', 'user_name', 'birth'],
    where: {
        'user_name': {
            [Op.like]: '%J%'
        },
        'age': {
            [Op.gt]: 18
        }
    },
    limit: 10,
    offset: 1
})

Association

Simple association

// assume that UserModel, UserProfile, userVipModel are sequelize model classes
const { plus } = require('sequelize-plus')
const userModel = plus(UserModel)
const userProfileModel = plus(UserProfileModel)
const userVipModel = plus(UserVipModel)

// default alias: combine upper case chars in model name and turn to lower case.
userModel.innerJoin(userProfileModel)

// custom alias
userModel.leftJoin(userProfileModel, 'up')

// set where
userModel.rightJoin(userVipModel, 'uv', {
    expireTime: ['lt', '2021-04-30 00:00:00']
})

Complex association

// leftJoin(models: Array, alias: string)
userModel
	.leftJoin(userVipModel, 'uv')
	.leftJoin([userSupremeVipModel, userVipModel], 'usv')

Fields selection

We assume that table user contains id, user_name and age field, corresponding model User contains id, userName and age; table user_profile contains id, user_id and address and company_name, corresponding model UserProfile contains id, userId, address and companyName.

No association

// filed(name, alias)
userModel.field('userName')				// SELECT `user_name` AS `userName`
userModel.field('userName', 'name')		// SELECT `user_name` AS `name`

const { fn, col } = require('sequelize')
userModel.field(fn('MAX', col('age')), 'maxAge')
// SELECT MAX(`age`) AS 'maxAge'

// fields(fields)
userModel.fields([
    'age', 'userName'
]) 	// SELECT `age`, `user_name` AS `userName`
userModel.fields({
    // alias => field name
    userAge: 'age',
    name: 'userName'
})	// SELECT `age` AS `userAge`, `name` AS `userName`

With associations

userModel.innerJoin('UserProfile', 'up')

// fields(model, fields)
userModel.fields('userProfile', ['address', 'companyName'])
// SELECT `up`.`address`, `up`.`company_name`
userModel.fields('userProfile', {
    name: 'companyName'
})	// SELECT `up`.`company_name` AS 'name'
userModel.fields('up', { ... })	// the same as above

冲突检测

// 冲突检测默认关闭,需要开启冲突检测
SequelizePlus.settings.set('checkFieldNameConflict', true)

userModel
    .leftJoin('UserProfle')
    .field('id')
	.field('up.id')
// Error: Field name conflict: id

Query condition(where)

No association

// setWhere(fieldName, value)
// setWhere(fieldName, operator, value)
userModel.setWhere('name', 'James')			// WHERE `name` = `James`
userModel.setWhere('name', 'like', '%J%')	// WHERE `name` LIKE `%J%`

// where(pk)
userModel.where(1055)		// WHERE `id` = 1055
// where(fieldName, value)
userModel.where('age', 20)	// WHERE `age` = 20
// where(fieldName, operator, value)
userModel.where('age', 'gte', 20)		// WHERE `age` >= 20
// where(Object)
userModel.where({
    name: 'James',
    age: ['gte', 20],
})

With association

userModel.leftJoin(UserVipModel, 'uv')
userModel.leftJoin([UserSupremeVipModel, UserVipModel], 'usv')

userModel.where('usv.expireTime', 'lt', '2021-4-30 00:00:00')
userModel.where('uv.expireTime', {
  lt: '2021-4-30 00:00:00',
  gte: '2021-4-29 00:00:00',
})
console.log(userModel.getOption('where'))
// {
//   '$uv.usv.expire_time$': { [Symbol(lt)]: '2021-4-30 00:00:00' },
//   '$uv.expire_time$': {
//     [Symbol(lt)]: '2021-4-30 00:00:00',
//     [Symbol(gte)]: '2021-4-29 00:00:00'
//   }
// }

userModel.clearOption()
userModel.where$('usv', {
  level: 5,
  expireTime: ['gt', '2021-4-30 00:00:00'],
  id: { in: [100, 101] },
})
console.log(userModel.getOption('where'))
// {
//   '$uv.usv.level$': 5,
//   '$uv.usv.expire_time$': { [Symbol(gt)]: '2021-4-30 00:00:00' },
//   '$uv.usv.id$': { [Symbol(in)]: [ 100, 101 ] }
// }

Aggregation

const func = async () => {
    // count all
  	const count = await userModel.count()
  	console.log(count)

    // get max value
  	const maxAge = await userModel.max('age')
  	console.log(maxAge)

    // get min value
  	const minAge = await userModel.min('age')
  	console.log(minAge)

    // get average value
  	const avgAge = await userModel.avg('age')
  	console.log(avgAge)

    // get summation value
  	const sumAge = await userModel.sum('age')
  	console.log(sumAge)
}

More

// order(field: string, sort: 'asc'|'ASC'|'desc'|'DESC')
userModel.order('id', 'DESC')
// order(items: array)
userModel.order([ ['userName', 'ASC'], ['Age', 'DESC'] ])

// page(pageSize: number, pageNumber: number = 1)
userModel.page(10, 2)
// { limit: 10, offset: 10 }

// group(field)
userModel.group('userName')