Load Once and Queue Every Save

In the last lesson, Hana’s kettle and Omar’s fan reached Dev’s desk at the same moment, both requests received 201 Created, and one ticket never made it into tickets.json. The store read the file, waited, and wrote it back, and another request slipped in during the wait.

In this lesson, you’ll rebuild the store so that can’t happen. You’ll load tickets.json once when the app starts, change tickets in memory, and send every save through one queue, so saves never overlap. Then you’ll run the same race again and count the tickets. Start with the read that came too early.

Load the Tickets Once

The lost ticket came from two reads of the same file before either save. Here’s what race.ts printed against the old store, after both requests read five tickets:

Language: Program Output
[ 201, 201 ]
6

Each create() call loaded its own copy of five tickets, then paused at its await while the other request ran, so the second save wrote over the first. The fix is to stop reading the file for every request. The store reads it once, at startup, into one array, and every request works on that same array.

The store also has to decide what startup does when the file isn’t usable. When there’s no tickets.json yet, as on the café’s very first Saturday, an empty list is the right start. When the file is broken, as some of your race runs left it, the app should refuse to start and say why. In store.ts, replace the load() helper inside createTicketStore() with this function above it, outside the factory:

Language: TypeScript Filename: store.ts
async function load(file: string): Promise<Ticket[]> {
  let text: string;
  try {
    text = await readFile(file, "utf8");
  } catch (error) {
    const missing =
      error instanceof Error && "code" in error && error.code === "ENOENT";
    if (missing) {
      return [];
    }
    throw error;
  }
  try {
    return JSON.parse(text);
  } catch (error) {
    throw new Error(`${file} isn't valid JSON. Fix or replace it.`, {
      cause: error,
    });
  }
}

The first try reads the file. When the file doesn’t exist, the readFile() you know from Timers and Files rejects with an error whose .code is "ENOENT", Node’s code for “no such file or directory.” Then load() returns an empty array. The function rethrows any other read error, such as a permissions problem, as is.

The second try parses the text. A broken file makes JSON.parse() throw a SyntaxError that names a character position but not the file. So load() throws its own error with the file’s name and what to do. It passes the SyntaxError on as its .cause, which keeps the position. The store still trusts that valid JSON holds tickets. Checking the shape of the data properly is a job for schemas, and that’s for later.

Now make the factory load the tickets when you call it. It becomes an async function, and tickets lives inside it for as long as the app runs:

Language: TypeScript Filename: store.ts
export async function createTicketStore(file: string) {
  const tickets = await load(file);

  async function save(): Promise<void> {
    const text = JSON.stringify(tickets, null, 2);
    await writeFile(file, text + "\n");
  }

  async function list(): Promise<Ticket[]> {
    return tickets.map((ticket) => ({ ...ticket }));
  }

  async function get(id: string): Promise<Ticket | undefined> {
    const ticket = tickets.find((ticket) => ticket.id === id);
    return ticket === undefined ? undefined : { ...ticket };
  }

The list() and get() functions no longer touch the file. They stay async, so the routes’ await store.list() and await store.get() keep working unchanged. They hand out copies, { ...ticket }, so code outside the store can’t change a ticket without saving it. The save() function now takes no argument, because there’s only one list to save.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.