Practice how to implement batching and caching for an API using callbacks.
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
node populateDb.js
Okay! Now that everything is ready. Let’s start the server.
node server.js
Open a new terminal and just execute the following command:
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