In this lesson, you caught the repair café’s app crashing in the middle of a save, saw why that can break tickets.json, and changed the store’s save() so the file survives the app crashing during a save.
Key Points
- A server doesn’t always finish what it starts. The app can crash, or its process can be killed, right in the middle of a save.
- A crash during a save can lose the whole list. A test script started the app from the five starting tickets, kept posting tickets to it, killed the app’s process at a random moment, and checked whether
tickets.jsonstill parsed. In a hundred runs with the store from the last lesson, ninety-three left a file that parses, one left it empty, at zero bytes, and six left it cut short. On a broken file,load()stops the app, because the file isn’t valid JSON anymore. writeFile()replaces a file in steps, not in one go. It first opens the file for writing, which empties it to zero bytes. Then it writes the new text in, a piece at a time, and then it closes the file. A crash before the open leaves the old list, a crash after the last write leaves the new one, and a crash in between leaves an empty file or one cut short.- Write the new text to a temporary file, then rename it over the real one. A rename moves no bytes. It points the name
tickets.jsonat the new file in one step, so at every momenttickets.jsonholds the whole old list or the whole new one. A ticket caught mid-save gets no201, so the desk can’t tell whether it was saved. A crash during the write can only break the temporary file, and the next save writes over it. - Keep the temporary file beside
tickets.json, because the system’s temp folder can be on another disk. A rename only works within one file system, and the same folder keeps both files on the same one. - The queue still runs one save at a time, so two saves never share the temporary file.
- The same hundred crashes against the new store left a
tickets.jsonthat parses every time. In forty-five runs, a temporary file was left behind, which the app never reads. - Each safeguard prevents one problem. Loading once and changing tickets in memory stops one request from erasing another’s update. The queue stops two writes from overlapping. The rename stops an app crash from breaking the file.
- A JSON file is enough for one app at the café. Run several copies of the app, and each keeps its own tickets and its own queue, so one copy’s save wipes out another’s tickets. That’s what databases are for, and they’re for later.
The Final Code
Here’s the top of store.ts with the new import, and the start of createTicketStore() with the two-step save(). The rest of the store is unchanged from the last lesson: