-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
63 lines (47 loc) · 1.85 KB
/
main.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
// ./main.js
import express from 'express'
import cors from 'cors';
import fetch from 'node-fetch';
import { API } from './const.js';
import { METHOD, NO_PARAMETERS, NO_URL, NO_RESULT } from './errors.js';
let counter = 0; // Counter.
// Middlewares.
const app = express();
app.use(express.json());
app.use(cors());
// Port listening.
const port = process.env.PORT || 5500;
app.listen(port, () => console.info(`Listening on port: ${port}`));
// Wrong method request used.
app.post('/', (_, response) => response.json(METHOD));
app.put('/', (_, response) => response.json(METHOD));
app.delete('/', (_, response) => response.json(METHOD));
app.get('/', async (request, response) => {
try {
// Get the paramaters from the GET request.
const parameters = request.query;
if (!parameters) response.json(NO_PARAMETERS);
else if (!parameters.url) response.json(NO_URL);
else {
const url = API + parameters.url;
const data = await fetch(url).then(result => {
return result.ok ? result.json() : result.text()
.then(error => { throw JSON.parse(error) })
}).catch(error => { return error });
// Check the result and change the success value.
const success = data.success && !!data.destination;
const message = success ? data.destination : NO_RESULT;
if (success) { // Display the result in the logs.
console.info(`[${counter}] ${parameters.url} -> ${message}`);
counter++;
}
response.json({ success, message });
}
} catch (error) {
console.error(error);
response.json({
success: false,
message: `Something went wrong: ${error}`
});
}
});