Last active
January 27, 2023 16:47
-
-
Save uxdxdev/d20e3d8bea548b79e2f303107f799bea to your computer and use it in GitHub Desktop.
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
// 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