Last active
September 13, 2018 14:04
-
-
Save neilsonlima/73a9a4e7dabfdacb1078e941f8ca094c to your computer and use it in GitHub Desktop.
Cadastra os elementos que não estão cadastrados e atualiza os que forem diferentes
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' | |
const knex = require('../database') | |
module.exports = { | |
update: async list => { | |
list.forEach(element => { | |
if (element['data'] !== undefined) { | |
let params = element.data | |
return knex('tb_name') | |
.transacting(params) | |
.select('*') | |
.where({ id: params.id }) | |
.map(function (row) { | |
return row | |
}) | |
.then(rows => { | |
return rows.length === 0 ? undefined : rows[0] | |
}) | |
.then(row => { | |
if (!row) { | |
return knex('tb_name') | |
.transacting(params) | |
.insert({'...'}) | |
.returning('id') | |
.then(row => { | |
return { | |
error: false, | |
data: row.id | |
} | |
}) | |
} else { | |
if (...) { | |
return knex('tb_name') | |
.transacting(params) | |
.where({ id: row.id }) | |
.update({'...'}) | |
.then(function () { | |
return { | |
error: false, | |
data: row.id | |
} | |
}) | |
} | |
} | |
}) | |
.catch(err => { | |
return { | |
status: 500, | |
error: true, | |
data: { | |
message: err.message | |
} | |
} | |
}) | |
.then(() => knex.destroy()) | |
} | |
}) | |
// knex.destroy() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment