-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverScript.js
More file actions
98 lines (87 loc) · 2.35 KB
/
serverScript.js
File metadata and controls
98 lines (87 loc) · 2.35 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
let bodyParser = require('body-parser')
let express = require('express');
let app = express();
const cors = require("cors");
const router = express.Router();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cors({origin:"*"}))
app.use("/api/cardlist", router);
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
const cardList = [
{
id: 1,
name: "Dank Magician",
level : 7,
attribute : "Dark",
type : "Spellcaster"
},
{
id: 2,
name: "Dank Magician Girl",
level : 6,
attribute : "Dark",
type : "Spellcaster"
},
{
id: 3,
name: "Dank Rebelion",
level : 4,
attribute : "Dark",
type : "Dragon"
}
];
router.get("/", (req, res) => {
res.json(cardList);
});
router.get("/:id", (req, res) => {
const cardID = req.params.id;
const currentID = cardList.find((card) => card.id == cardID);
if (currentID) {
res.json(currentID);
} else {
res.sendStatus(404);
}
});
router.post("/", (req, res) => {
const postCard = req.body;
const isValid = isValidCard(postCard) && !cardList.find((card) => card.id == postCard.id);
if (isValid) {
cardList.push(postCard);
res.send(postCard);
} else {
res.sendStatus(500);
}
});
router.put("/:id", (req, res) => {
const cardID = req.params.id;
const currentCard = cardList.find((card) => card.id == cardID);
if (currentCard) {
const putCard = req.body;
const isValid = isValidCard(putCard);
if (isValid) {
currentCard.name = putCard.name;
currentCard.level = putCard.level;
currentCard.attribute = putCard.attribute;
currentCard.type = putCard.type;
res.sendStatus(204);
} else {
res.sendStatus(404);
}
}
});
router.delete("/:id", (req, res) => {
const cardID = req.params.id;
const currentCard = cardList.findIndex((card) => card.id == cardID);
if (currentCard !== -1) {
cardList.splice(currentCard, 1);
res.sendStatus(204);
} else {
res.sendStatus(404);
}
});
function isValidCard(card) {
return "id" in card && "name" in card && "level" in card && "attribute" in card && "type" in card;
}