Imp: Do not accept requests on /api/shorturl/ POST endpoint untilshortUrlsCounter is read from MongoDB

This commit is contained in:
Manish 2023-03-29 12:20:16 +11:00
parent 8072461ab2
commit df02eafbd1

View File

@ -32,21 +32,23 @@ const counterSchema = new mongoose.Schema({
const Counter = mongoose.model("Counter", counterSchema); const Counter = mongoose.model("Counter", counterSchema);
let shortUrlsCounterSet = false;
let shortUrlsCounter = 0; let shortUrlsCounter = 0;
Counter.findOne({ name: "shortUrl" }) Counter.findOne({ name: "shortUrl" })
.then((counter) => { .then((counter) => {
if (counter) { if (counter) {
shortUrlsCounter = counter.seq;
console.log(`Old counter: ${counter}`); console.log(`Old counter: ${counter}`);
shortUrlsCounter = counter.seq;
shortUrlsCounterSet = true;
} else { } else {
const shortUrlsCounterModel = new Counter({ name: "shortUrl" }); const shortUrlsCounterModel = new Counter({ name: "shortUrl" });
shortUrlsCounterModel shortUrlsCounterModel
.save() .save()
.then((counter) => { .then((counter) => {
if (counter) { if (counter) {
shortUrlsCounter = counter.seq;
console.log(`New counter: ${counter}`); console.log(`New counter: ${counter}`);
shortUrlsCounter = counter.seq;
shortUrlsCounterSet = true;
} else { } else {
console.log(`Error: could not create a new counter`); console.log(`Error: could not create a new counter`);
} }
@ -68,6 +70,12 @@ app.use(express.urlencoded({ extended: false }));
// Your first API endpoint // Your first API endpoint
app.post("/api/shorturl/", (req, res) => { 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; const original = req.body.url;
try { try {
const hostname = new URL(original).hostname; const hostname = new URL(original).hostname;