Skip to content

Commit 54f416d

Browse files
committed
Add quotes.controller.js, database.js, quote.model.js, quotes.routes.js
1 parent 2b2680b commit 54f416d

File tree

7 files changed

+583
-8
lines changed

7 files changed

+583
-8
lines changed

app.js

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,23 @@
11
const express = require("express");
22

3+
const db = require("./data/database");
4+
5+
const quoteRoutes = require("./routes/quotes.routes");
6+
37
const app = express();
48

5-
app.get("/quote", function (req, res, next) {
6-
res.json({
7-
quote:
8-
"As you dive deeper into web development, web development will dive deeper into you!",
9+
app.use("/quote", quoteRoutes);
10+
11+
app.use(function (error, req, res, next) {
12+
res.status(500).res.json({
13+
message: "Something went wrong!",
914
});
1015
});
1116

12-
app.listen(3000);
17+
db.initDb()
18+
.then(function () {
19+
app.listen(3000);
20+
})
21+
.catch(function (error) {
22+
console.log("Connecting to the database failed!");
23+
});

controllers/quotes.controller.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
const Quote = require("../models/quote.model");
2+
3+
async function getRandomQuote(req, res, next) {
4+
let randomQuote;
5+
try {
6+
randomQuote = await Quote.getRandomQuote();
7+
} catch (error) {
8+
return next(error);
9+
}
10+
11+
res.json({
12+
quote: randomQuote,
13+
});
14+
}
15+
16+
module.exports = {
17+
getRandomQuote: getRandomQuote,
18+
};

data/database.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
const mongodb = require("mongodb");
2+
3+
const MongoClient = mongodb.MongoClient;
4+
5+
let database;
6+
7+
async function initDb() {
8+
const client = await MongoClient.connect("mongodb://localhost:27017");
9+
database = client.db("first-api");
10+
}
11+
12+
function getDb() {
13+
if (!database) {
14+
throw new Error("Database not connected!");
15+
}
16+
17+
return database;
18+
}
19+
20+
module.exports = {
21+
initDb: initDb,
22+
getDb: getDb,
23+
};

models/quote.model.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const db = require("../data/database");
2+
3+
class Quote {
4+
static async getRandomQuote() {
5+
const quotes = await db.getDb().collection("quotes").find().toArray();
6+
const randomQuoteIndex = Math.floor(Math.random() * quotes.length);
7+
// [1, 2, 3] => length: 3 => 0.1 * 3 => 0.3 => Math.floor(0.3) => 0
8+
9+
const randomQuote = quotes[randomQuoteIndex];
10+
11+
return randomQuote.text;
12+
}
13+
}
14+
15+
module.exports = Quote;

0 commit comments

Comments
 (0)