Skip to content

Instantly share code, notes, and snippets.

@luc0
Last active November 24, 2019 08:36
Show Gist options
  • Save luc0/6da72d2ea4d8c599b8e838ebe1e9a18e to your computer and use it in GitHub Desktop.
Save luc0/6da72d2ea4d8c599b8e838ebe1e9a18e to your computer and use it in GitHub Desktop.
Node.js ( knex / bootshelf helper)
'use strict';
/*
CUSTOM METHODS TO EXTEND ORM
*/
module.exports = {
/*
var instance = new orm.bulkUpsert({
knex: knex,
model: 'modelName',
update: ['uniqueField','field1','field2']
});
instance.add( [ 'uniqueValue','value1','value2' ] );
instance.save( () => {
res.send(data);
});
*/
// Upsert many fields with many values.
bulkUpsert: class bulkUpsert {
constructor(config) {
this.knex = config.knex;
this.values = '';
this.fields = config.update;
this.model = config.model;
this.hasSomethingToSave = false;
}
add(fields) {
this.values += this.values ? ',' : '';
fields.forEach((f, i) => {
this.values += ( i ) ? `,` : `(`;
this.values += ( f == null ) ? `''` : `'${f}'`; // nulls to empty
});
this.values += ')';
this.hasSomethingToSave = true;
}
save(cb) {
let sql = 'INSERT INTO `' + this.model + '` (';
let update = '';
this.fields.forEach((f, i) => {
if (i) {
sql += `,${f}`;
update += `,${f}=VALUES(${f})`;
} else {
sql += f;
update += `${f}=VALUES(${f})`;
}
});
sql += `) VALUES ${this.values} ON DUPLICATE KEY UPDATE ${update}`;
if (this.hasSomethingToSave) {
this.knex.raw(sql).then(() => cb(null, { success: true }));
} else {
cb(null, { success: 'no hubo cambios.' });
}
}
}
};
@luc0
Copy link
Author

luc0 commented Sep 15, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment