Skip to content

Instantly share code, notes, and snippets.

@uxdxdev
Last active January 27, 2023 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uxdxdev/d20e3d8bea548b79e2f303107f799bea to your computer and use it in GitHub Desktop.
Save uxdxdev/d20e3d8bea548b79e2f303107f799bea to your computer and use it in GitHub Desktop.
// Command
const InsertCommand = (database, id) => {
return {
execute: () => database.insertRecord(id),
undo: () => database.deleteRecord(id)
};
};
// Receiver
const insertRecord = id => console.log('>>> Database insert', id);
const deleteRecord = id => console.log('<<< Database delete', id);
const Database = () => {
return {
insertRecord,
deleteRecord
};
};
// Invoker
const rollback = stack => {
while (stack.length > 0) stack.pop().undo();
};
const TransactionStart = commands => {
const stack = [];
commands.map((command, index) => {
if (index === 2) {
console.log('Something went wrong, rollback transaction');
rollback(stack);
return;
}
command.execute();
stack.push(command);
});
};
// Client
const Application = () => {
const database = Database(); // Receiver
const commands = []; // Commands
commands.push(InsertCommand(database, 4673));
commands.push(InsertCommand(database, 7890));
commands.push(InsertCommand(database, 1234));
TransactionStart(commands); // Invoker
};
Application();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment