|
| 1 | +import Joi from 'joi' |
| 2 | +import { metric } from '../text-formatters.js' |
| 3 | +import { BaseJsonService, InvalidResponse, NotFound } from '../index.js' |
| 4 | + |
| 5 | +const schema = Joi.object({ |
| 6 | + entities: Joi.object({ |
| 7 | + user: Joi.object() |
| 8 | + .required() |
| 9 | + .pattern(/^\w+$/, { |
| 10 | + points: Joi.number().allow(null).required(), |
| 11 | + }), |
| 12 | + }).optional(), |
| 13 | +}).required() |
| 14 | + |
| 15 | +/** |
| 16 | + * This badge displays the total number of points a student has accumulated |
| 17 | + * from completing challenges on freeCodeCamp. |
| 18 | + */ |
| 19 | +export default class FreeCodeCampPoints extends BaseJsonService { |
| 20 | + static category = 'other' |
| 21 | + static route = { |
| 22 | + base: 'freecodecamp/points', |
| 23 | + pattern: ':username', |
| 24 | + } |
| 25 | + |
| 26 | + static examples = [ |
| 27 | + { |
| 28 | + title: 'freeCodeCamp points', |
| 29 | + namedParams: { username: 'sethi' }, |
| 30 | + staticPreview: this.render({ points: 934 }), |
| 31 | + }, |
| 32 | + ] |
| 33 | + |
| 34 | + static defaultBadgeData = { label: 'points', color: 'info' } |
| 35 | + |
| 36 | + static render({ points }) { |
| 37 | + return { message: metric(points) } |
| 38 | + } |
| 39 | + |
| 40 | + async fetch({ username }) { |
| 41 | + return this._requestJson({ |
| 42 | + schema, |
| 43 | + url: `https://api.freecodecamp.org/api/users/get-public-profile`, |
| 44 | + options: { |
| 45 | + qs: { |
| 46 | + username, |
| 47 | + }, |
| 48 | + }, |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + static transform(response, username) { |
| 53 | + const { entities } = response |
| 54 | + |
| 55 | + if (entities === undefined) |
| 56 | + throw new NotFound({ prettyMessage: 'profile not found' }) |
| 57 | + |
| 58 | + const { points } = entities.user[username] |
| 59 | + |
| 60 | + if (points === null) throw new InvalidResponse({ prettyMessage: 'private' }) |
| 61 | + |
| 62 | + return points |
| 63 | + } |
| 64 | + |
| 65 | + async handle({ username }) { |
| 66 | + const response = await this.fetch({ username }) |
| 67 | + const points = this.constructor.transform(response, username) |
| 68 | + return this.constructor.render({ points }) |
| 69 | + } |
| 70 | +} |
0 commit comments