Skip to content

Instantly share code, notes, and snippets.

@alexandrebodin
Created April 15, 2017 20:23
Show Gist options
  • Save alexandrebodin/76f01aeb1caf537ecee5b6c5bf238eaf to your computer and use it in GitHub Desktop.
Save alexandrebodin/76f01aeb1caf537ecee5b6c5bf238eaf to your computer and use it in GitHub Desktop.
entitySave
// 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