-
-
Notifications
You must be signed in to change notification settings - Fork 447
Mickey Haile -Node-Coursework-Week2 #269
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
const express = require("express"); | ||
const cors = require("cors"); | ||
const bodyParser = require("body-parser"); | ||
|
||
const app = express(); | ||
|
||
|
@@ -20,4 +21,46 @@ app.get("/", function (request, response) { | |
response.sendFile(__dirname + "/index.html"); | ||
}); | ||
|
||
app.get("/messages/search", (req, res) => { | ||
const { term } = req.query; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Always nice to try and cover off edge cases and handle them; e.g. what if |
||
console.log(term); | ||
const filterMessages = messages.filter((message) => | ||
message.text.toLowerCase().includes(term.toLowerCase()) | ||
); | ||
console.log(filterMessages); | ||
res.send(filterMessages); | ||
}); | ||
|
||
app.get("/messages", (req, res) => { | ||
res.json(messages); | ||
}); | ||
|
||
app.get("/messages/:id", function (req, res) { | ||
const id = req.params.id; | ||
messages = messages.filter((message) => message.id === Number(id)); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To convert to an integer, use |
||
res.status(200).send(messages); | ||
}); | ||
|
||
app.get("/messages/latest", (req, res) => { | ||
res.json(messages.slice(-10)); | ||
}); | ||
|
||
app.post("/messages", (req, res) => { | ||
const { from, text } = req.body; | ||
const ourMessageObject = { | ||
id: Date.now(), | ||
from, | ||
text, | ||
timeSent: new Date().toLocaleDateString(), | ||
}; | ||
messages.push(ourMessageObject); | ||
res.send("Message received successfully."); | ||
}); | ||
|
||
app.delete("/messages/:id", (req, res) => { | ||
const id = req.params.id; | ||
messages = messages.filter((message) => message.id !== Number(id)); | ||
res.json(messages); | ||
}); | ||
|
||
app.listen(process.env.PORT); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would add a default value for this in case this env var is not set (e.g. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nowadays you can just use
express.json()
(turns out theexpress
package now includesbodyParser
by default, and soexpress.json()
is the same thing asbodyParser.json
in middleware - this was news to me 😅 )