-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (88 loc) · 2.13 KB
/
index.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
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
const express = require('express');
const bodyParser = require('body-parser');
const argv = require('optimist')
.boolean('cors')
.argv;
require('dotenv').config();
const cors = require('cors');
const BinRepository = require('./src/BinRepository');
const app = express();
const PORT = argv.p || process.env.PORT || 5000;
const HOST = process.env.HOST || `http://localhost:${PORT}`;
const URL = `${HOST}/bin`;
const binRepository = new BinRepository();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
app.get('/api/bins', (req, res) => {
return binRepository.getAll()
.then((result) => {
res.status(200);
res.send(result);
})
.catch(error => {
res.status(404);
res.send(error);
});
});
app.post('/api/bins', (req, res) => {
return binRepository.createBin()
.then((hash) => {
res.send({
hash,
url: `${URL}/${hash}`
});
res.status(200);
})
.catch(() => {
res.send('Error on create bin. Please try again');
res.status(400);
})
});
app.get('/api/bins/:hash', (req, res) => {
return binRepository.getByHash(req.params.hash)
.then((result) => {
res.status(200);
res.send(result);
})
.catch(error => {
res.status(404);
res.send(error);
});
});
app.get('/api/bins/:hash/:id', (req, res) => {
return binRepository.getById(req.params.hash, req.params.id)
.then((result) => {
res.status(200);
res.send(result);
})
.catch(error => {
res.status(404);
res.send(error);
});
});
app.delete('/api/bins/:hash', (req, res) => {
return binRepository.deleteHash(req.params.hash)
.then(() => {
res.status(200);
res.end();
})
.catch(error => {
res.status(404);
res.send(error);
});
});
app.all('/bin/:hash', (req, res) => {
return binRepository.create(req.params.hash, req)
.then((id) => {
res.status(200);
res.send({ id });
})
.catch(error => {
res.status(404);
res.send(error);
});
});