From df02eafbd19b1908a0ae9b799897e534ff991e0a Mon Sep 17 00:00:00 2001 From: Manish Date: Wed, 29 Mar 2023 12:20:16 +1100 Subject: [PATCH] Imp: Do not accept requests on `/api/shorturl/` POST endpoint until`shortUrlsCounter` is read from MongoDB --- index.js | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 6d9059f..0790c9c 100644 --- a/index.js +++ b/index.js @@ -32,21 +32,23 @@ const counterSchema = new mongoose.Schema({ const Counter = mongoose.model("Counter", counterSchema); +let shortUrlsCounterSet = false; let shortUrlsCounter = 0; - Counter.findOne({ name: "shortUrl" }) .then((counter) => { if (counter) { - shortUrlsCounter = counter.seq; console.log(`Old counter: ${counter}`); + shortUrlsCounter = counter.seq; + shortUrlsCounterSet = true; } else { const shortUrlsCounterModel = new Counter({ name: "shortUrl" }); shortUrlsCounterModel .save() .then((counter) => { if (counter) { - shortUrlsCounter = counter.seq; console.log(`New counter: ${counter}`); + shortUrlsCounter = counter.seq; + shortUrlsCounterSet = true; } else { console.log(`Error: could not create a new counter`); } @@ -68,6 +70,12 @@ app.use(express.urlencoded({ extended: false })); // Your first API endpoint app.post("/api/shorturl/", (req, res) => { + if (!shortUrlsCounterSet) { + res.status(503); + return res.send( + "Sorry, this API endpoint is not yet ready to handle requests!" + ); + } const original = req.body.url; try { const hostname = new URL(original).hostname;