Created
January 26, 2017 00:10
-
-
Save bobbynewmark/177d3395edfb359e47a4a886b12635d8 to your computer and use it in GitHub Desktop.
Simple Hapi Server to query Octopus for deploy stats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const Hapi = require('hapi'); | |
const rp = require('request-promise'); | |
const Boom = require('boom'); | |
const m = require('moment'); | |
const mkOctopusOptions = function(loc) { | |
var url = loc.indexOf("/") == 0 ? process.env.OCTOPUS_URL + loc : process.env.OCTOPUS_URL + '/' + loc; | |
return { | |
uri: url, | |
headers: { | |
'X-Octopus-ApiKey': process.env.OCTOPUS_APIKEY | |
}, | |
json: true // Automatically parses the JSON string in the response | |
}; | |
}; | |
const server = new Hapi.Server(); | |
server.connection({ | |
host: process.env.host || '0.0.0.0', | |
port: process.env.port || 8000 | |
}); | |
const stageMap = { | |
"Environments-1" : "stage", | |
"Environments-41": "peek", | |
"Environments-42": "live", | |
"Environments-81": "live", | |
"Environments-141": "live" | |
}; | |
const getOctopusDeployments = function(deployments, start) { | |
const url = 'deployments?taskState=Success'; | |
if (deployments && !deployments.Links["Page.Next"]) { | |
return deployments; //You are at the end so stop; | |
} | |
else if (deployments) { | |
url = deployments.Links["Page.Next"] + '&taskState=Success'; | |
} | |
return rp(mkOctopusOptions(url)).then(function(resp) { | |
if (!deployments) { | |
return getOctopusDeployments(resp, start); | |
} | |
else { | |
resp.Items = deployments.Items.concat(resp.Items); | |
return getOctopusDeployments(resp, start); | |
} | |
}); | |
}; | |
const paths = '/' + (process.env.MAGIC_NUMBER || "0"); | |
const deploysPath = paths + "/deploys"; | |
server.route({ | |
method:'GET', | |
path: deploysPath, | |
handler: function (request, reply) { | |
let start = m.utc().startOf('month').format('YYYY-MM-DDTHH:mm:ss.000+00:00'); | |
return getOctopusDeployments(null, start) | |
.then(function(deployments) { | |
let result = deployments.Items | |
.filter(function(i) { | |
return i.Created > start; | |
}) | |
.reduce(function(o,i) { | |
let key = stageMap[i.EnvironmentId]; | |
if (key) { | |
o[key]++; | |
} | |
return o; | |
}, {live:0,peek:0,stage:0}); | |
result.start = start; | |
return reply(result); | |
}).catch(function(err) { | |
return reply(Boom.wrap(err)); | |
}); | |
} | |
}); | |
server.start((err) => { | |
if (err) { | |
throw err; | |
} | |
console.log('Server running at:', server.info.uri); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment