Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consolidate [NpmDownloads] into one service #3318

Merged
merged 1 commit into from
Apr 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 78 additions & 81 deletions services/npm/npm-downloads.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,95 +10,92 @@ const pointResponseSchema = Joi.object({
downloads: nonNegativeInteger,
}).required()

// https://github.com/npm/registry/blob/master/docs/download-counts.md#output-1
const rangeResponseSchema = Joi.object({
downloads: Joi.array()
.items(pointResponseSchema)
.required(),
}).required()

function DownloadsForInterval(interval) {
const { base, messageSuffix = '', query, isRange = false, name } = {
week: {
base: 'npm/dw',
messageSuffix: '/w',
query: 'point/last-week',
name: 'NpmDownloadsWeek',
},
month: {
base: 'npm/dm',
messageSuffix: '/m',
query: 'point/last-month',
name: 'NpmDownloadsMonth',
},
year: {
base: 'npm/dy',
messageSuffix: '/y',
query: 'point/last-year',
name: 'NpmDownloadsYear',
},
total: {
base: 'npm/dt',
query: 'range/1000-01-01:3000-01-01',
isRange: true,
name: 'NpmDownloadsTotal',
},
}[interval]
const intervalMap = {
dw: {
query: 'point/last-week',
schema: pointResponseSchema,
transform: json => json.downloads,
messageSuffix: '/week',
},
dm: {
query: 'point/last-month',
schema: pointResponseSchema,
transform: json => json.downloads,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A little bit of repetition here, though it helps with clarity.

messageSuffix: '/month',
},
dy: {
query: 'point/last-year',
schema: pointResponseSchema,
transform: json => json.downloads,
messageSuffix: '/year',
},
dt: {
query: 'range/1000-01-01:3000-01-01',
// https://github.com/npm/registry/blob/master/docs/download-counts.md#output-1
schema: Joi.object({
downloads: Joi.array()
.items(pointResponseSchema)
.required(),
}).required(),
transform: json =>
json.downloads
.map(item => item.downloads)
.reduce((accum, current) => accum + current),
messageSuffix: '',
},
}

const schema = isRange ? rangeResponseSchema : pointResponseSchema
// This hits an entirely different API from the rest of the NPM services, so
// it does not use NpmBase.
module.exports = class NpmDownloads extends BaseJsonService {
static get category() {
return 'downloads'
}

// This hits an entirely different API from the rest of the NPM services, so
// it does not use NpmBase.
return class NpmDownloads extends BaseJsonService {
static get name() {
return name
static get route() {
return {
base: 'npm',
pattern: ':interval(dw|dm|dy|dt)/:scope(@.+)?/:packageName',
}
}

static get category() {
return 'downloads'
}
static get examples() {
return [
{
title: 'npm',
namedParams: { interval: 'dw', packageName: 'localeval' },
staticPreview: this.render({ interval: 'dw', downloadCount: 30000 }),
keywords: ['node'],
},
]
}

static get route() {
return {
base,
pattern: ':scope(@.+)?/:packageName',
}
}
// For testing.
static get _intervalMap() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea! This makes things easy to test without having to define (and unnecessarily call) a class level render/transform function

return intervalMap
}

static get examples() {
return [
{
title: 'npm',
pattern: ':packageName',
namedParams: { packageName: 'localeval' },
staticPreview: this.render({ downloads: 30000 }),
keywords: ['node'],
},
]
}
static render({ interval, downloadCount }) {
const { messageSuffix } = intervalMap[interval]

static render({ downloads }) {
return {
message: `${metric(downloads)}${messageSuffix}`,
color: downloads > 0 ? 'brightgreen' : 'red',
}
return {
message: `${metric(downloadCount)}${messageSuffix}`,
color: downloadCount > 0 ? 'brightgreen' : 'red',
}
}

async handle({ scope, packageName }) {
const slug = scope ? `${scope}/${packageName}` : packageName
let { downloads } = await this._requestJson({
schema,
url: `https://api.npmjs.org/downloads/${query}/${slug}`,
errorMessages: { 404: 'package not found or too new' },
})
if (isRange) {
downloads = downloads
.map(item => item.downloads)
.reduce((accum, current) => accum + current)
}
return this.constructor.render({ downloads })
}
async handle({ interval, scope, packageName }) {
const { query, schema, transform } = intervalMap[interval]
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like using destructuring here. It makes this code particularly readable and I think a bit less error prone.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 I like this a lot too


const slug = scope ? `${scope}/${packageName}` : packageName
const json = await this._requestJson({
schema,
url: `https://api.npmjs.org/downloads/${query}/${slug}`,
errorMessages: { 404: 'package not found or too new' },
})

const downloadCount = transform(json)

return this.constructor.render({ interval, downloadCount })
}
}

module.exports = ['week', 'month', 'year', 'total'].map(DownloadsForInterval)
25 changes: 25 additions & 0 deletions services/npm/npm-downloads.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict'

const { test, given } = require('sazerac')
const NpmDownloads = require('./npm-downloads.service')

describe('NpmDownloads', function() {
test(NpmDownloads._intervalMap.dt.transform, () => {
given({
downloads: [
{ downloads: 2, day: '2018-01-01' },
{ downloads: 3, day: '2018-01-02' },
],
}).expect(5)
})

test(NpmDownloads.render, () => {
given({
interval: 'dt',
downloadCount: 0,
}).expect({
message: '0',
color: 'red',
})
})
})
48 changes: 14 additions & 34 deletions services/npm/npm-downloads.tester.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
'use strict'

const { ServiceTester } = require('../tester')
const { isMetric } = require('../test-validators')
const { isMetricOverTimePeriod, isMetric } = require('../test-validators')
const t = (module.exports = require('../tester').createServiceTester())

const t = new ServiceTester({
id: 'NpmDownloads',
title: 'NpmDownloads',
pathPrefix: '/npm',
})
module.exports = t
t.create('weekly downloads of left-pad')
.get('/dw/left-pad.json')
.expectBadge({
label: 'downloads',
message: isMetricOverTimePeriod,
color: 'brightgreen',
})

t.create('weekly downloads of @cycle/core')
.get('/dw/@cycle/core.json')
.expectBadge({ label: 'downloads', message: isMetricOverTimePeriod })

t.create('total downloads of left-pad')
.get('/dt/left-pad.json')
Expand All @@ -22,32 +27,7 @@ t.create('total downloads of @cycle/core')
.get('/dt/@cycle/core.json')
.expectBadge({ label: 'downloads', message: isMetric })

t.create('total downloads of package with zero downloads')
.get('/dt/package-no-downloads.json')
.intercept(nock =>
nock('https://api.npmjs.org')
.get('/downloads/range/1000-01-01:3000-01-01/package-no-downloads')
.reply(200, {
downloads: [{ downloads: 0, day: '2018-01-01' }],
})
)
.expectBadge({ label: 'downloads', message: '0', color: 'red' })

t.create('exact total downloads value')
.get('/dt/exact-value.json')
.intercept(nock =>
nock('https://api.npmjs.org')
.get('/downloads/range/1000-01-01:3000-01-01/exact-value')
.reply(200, {
downloads: [
{ downloads: 2, day: '2018-01-01' },
{ downloads: 3, day: '2018-01-02' },
],
})
)
.expectBadge({ label: 'downloads', message: '5' })

t.create('total downloads of unknown package')
t.create('downloads of unknown package')
.get('/dt/npm-api-does-not-have-this-package.json')
.expectBadge({
label: 'downloads',
Expand Down