Last active
April 13, 2017 14:36
-
-
Save elmasse/21c6324cf53016f07c81ad7c008ede24 to your computer and use it in GitHub Desktop.
webtaks slack bot npm 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 latest'; | |
const express = require('express'); | |
const request = require('request'); | |
const moment = require('moment'); | |
const { fromExpress } = require('webtask-tools'); | |
const app = express(); | |
app.get('/', (req, res)=> { | |
const period = `last-month`; | |
const { text } = req.query; | |
const packageName = text; | |
if (!packageName) { | |
res.status(500).send('You need to tell me which package!') | |
} | |
request(`https://api.npmjs.org/downloads/range/${period}/${packageName}`, (error, response, body) => { | |
if (error) { | |
return res.status(500).send('Ups!.. something was wrong'); | |
} | |
const {error:apiError, downloads, end} = JSON.parse(body); | |
if (apiError) { | |
return res.status(500).send(apiError); | |
} | |
const stat = stats(downloads, end); | |
res.send(`Downloads for <https://www.npmjs.com/${packageName}|${packageName}> *${stat.day}* _last day_ *${stat.week}* _last week_ and *${stat.month}* _last month_`); | |
}); | |
}); | |
const stats = (downloads, end) => { | |
const lastDay = moment(end); | |
const lastWeek = lastDay.clone().subtract(7, 'days'); | |
const day = downloads.filter((v) => moment(v.day).isSame(lastDay, 'day')).map((v)=> { console.log(v); return v.downloads}).reduce((prev, curr)=> prev+curr, 0); | |
const week = downloads.filter((v) => moment(v.day).isAfter(lastWeek)).map((v)=> v.downloads).reduce((prev, curr)=> prev+curr); | |
const month = downloads.map((v)=> v.downloads).reduce((prev, curr)=> prev+curr); | |
return { | |
day, | |
week, | |
month | |
}; | |
} | |
module.exports = fromExpress(app); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment