-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.js
81 lines (67 loc) · 2 KB
/
server.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
require("dotenv").config();
// get all the packages we need
const express = require("express");
const connectToDatabase = require("./connectToDatabase");
const ObjectId = require("mongodb").ObjectId;
// set our port
const port = process.env.PORT || 3000;
// create and configure our express app
const app = express();
app.use(express.json()); // tell express to parse json data
/**
* routes
* ===========================
* ===========================
**/
/**
* Home Page
*/
app.get("/", async (req, res) => {
res.json({ message: "welcome to the new twitter!" });
});
/**
* Get all tweets
*/
app.get("/tweets", async (req, res) => {
const { db } = await connectToDatabase();
const tweets = await db.collection("tweets").find({}).toArray();
res.json({ tweets });
});
// get a single tweet
app.get("/tweets/:tweetId", async (req, res) => {
const { db } = await connectToDatabase();
const tweet = await db
.collection("tweets")
.findOne({ _id: new ObjectId(req.params.tweetId) });
res.json({ tweet });
});
// create a tweet
app.post("/tweets", async (req, res) => {
const { db } = await connectToDatabase();
const result = await db
.collection("tweets")
.insertOne({ text: req.body.text });
res.json({ tweetId: result.insertedId });
});
// update a tweet
app.put("/tweets/:tweetId", async (req, res) => {
const { db } = await connectToDatabase();
const tweet = await db.collection("tweets").findOneAndUpdate(
{ _id: new ObjectId(req.params.tweetId) },
{ $set: { text: req.body.text } },
{ returnOriginal: false } // return the updated document
);
res.json({ tweet });
});
// delete a tweet
app.delete("/tweets/:tweetId", async (req, res) => {
const { db } = await connectToDatabase();
await db
.collection("tweets")
.deleteOne({ _id: new ObjectId(req.params.tweetId) });
res.code(204); // response code for resource deleted successfully
});
// express listen on 3000 and log a message
app.listen(port, () => {
console.log(`server started on port ${port}`);
});