From 76eeb3d56bd58648a1dddf50be22a4491a378302 Mon Sep 17 00:00:00 2001 From: Amio Date: Fri, 31 May 2019 16:03:21 +0800 Subject: [PATCH] Migrate vs-marketplace badge to v2 --- endpoints/vs-marketplace.ts | 86 +++++++++++++++++++++++++++++++++++++ libs/examples.ts | 1 + 2 files changed, 87 insertions(+) create mode 100644 endpoints/vs-marketplace.ts diff --git a/endpoints/vs-marketplace.ts b/endpoints/vs-marketplace.ts new file mode 100644 index 0000000..0329192 --- /dev/null +++ b/endpoints/vs-marketplace.ts @@ -0,0 +1,86 @@ +import millify from 'millify' +import got from '../libs/got' +import { version as v, versionColor } from '../libs/utils' +import { + badgenServe, + BadgenServeMeta as Meta, + BadgenServeHandlers as Handlers, + BadgenServeHandlerArgs as Args +} from '../libs/badgen-serve' + +export const meta: Meta = { + title: 'Visual Studio Marketplace', + examples: { + '/vs-marketplace/v/vscodevim.vim': 'version', + '/vs-marketplace/i/vscodevim.vim': 'installs', + '/vs-marketplace/d/vscodevim.vim': 'downloads', + '/vs-marketplace/rating/vscodevim.vim': 'rating', + } +} + +export const handlers: Handlers = { + '/vs-marketplace/:topic/:pkg': handler +} + +export default badgenServe(handlers) + +async function handler ({ topic, pkg }: Args) { + const { results } = await queryVSM(pkg) + const extension = results[0].extensions[0] + + if (!extension) { + return { + subject: 'VS Marketplace', + status: 'not found', + color: 'grey' + } + } + + switch (topic) { + case 'v': + const version = extension.versions[0].version + return { + subject: 'VS Marketplace', + status: v(version), + color: versionColor(version) + } + case 'd': + const { install, updateCount } = parseStatistics(extension) + return { + subject: 'downloads', + status: millify(install + updateCount), + color: 'green' + } + case 'i': + return { + subject: 'installs', + status: millify(parseStatistics(extension).install), + color: 'green' + } + case 'rating': + const { averagerating, ratingcount } = parseStatistics(extension) + return { + subject: 'rating', + status: `${averagerating.toFixed(1)}/5 (${ratingcount})`, + color: 'green' + } + } +} + +const queryVSM = async pkgName => { + const endpoint = 'https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery' + return got.post(endpoint, { + query: { 'api-version': '3.0-preview.1' }, + body: { + filters: [{ criteria: [{ filterType: 7, value: pkgName }] }], + flags: 914 + } + }).then(res => res.body) +} + +const parseStatistics = extension => { + return extension.statistics.reduce((accu, curr) => { + accu[curr.statisticName] = curr.value + return accu + }, {}) +} diff --git a/libs/examples.ts b/libs/examples.ts index 6d204a4..b5121f6 100644 --- a/libs/examples.ts +++ b/libs/examples.ts @@ -23,6 +23,7 @@ const liveBadgeExampleList = [ 'rubygems', 'apm', 'hackage', + 'vs-marketplace', // CI 'appveyor', // quality & metrics