From 36b28bae93cb4fc469d32544f692e9911711d644 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Birk=20Jernstr=C3=B6m?= Date: Tue, 16 Jul 2024 14:04:40 +0200 Subject: [PATCH] fix(polar): Implement updates to Polar API (#80) --- README.md | 1 - src/providers/polar.ts | 32 ++++++++++++++++++++++++-------- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 7fa6c03..dfb8f38 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,6 @@ SPONSORKIT_AFDIAN_TOKEN= ; Get your token at https://polar.sh/settings SPONSORKIT_POLAR_TOKEN= ; The name of the organization to fetch sponsorships from. -; If not set, it will fetch the sponsorships of the user. SPONSORKIT_POLAR_ORGANIZATION= ``` diff --git a/src/providers/polar.ts b/src/providers/polar.ts index e786624..b92a47f 100644 --- a/src/providers/polar.ts +++ b/src/providers/polar.ts @@ -11,27 +11,43 @@ export const PolarProvider: Provider = { export async function fetchPolarSponsors(token: string, organization?: string): Promise { if (!token) throw new Error('Polar token is required') + if (!organization) + throw new Error('Polar organization is required') const apiFetch = ofetch.create({ - baseURL: 'https://api.polar.sh/api/v1', + baseURL: 'https://api.polar.sh/v1', headers: { Authorization: `Bearer ${token}` }, }) /** - * First fetch the list of all subscriptions. This is a paginated + * Get the organization by config name. Fetching the ID for future API calls. + * + * For backward compatability with existing configs, improved readability & DX, + * we keep config.polar.organization vs. introducing config.polar.organization_id even + * though we only need the ID. + */ + const org = await apiFetch('/organizations', { + params: { + name: organization, + }, + }) + const orgId = org.items?.[0]?.id + if (!orgId) + throw new Error(`Polar organization "${organization}" not found`) + + /** + * Fetch the list of all subscriptions. This is a paginated * endpoint so loop through all the pages */ let page = 1 let pages = 1 const subscriptions = [] do { - const params: Record = { page } - if (organization) { - params.organization_name = organization - // Polar only supports GitHub for now - params.platform = 'github' + const params: Record = { + organization_id: orgId, + page, } - const subs = await apiFetch('/subscriptions/subscriptions/search', { params }) + const subs = await apiFetch('/subscriptions', { params }) subscriptions.push(...subs.items) pages = subs.pagination.max_page