Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created January 24, 2020 17:02
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save prof3ssorSt3v3/e505d98c5ebf7b3df60bdd8789cf9f55 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/e505d98c5ebf7b3df60bdd8789cf9f55 to your computer and use it in GitHub Desktop.
"use strict";
const data = require("./data"); //data.channels[n].id .name .last_update
const express = require("express");
const app = express();
app.use(express.json());
app.get("/api/channel", (req, res) => {
//return the list of channels
// respond with a 200
res.json(data);
console.log("GET", data.channels);
});
app.get("/api/channel/:id", (req, res) => {
//return specific channel
// respond with a 200
let obj = data.channels.find(item => item.id == parseInt(req.params.id));
res.json(obj);
console.log("GET", obj);
});
app.post("/api/channel", (req, res) => {
//add new channel then return new list
// respond with a 201
let { name } = req.body;
console.log(req.body);
let id =
data.channels.reduce((prev, curr) => {
return prev < curr.id ? curr.id : prev;
}, 0) + 1;
let last_update = Date.now();
let obj = { id, name, last_update };
data.channels.push(obj);
res.status(201).json(obj);
console.log("POST", data.channels);
});
app.put("/api/channel/:id", (req, res) => {
//replace a channel based on id
// respond with 200 or 204
// 202 if the operation is async and still pending
// Basically an UPDATE but we could also do an INSERT if the id is available
// Or we could choose to create a new id and do an INSERT if the id does not exist
let id = parseInt(req.params.id);
let name = req.body.name;
let last_update = Date.now();
let idx = data.channels.findIndex(item => item.id === id);
data.channels[idx].name = name;
data.channels[idx].last_update = last_update;
res.status(200).json(data.channels[idx]);
console.log("PUT", data.channels);
});
app.patch("/api/channel/:id", (req, res) => {
//edit a channel
// respond with 200 or 204
// 202 if the operation is async and still pending
let id = req.params.id;
let name = req.body.name;
let last_update = Date.now();
let idx = data.channels.findIndex(item => item.id === id);
data.channels[idx].name = name;
data.channels[idx].last_update = last_update;
res.status(200).json(obj);
console.log("PATCH", data.channels);
});
app.delete("/api/channel/:id", (req, res) => {
//delete a channel
//respond with 200 or 204
// 202 if the operation is async and still pending
let id = req.params.id;
data.channels = data.channels.filter(item => item.id !== id);
res.status(204).end();
console.log("DELETE", data.channels);
});
app.head("/api/channel", (req, res) => {
//return same headers as get. no content. to check that endpoint is functional
res.status(200).end();
});
app.options("/api/channel", (req, res) => {
//return headers including ALLOW to say what methods are allowed
res.status(200);
res.set("Allow", "GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD");
res.set("Access-Control-Allow-Origin", "*"); //cors
res.set("Content-Length", "0");
res.end();
});
/**
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'204': 'No Content',
*/
app.listen(3000, err => {
if (err) {
return console.log(err);
}
console.log("listening on port", 3000);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Send Requests to a Server</title>
</head>
<body>
<pre id="output"></pre>
<script>
let url = "http://localhost:3000/api/channel";
// url = url + "/1";
let h = new Headers();
h.append("Content-Type", "application/json");
let data = JSON.stringify({ name: "Steve Griffith" });
let req = new Request(url, {
method: "POST",
headers: h,
body: data
});
fetch(req)
.then(res => res.json())
.then(data => {
console.log(data);
document.getElementById("output").textContent = JSON.stringify(
data,
null,
2
);
});
</script>
</body>
</html>
let data = {
"channels": [
{ "id": 1, "name": "Wes Bos", "last_update": 1579748107846 },
{ "id": 2, "name": "Fun Fun Function", "last_update": 1579229707118 },
{ "id": 3, "name": "Brad Traversy", "last_update": 1578970507005 },
{ "id": 4, "name": "TipTut", "last_update": 1575946507312 },
{ "id": 5, "name": "Colt Steele", "last_update": 1577933707123 },
{ "id": 6, "name": "Net Ninja", "last_update": 1577674507000 }
]
};
module.exports = data;
@Pj-Thinker
Copy link

I believe that In patch and delete http request the

let id = req.params.id;
should be replaced with

let id = parseInt(req.params.id);

Respects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment