The shopping list projects chapter08_memory
and chapter08_disk
stored values in memory or a JSON file.
Convert the persistence layer to use PostgreSQL or MongoDB.
Use either the raw database clients (i.e., pg
or mongodb
) or an ODM/ORM (i.e., sequelize
or mongoose
).
The sample code for this chapter has an aggregation operation (summing a total) performed in the domain logic:
// Compute the total quantity of items
function computeTotalQuantity() {
let total = 0;
for (let item of persistence.findAllItems()) {
total += item.quantity;
}
return total;
}
One problem with this code is that computing the sum involves loading the dataset into memory.
Both PostgreSQL and MongoDB support aggregation. How could the code be changed to use aggregation operators (e.g., the sum(quantity)
aggregation operator in SQL and the $sum: "$quantity"
accumulator in a Mongo aggregation pipeline)?
The sample code for this chapter has an API call that uses a function from the imported persistence
and domain
:
app.get('/api/items', (req, res) => {
res.json({
items: persistence.findAllItems(),
total: domain.computeTotalQuantity()
});
});
A problem with this code is that computeTotalQuantity
also calls findAllItems
. This results in two invocations of findAllItems
, and therefore two identical database queries to handle a single request.
Is there a problem with this design? If so, how could it be improved?