Skip to content

Instantly share code, notes, and snippets.

@Lissy93
Created February 27, 2024 01:17
Show Gist options
  • Save Lissy93/2568a009cf1c9b7ecb801307ebb4ac7b to your computer and use it in GitHub Desktop.
Save Lissy93/2568a009cf1c9b7ecb801307ebb4ac7b to your computer and use it in GitHub Desktop.

Revisions

  1. Lissy93 created this gist Feb 27, 2024.
    66 changes: 66 additions & 0 deletions github-sponsors-api.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    addEventListener('fetch', event => {
    event.respondWith(handleRequest(event.request))
    })

    async function handleRequest(request) {
    const { pathname } = new URL(request.url);
    const username = pathname.split('/')[1];

    if (!username) {
    return new Response(
    'Simple API to fetch GitHub Sponsors of a given user 💖\nUsage: GET /[username]',
    { status: 200 }
    );
    }

    const query = `
    query {
    user(login: "${username}") {
    sponsorshipsAsMaintainer(first: 100) {
    edges {
    node {
    sponsorEntity {
    ... on User {
    login
    name
    avatarUrl
    }
    ... on Organization {
    name
    avatarUrl
    }
    }
    }
    }
    }
    }
    }
    `;

    try {
    const apiResponse = await fetch('https://api.github.com/graphql', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    'Authorization': `bearer ${GH_API_TOKEN}`,
    'User-Agent': 'GetUserSponsors'
    },
    body: JSON.stringify({ query })
    });

    const result = await apiResponse.json();

    if (!apiResponse.ok) {
    throw new Error(result.errors ? result.errors.map(e => e.message).join('; ') : 'Failed to fetch GitHub data');
    }

    // Extracting sponsor details
    const sponsors = result.data.user.sponsorshipsAsMaintainer.edges.map(edge => edge.node.sponsorEntity);

    return new Response(JSON.stringify(sponsors), {
    headers: { 'Content-Type': 'application/json' },
    });
    } catch (error) {
    return new Response(error.message, { status: 500 });
    }
    }