-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
109 lines (95 loc) · 2.21 KB
/
Copy pathindex.js
File metadata and controls
109 lines (95 loc) · 2.21 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
99
100
101
102
103
104
105
106
107
108
109
const express = require("express");
const morgan = require("morgan");
require("dotenv").config();
const mongoose = require("mongoose");
const cors = require("cors");
const { response } = require("express");
const Person = require("./models/person");
const app = express();
app.use(express.json());
app.use(cors());
app.use(express.static("build"));
morgan.token("body", function getBody(req, res) {
return JSON.stringify(req.body);
});
app.use(
morgan(":method :url :status :response-time ms - :res[content-length] :body")
);
function createId() {
return Math.floor(Math.random() * Math.floor(1000000));
}
let persons = [
{
name: "Arto Hellas",
number: "040-123456",
id: 1,
},
{
name: "Ada Lovelace",
number: "040-123456",
id: 2,
},
{
name: "Dan Abramov",
number: "040-123456",
id: 3,
},
{
name: "Mary Poppendieck",
number: "040-123456",
id: 4,
},
];
app.get("/api/persons", (request, response) => {
Person.find({}).then((persons) => {
response.json(persons);
});
});
app.get("/api/persons/:id", (req, res) => {
const id = req.params.id;
const person = persons.find((p) => p.id.toString() === id);
if (person) res.json(person);
else res.status(404).end();
});
app.post("/api/persons", (req, res) => {
const body = req.body;
if (!body.name) {
return res.status(400).json({
error: "name missing",
});
}
if (!body.number) {
return res.status(400).json({
error: "number missing",
});
}
if (persons.find((p) => p.name === body.name)) {
return res.status(400).json({
error: "name must be unique",
});
}
const person = {
name: body.name,
number: body.number,
id: createId(),
};
persons = persons.concat(person);
res.json(person);
});
app.delete("/api/persons/:id", (request, response) => {
const id = Number(request.params.id);
persons = persons.filter((person) => person.id !== id);
response.status(204).end();
});
app.get("/info", (req, res) => {
res.send(
`<div>` +
`phonebook has info for ${persons.length} people` +
`<p>${Date()}</p>` +
`</div>`
);
});
const PORT = process.env.PORT;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});