-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (91 loc) · 2.36 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
const Koa = require("koa");
const Router = require("koa-router");
const cors = require("@koa/cors");
const axios = require("axios");
const cheerio = require("cheerio");
const app = new Koa();
const router = new Router();
const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
if (err.status) {
ctx.status = err.status;
ctx.body = { error: err.message };
} else {
console.error(err);
ctx.status = 500;
ctx.body = { error: "Internal server error" };
}
}
});
router.use(async (ctx, next) => {
return next();
});
router.get("/", async (ctx, next) => {
let $;
console.log("request");
await axios
.get("https://www.ufc.com/rankings")
.then(res => {
$ = cheerio.load(res.data, { normalizeWhitespace: true });
})
.catch(err => {
console.log(err);
});
let response = [];
let weight_classes = $(".views-view-table"); // selecting all tables
// here I am creating an object for each weight class (wc), which will contain the wc name and all fighters
// rank 0 means champ
weight_classes.find($(".info")).each((idx, el) => {
let info = {
wclass: "",
fighters: []
};
info.wclass = $(el)
.find($("h4"))
.text();
const regex = /pound-for-pound/gi;
info.wclass = info.wclass.replace(regex, "P4P"); // replacing pound-for-pound with P4P, as it's shorter
info.fighters.push([
$(el)
.find($("a"))
.text()
]);
response.push(info);
});
let rank;
let name;
let rank_change;
weight_classes.find($("tbody")).each((idxTbl, table) => {
$(table)
.find($("tr"))
.each((idxCell, cell) => {
rank = $(cell)
.find(".views-field-weight-class-rank")
.text()
.replace(/\s\s+/g, "");
name = $(cell)
.find("a")
.text()
.replace(/\s\s+/g, "");
rank_change = $(cell)
.find(".views-field-weight-class-rank-change")
.text()
.replace(/\s\s+/g, "");
response[idxTbl].fighters.push([name, rank_change]);
});
});
ctx.body = response;
return next();
});
router.get("/favicon.ico", async (ctx, next) => {
ctx.status = 204;
next();
});
app.use(router.routes());
app.listen(PORT, null, () => {
console.log("App running on port", PORT);
});