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));