-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
61 lines (53 loc) · 1.72 KB
/
main.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
56
57
58
59
60
61
// IMPORTS
// ===============================================================================
const express = require("express");
const Post = require("./models/postDB");
const User = require("./models/userDB");
const breaker = "=====================================";
// SETUP
// ===============================================================================
const app = express();
const port = process.env.PORT || 8080;
app.listen(port, ()=>{
console.log(`listening on port ${port}`);
console.log(breaker);
});
// ROUTING
// ===============================================================================
app.get("/", (req, resp)=>{
resp.header("Access-Control-Allow-Origin", "*");
resp.send("hi!");
})
app.get("/api/index", async (req, resp)=>{
const allPosts = await Post.find({});
let latestPost = {};
for(let post of allPosts){
latestPost = post;
};
const index = latestPost.sNum;
resp.header("Access-Control-Allow-Origin", "*");
resp.send({latest: index});
});
app.get("/api/loadmore", async (req, resp)=>{
const {latest_index, posts_loaded} = req.query;
const startingSnum = latest_index-posts_loaded;
// get 3 posts
const postLists = [];
for(let i = 0; i<3; i++){
const idx = startingSnum - i;
//console.log(idx);
if(idx >= 0){
const post = await Post.findOne({sNum: idx});
postLists.push(post);
}
}
// get username from user id
const usernameList = [];
for(let post of postLists){
const username = await User.findOne({userId: post.authorId});
usernameList.push(username.username);
}
reply = {postLists, usernameList};
resp.header("Access-Control-Allow-Origin", "*");
resp.send(reply);
});