-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.js
95 lines (95 loc) · 2.69 KB
/
service.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
const Datastore = require('nedb-promises')
const axios = require('axios')
let db,instance
module.exports = {
init:async()=>{
db = Datastore.create({ filename: './website.db', autoload: true })
instance = axios.create()
instance.defaults.timeout = 800
},
add:async(req,res)=>{
var valid=req.body.name&&req.body.name.trim().startsWith("https://")||req.body.name.trim().startsWith("http://")
if(!valid){
res.status(500).json({
success:false,
reason:"url invalid"
})
return
}
let document={
name:req.body.name,
dateCreated:Date.now(),
lastChecked:Date.now(),
lastHealth:'Good',
}
try{
let isExists=await db.find({name:document.name})
if(isExists.length>0)throw ({message:"Already on the list"})
let newDoc=await db.insert(document)
res.status(200).json({
success:true,
data:newDoc
})
}
catch(err){
res.status(500).json({
success:false,
reason:err.message
})
}
},
removeAll:async(req,res)=>{
try{
let remDoc=await db.remove({})
res.status(200).json({
success:true,
data:remDoc
})
}
catch(err){
console.log(err)
res.status(500).json({
success:false,
reason:err.message
})
}
},
getAll:async(req,res)=>{
try{
let allSites=await db.find({})
res.status(200).json({
success:true,
data:allSites
})
}
catch(err){
res.status(500).json({
success:false,
reason:err.message
})
}
},
checkHealth:async(req,res)=>{
let allSites=await db.find({})
allSites.map(async site=>{
try{
let check=await instance.get(site.name)
let success=check.status<400
await db.update({ name:site.name}, { $set: {
lastChecked:Date.now(),
lastHealth:'Good',
reason:"Ping Success"
}
},{ upsert: true })
}
catch(e){
await db.update({ name:site.name}, { $set: {
lastChecked:Date.now(),
lastHealth:'Bad',
reason:e.message
}
}, { upsert: true })
}
})
},
}