-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
50 lines (43 loc) · 1.1 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
require("dotenv").config();
const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const errorHandler = require("./handlers/error");
const authRoutes = require("./routes/auth");
const messagesRoutes = require("./routes/messages");
const { loginRequired, ensureCorrectUser } = require("./middleware/auth");
const db = require("./models");
const PORT = 8081;
app.use(cors());
app.use(bodyParser.json());
//routes
app.use("/api/auth", authRoutes);
app.use("/api/users/:id/messages",
loginRequired,
ensureCorrectUser,
messagesRoutes
)
app.get("/api/messages", loginRequired, async function(req, res, next){
try{
let messages = await db.Message.find()
.sort({ createdAt: "desc"})
.populate("user",{
username: true,
profileImageUrl: true
});
return res.status(200).json(messages);
}
catch(err){
return next(err);
}
});
app.use(function(req,res,next){
let err = new Error("Not Found");
err.status = 404;
next(err);
});
app.use(errorHandler);
app.listen(PORT, function() {
console.log(`server started at ${PORT}`);
});