Created
April 15, 2017 20:23
-
-
Save alexandrebodin/76f01aeb1caf537ecee5b6c5bf238eaf to your computer and use it in GitHub Desktop.
entitySave
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
// db/utils/buildSaver.js | |
const buildEntitySaver = (tableName, entityToDB) => { | |
function create(entity) { | |
return queryBuilder(tableName) | |
.insert(entityToDB(entity)) | |
.returning('id') | |
.then(([id]) => id); | |
} | |
function edit(entity) { | |
return queryBuilder(tableName) | |
.update(entityToDB(entity, true)) | |
.returning('id') | |
.where('id', entity.id) | |
.then(([id]) => id) | |
} | |
function save(entity) { | |
if (entity.id === null) { | |
return create(entity) | |
.then(id => entity.set('id', id)); | |
} | |
return edit(entity).then(() => entity); | |
} | |
return save; | |
} | |
// db/contact/save.js | |
function entityToDB(contact, isEdition = false) { | |
const { | |
type, | |
createdAt, | |
updatedAt, | |
} = contact; | |
return { | |
type, | |
created_at: createdAt, | |
updated_at: isEdition ? new Date() : updatedAt, | |
}; | |
} | |
const entityToDB = new Resolver({ | |
id: (data, { isEdition }) => | |
updatedAt: (data, { isEdition }) => isEdtition === true ? new Date() : data.updated_at; | |
}) | |
entityToDB(data, { isEdition }); | |
const saveContact = buildEntitySaver('contact', entityToDB); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment