Search⌘ K
AI Features

Exercise: Batching and Caching with Callback

Explore how to implement batching and caching mechanisms in Node.js using callbacks, streams, and events. This lesson helps you handle asynchronous data streams efficiently, avoid common pitfalls like Zalgo callbacks, and optimize API responses without relying on promises or async/await.

Problem statement

Implement batching and caching for the totalSales API examples using only callbacks, streams, and events (without using promises or async/await).

Pay attention to Zalgo when returning cached values!

Coding challenge

Write your solution code in the following code widget. We’ve already added the package.json file for your ease.



// Write your code here


Template code to implement batching and caching with callbacks

Solution

Here’s the solution to the above problem. You can go through it by executing the following command:

C++
node populateDb.js

Okay! Now that everything is ready. Let’s start the server.

C++
node server.js

Open a new terminal and just execute the following command:

C++
cd app && node loadTest.js

import { createServer } from 'http'
import { totalSales } from './totalSalesCache.js'

createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost')
  const product = url.searchParams.get('product')
  console.log(`Processing query: ${url.search}`)

  totalSales(product, (err, sum) => {
    if (err) {
      res.setHeader('Content-Type', 'application/json')
      res.writeHead(500)
      res.end(
        JSON.stringify({
          error: 'Internal server error',
        })
      )
      return
    }
    res.setHeader('Content-Type', 'application/json')
    res.writeHead(200)
    res.end(
      JSON.stringify({
        product,
        sum,
      })
    )
  })
}).listen(8000, () => console.log('Server started'))
Solution code to implement batching and caching with callbacks

Explanation

...