04. Persistence
June 5, 2018 ยท View on GitHub
Having our bank lose all transactions between restarts is not only annoying, but also bad for operations and business. 100% uptime is not a bet we want to make in our bank.
Problem
Persisting the transaction log to disk is as easy as calling JSON.stringify on
our transaction log and using the core fs module to write the string to disk.
Loading the transaction log back in is just using require on the resulting
JSON file. Don't over-think things here, there's heaps of way this can be
optimised and there are many sequencing problems here that you can spend the
rest of the week ironing out, but that's not why we're here. They are good to
keep in mind and note, though. Here's some of the ones we've thought of: race
conditions with multiple tellers making operations at the same time, writing
only new records to disk, only replying to the teller after the log has been
committed to disk, etc.
Hint
You can take advantage of the 2nd argument of
JSON.stringify(obj, null, indent) to get pretty printing of your JSON file.
This will make debugging and some of the following exercises easier.
Testing
Test that your bank.js produces a transaction JSON file by issuing it a couple
of deposit and withdraw commands. Also check that the balance is the same
before and after restarting.