-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
99 lines (84 loc) · 2.24 KB
/
api.js
File metadata and controls
99 lines (84 loc) · 2.24 KB
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
'use strict'
const debug = require('debug')('bugverse:api:routes')
const express = require('express')
const db = require('bugverse-db')
const config = require('./config')
const asyncify = require('express-asyncify')
const auth = require('express-jwt')
const guard = require('express-jwt-permissions')()
const api = asyncify(express.Router())
let services, Agent, Metric
api.use('*', async (req, res, next) => {
if (!services) {
debug('connecting to database')
try {
services = await db(config.db)
} catch (e) {
return next(e)
}
Agent = services.Agent
Metric = services.Metric
}
next()
})
api.get('/agents', auth(config.auth) , async (req, res, next) => {
debug(' A request has come to /agents')
const { user } = req
if(!user || !user.username){
return next(new Error('Not Autorized'))
}
let agents = []
try {
if(user.admin){
agents = await Agent.findConnected()
} else {
agents = await Agent.findByUserName(user.username)
}
} catch (e) {
return next(e)
}
res.send(agents)
})
api.get('/agent/:uuid', async (req, res, next) => {
const {uuid} = req.params
debug(`request to /agent/${uuid}`)
let agent
try {
agent = await Agent.findByUuid(uuid)
} catch (e) {
return next(e)
}
if (!agent) {
return next(new Error(`Agent not found with uuid ${uuid}`))
}
res.send(agent)
})
api.get('/metrics/:uuid', auth(config.auth), guard.check(['metrics:read']), async (req, res, next) => {
const { uuid } = req.params
debug(`request to /metrics/${uuid}`)
let metrics = null
try {
metrics = await Metric.findByAgentUuid(uuid)
} catch (e) {
return next(e)
}
if (!metrics || metrics.length === 0) {
return next(new Error(`Metrics not found for agent with uuid ${uuid}`))
}
res.send(metrics)
})
api.get('/metrics/:uuid/:type', async (req, res, next) => {
const { uuid, type } = req.params
debug(`request to /metrics/${uuid}/${type}`)
let metrics = []
try {
metrics = await Metric.findByTypeAgentUuid(type, uuid)
} catch (e) {
return next(e)
}
if (!metrics || metrics.length === 0) {
return next(new Error(`Metrics (${type}) not found for agent with uuid ${uuid}`))
}
res.send(metrics)
})
module.exports = api