-
-
Save scootcho/23e78af7aa70abbd52b1bee903a683a3 to your computer and use it in GitHub Desktop.
Node.js ( knex / bootshelf helper)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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.' }); | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment