-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (47 loc) · 1.38 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const path = require("path");
const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const Planet = require("./models/planet");
const PORT = process.env.PORT || 8000;
// Express app
const app = express();
// Environment Variables
dotenv.config();
// Connect to DB
const dbURI = `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWD}@mongo.jynjm.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority`;
mongoose
.connect(dbURI)
.then(() => {
app.listen(PORT, () => console.log(`Running on port ${PORT}`));
})
.catch((err) => console.log("Could not connect :(", err));
// Routes
app.get("/", cors(), (_, res) => {
res.sendFile(path.join(__dirname, "/views/index.html"));
});
app.get("/all", async (_, res) => {
try {
const data = await Planet.find();
if (!data) {
throw new Error("Something went wrong!");
}
res.status(200).json(data);
} catch (err) {
res.status(500).json({ "Server Error": err.message });
}
});
app.get("/:planet", cors(), async (req, res) => {
try {
const data = await Planet.findOne({
slug: req.params.planet.toLowerCase(),
});
if (!data) {
throw new Error("Are you going beyond solar system?");
}
res.status(200).json(data);
} catch (err) {
res.status(404).json({ error: err.message });
}
});