Skip to content

Instantly share code, notes, and snippets.

@Rowadz
Last active October 14, 2021 19:18
Show Gist options
  • Save Rowadz/f4d26879efadcac290010de54e0e4257 to your computer and use it in GitHub Desktop.
Save Rowadz/f4d26879efadcac290010de54e0e4257 to your computer and use it in GitHub Desktop.
// eslint-disable-next-line no-unused-vars
module.exports = function(options = {}) {
// Return the actual hook.
return async context => {
// relationRecords are array of data
// e.g: Array<Comments> || Array<Likes> which sequelize will not handle in a patch request
const { id, data: { relationRecords } } = context;
const service1 = context.app.service('relation1Service');
await removeOldData(service1, +id);
await addNewData(service1, +id, relationRecords);
return context;
};
};
// m:n relation
const removeOldData = async (service, fk_id) =>
service.remove(null, { query: { fk_id } });
// m:n relation
const addNewData = async (service, fk_id, arrayOfIds) =>
service.create(
arrayOfIds.map(({ fk2_id }) => ({ fk2_id, fk_id }))
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment