Skip to content

Commit

Permalink
[Crates] Implement Dependents Badge (badges#10438)
Browse files Browse the repository at this point in the history
* add dependents service

* remove redundant timeout
  • Loading branch information
erayerdin authored Aug 4, 2024
1 parent bdf84f9 commit a583ca7
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
49 changes: 49 additions & 0 deletions services/crates/crates-dependents.service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import Joi from 'joi'
import { pathParams } from '../index.js'
import { metric } from '../text-formatters.js'
import { nonNegativeInteger } from '../validators.js'
import { BaseCratesService, description } from './crates-base.js'

const dependentsResponseSchema = Joi.object({
meta: Joi.object({
total: nonNegativeInteger,
}).required(),
}).required()

export default class CratesDependents extends BaseCratesService {
static category = 'other'
static route = { base: 'crates/dependents', pattern: ':crate' }

static openApi = {
'/crates/dependents/{crate}': {
get: {
summary: 'Crates.io Dependents',
description,
parameters: pathParams({
name: 'crate',
example: 'tokio',
}),
},
},
}

static render({ dependentCount }) {
return {
label: 'dependents',
message: metric(dependentCount),
color: dependentCount === 0 ? 'orange' : 'brightgreen',
}
}

async fetch({ crate }) {
const url = `https://crates.io/api/v1/crates/${crate}/reverse_dependencies`
const schema = dependentsResponseSchema
return this._requestJson({ schema, url })
}

async handle({ crate }) {
const json = await this.fetch({ crate })
const { total: dependentCount } = json.meta
return this.constructor.render({ dependentCount })
}
}
15 changes: 15 additions & 0 deletions services/crates/crates-dependents.tester.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { isMetric } from '../test-validators.js'
import { createServiceTester } from '../tester.js'
export const t = await createServiceTester()

t.create('dependent count').get('/tokio.json').expectBadge({
label: 'dependents',
message: isMetric,
})

t.create('dependent count (nonexistent package)')
.get('/foobar-is-not-crate.json')
.expectBadge({
label: 'crates.io',
message: 'not found',
})

0 comments on commit a583ca7

Please sign in to comment.