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

v1.2.17

Published

sequelize utilitary from fast CRUD

Downloads

18

Readme

sequelize-crud

sequelize utilitary from fast CRUD

Getting Started

methods to migrations

import { createTable, dropTable } from 'sequelize-crud/lib/models/migration';

const tableName = 'User';
const defineTable = Sequelize => ({
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: {
    type: Sequelize.INTEGER,
    unique: true,
    autoIncrement: true,
  },
});

export default {
  up: createTable(tableName, defineTable),
  down: dropTable(tableName),
}

or

import { createAndDropTable } from 'sequelize-crud/lib/models/migration';
...
export default createAndDropTable(tableName, defineTable);

define fields

import { timestampsColumns } from 'sequelize-crud/lib/models/migration';

...timestampsColumns(Sequelize), = 
{
  createdAt: { type: Sequelize.DATE },
  updatedAt: { type: Sequelize.DATE },
  deletedAt: { type: Sequelize.DATE },
})
import { defaultColumns } from 'sequelize-crud/lib/models/migration';

...defaultColumns(Sequelize), = 
{
  externalId: { type: Sequelize.INTEGER },
  isActive: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true },
  createdAt: { type: Sequelize.DATE },
  updatedAt: { type: Sequelize.DATE },
  deletedAt: { type: Sequelize.DATE },
})

import { isActiveAndExternalField } from 'sequelize-crud/lib/models/migration';

...isActiveAndExternalField(Sequelize) = 
externalId: { type: Sequelize.INTEGER },
isActive: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true },
  

for seeders

import { insertAndDeleteTableItems } from 'sequelize-crud/lib/models/migration';

const tableName = 'User';
const data = [
  { name: 'name1' },
  { name: 'name2' },
];

export default insertAndDeleteTableItems(tableName, data);

or this do User.create() for all items en data

import { insertAndDeleteTableItems } from 'sequelize-crud/lib/models/migration';
import models from 'path of models';

const tableName = 'User';
const data = [
  { name: 'name1' },
  { name: 'name2' },
];

export default insertAndDeleteTableItems(tableName, data, models.User);

or ... for precalculate data

import { insertAndDeleteTableItems } from 'sequelize-crud/lib/models/migration';
import models from 'path of models';

const tableName = 'User';
const data = async () => ([
  { name: 'name1' },
  { name: 'name2' },
]);

export default insertAndDeleteTableItems(tableName, getData);

new methods for models

model.verifyPk
model.autoGeneratedFields
model.unupdateFields
model.validateToCreate
model.fullCreate
model.validateToUpdate
model.fullUpdate
model.importData

to add this methods

import fs from 'fs';
import sequelize from 'db/connection';
import { utilModels } from 'sequelize-crud';

const models = {};

const walkSync = (dir, filelist) => {
  const files = fs.readdirSync(dir);
  files.forEach((file) => {
    if (fs.statSync(`${dir}/${file}`).isDirectory()) {
      filelist = walkSync(`${dir}/${file}`, filelist);
    } else if (file.length >= 8 && file.slice(-8) === 'model.js') {
      filelist.push(`${dir}/${file}`);
    }
  });
  return filelist;
};

const fileModels = walkSync(__dirname, []);

fileModels.forEach((fileModel) => {
  let model = sequelize.import(fileModel);
  model = utilModels.addNewFeatures(model);
  models[model.name] = model;
});

Object.keys(models).forEach((modelName) => {
  if (models[modelName].associate) models[modelName].associate(models);
});

export default models;

verifyPk

get Error if id not found or id query is no match

const models from 'db/models';
const id = 1;
models.User.verifyPk(id);

or

const models from 'db/models';
const id = 1;
const clientId = 1;
models.User.verifyPk(id, { clientId });

note for this the relation is n:m

User.belongsToMany(Client, {...})
Client.belongsToMany(User, {...})

autoGeneratedFields

return autoGenerated Fields of model

unupdateFields

return unupdate Fields if you want to declare a field as unupdate

name: {
  type: Sequelize.STRING,
  canUpdate: false,
  allowNull: false,
},

validateToCreate

examples:

{
  name: 'hola',
  password: 'f433', // if field has validation will verify
  clients: [1, 2] , // check if each id is valid in Client table
  userAddress: [  // association start with lowercase
    { name:'a', number:'1' }, // validate each sub assoc
    { name:'b', number:'2' }, 
  ]
}

fullCreate

create is more power that create with assoc default sequelize

examples:

{
  name: 'hola',
  password: 'f433', // if field has validation will verify
  clients: [1, 2] , // check if each id is valid in Client table
  userAddress: [  // association start with lowercase
    { name:'a', number:'1' }, // validate each sub assoc
    { name:'b', number:'2' }, 
  ]
}

validateToUpdate

check if id bellow to father model and do recursive way

fullUpdate

update all data if the valid is correct

importData

if type is 'insert' do simples bulkCreate otherwise

for this is important externalId

example

const users = [{
  externalId: 10, 
  userId: 1, // in other database
  name: 'a',
  number: 1,
}]

User.importData(users);
// addresses need userId but only have externalId and ClientId
const addresses = [{
  externalId: 1,
  userId: 10, // in other database
  name: 'a',
  number: 1,
}]

// userId will be change to real id in the database

controller

base controller script has the next methods:

getById: (id, options = {}) => {},
getAll: (query, options = {}) => {},
create: (body, options = {}) => {},
update: (id, body, options = {}) => {},
remove: (id, options = {}) => {},

in options will be { include :[...]}

import { baseController } from 'sequelize-crud';
const controller = baseController(Account);
export default {
  ...controller,
  getAll: query => controller.getAll(query, { // overwrite method
    include: [{ model: User }],
  }),
  create: async (body) => {
    const { otherField, ...rest } = body;
    // do another function with otherField
    return controller.create(rest);
  },
};

router

crudRouter

you have get, post, patch, delete

options: {
  methods: ['getAll', 'getById','create', 'update', 'remove'] //  default all
  uuid: true|false //default false it is for getById,update and remove pk on model
  controller: baseController | customController, // default baseController
}
import { crudRouter } from 'sequelize-crud'; 
router.use('/clients', crudRouter(Client, options));

validateReq

import { validateReq } from 'sequelize-crud'; // check express-validators
router.post('/auth',
  validateReq(check(['username', 'password'], 'username and password are required').exists()),
  async (req, res, next) => {
  });

sanitize

importDataRouter

import { importDataRouter } from 'sequelize-crud';
router.post('/user-groups', importDataRouter(models.UserGroup));

generateApiConstants

import { generateApiConstants } from 'sequelize-crud';
router.use('/constants', generateApiConstants(models));