-
Notifications
You must be signed in to change notification settings - Fork 2
/
node_helper.js
99 lines (86 loc) · 3.57 KB
/
node_helper.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
const NodeHelper = require("node_helper")
const Log = require("logger")
module.exports = NodeHelper.create({
async socketNotificationReceived (notification, payload) {
const self = this
if (notification === "RETRIEVE_RESULTS") {
const url = "https://hs-consumer-api.espncricinfo.com/v1/pages/matches/current?lang=en&latest=true"
try {
const response = await fetch(url)
const body = await response.json()
let results = this.cleanJsonResults(body)
results = this.filterResult(results, payload)
self.sendSocketNotification("RESULTS_RETRIEVED", results)
} catch (error) {
Log.log("Error", error)
self.sendSocketNotification("RESULTS_RETRIEVED_FAILED", error)
}
}
},
filterResult (results, payload) {
const numberOfDays = payload.numberOfDays
const endRange = new Date(Date.now())
// startRange is endRange minus the numberOfDays
const startRange = new Date(endRange.getTime() - (numberOfDays * 24 * 60 * 60 * 1000))
// filter the results where the startdate and enddate are somewhere between startRange and endRange
let filteredResults = results.filter(result => {
const startDate = new Date(result.startDate)
const endDate = new Date(result.endDate)
return (startDate >= startRange && startDate <= endRange) || (endDate >= startRange && endDate <= endRange)
})
// status must not be null
filteredResults = filteredResults.filter(result => result.stage === "FINISHED")
return filteredResults
},
cleanJsonResults (json) {
// json looks like this, see Documentation/Example_match_result.json for full json
//
// {
// "matches": [
// {
// "startDate": "2024-08-30T00:00:00.000Z",
// "endDate": "2024-09-03T00:00:00.000Z",
// "title": "2nd Test",
// "statusText": "Bangladesh won by 6 wickets",
// "ground": {
// "smallName": "Rawalpindi",
// },
// "teams": [
// {
// "team": {
// "abbreviation": "PAK",
// "imageUrl": "db/PICTURES/CMS/381800/381891.png"
// },
// "score": "274 & 172"
// "scoreInfo": "T:185"
// },
// ],
// }
// ]
// }
const urlPrefix = "https://img1.hscicdn.com/image/upload/f_auto,t_ds_square_w_160,q_50/lsci"
const results = []
json.matches.forEach(match => {
const teams = []
match.teams.forEach(team => {
teams.push({
teamName: team.team?.abbreviation,
imageUrl: urlPrefix + team.team?.imageUrl,
score: team.score,
scoreInfo: team.scoreInfo
})
})
const result = {
startDate: match.startDate,
endDate: match.endDate,
title: match.title,
ground: match.ground?.smallName,
status: match.statusText,
stage: match.stage,
teams: teams
}
results.push(result)
})
return results
}
})