-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
54 lines (44 loc) · 973 Bytes
/
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
const express = require("express");
const app = express();
// Middleware
app.use(express.json());
// Routes
app.get("/", (req, res) => {
res.status(200).send({ data: "cool" });
});
app.get("/user", (req, res) => {
res.status(200).send({
data: {
user: "alex",
},
});
});
const createNewUser = (n) => {
return new Promise((resolve, reject) => {
resolve({ name: n, user: "guest", ts: Date.now() });
});
};
app.post("/user", async (req, res) => {
const { name = "" } = req.body;
try {
const newUser = await createNewUser(name);
res.status(201).send({
data: {
...newUser,
},
});
} catch (e) {
res.status(500).send({
data: {
error: e,
},
});
}
});
app.use((req, res, next) => {
res.status(404).send("Sorry, this route doesn't exist. Have a nice day :)");
});
const port = process.env.PORT || "8080";
app.listen(port, () => {
console.log("server is up on " + port);
});