All files / src/controllers github_controller.ts

10.86% Statements 5/46
0% Branches 0/14
0% Functions 0/3
10.86% Lines 5/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94      7x 7x   7x                                                                               7x                                                 7x                                            
import axios from 'axios';
import { Request, Response } from 'express';
 
const clientId = process.env.GITHUB_CLIENT_ID;
const clientSecret = process.env.GITHUB_CLIENT_SECRET;
 
export const handleGitHubOAuth = async (req: Request, res: Response) => {
    const { code } = req.body;
 
    if (!code) {
        return res.status(400).json({ error: 'Authorization code is required' });
    }
 
    try {
        const tokenResponse = await axios.post('https://github.com/login/oauth/access_token', {
            headers: { 'Content-Type': 'application/json' },
            client_id: clientId,
            client_secret: clientSecret,
            code: code,
        }) as any;
 
        const tokenData = await tokenResponse.data;
        const params = new URLSearchParams(tokenData);
        const accessToken = params.get('access_token');
 
        if (!accessToken) {
            return res.status(400).json({ error: 'Failed to retrieve access token' });
        }
 
        const userResponse = await axios.get('https://api.github.com/user', {
            headers: { Authorization: `Bearer ${accessToken}` },
        }) as {status: number, data: { login?: string }, json: () => Promise<any>};
 
        if (userResponse.status !== 200) {
            const errorText = await userResponse.data;
            return res.status(400).json({ error: errorText });
        }
 
        const userData = await userResponse.data;
        res.json({ username: userData.login });
    } catch (error) {
        console.error('Error during GitHub OAuth:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
};
 
export const fetchGitHubRepos = async (req: Request, res: Response) => {
    const { username } = req.params;
    const { accessToken } = req.query; // Optional access token for authenticated requests
 
    try {
        const apiUrl = `https://api.github.com/users/${username}/repos`;
 
        const headers = accessToken
            ? { Authorization: `Bearer ${accessToken}` }
            : undefined;
 
        const response = await axios.get(apiUrl, { headers }) as { data: any, status: number };
 
        if (response.status !== 200) {
            return res.status(400).json({ error: `Error fetching repos: ${response.status}` });
        }
 
        const repos = await response.data;
        res.json(repos);
    } catch (error) {
        console.error('Error fetching repos:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
};
 
export const fetchRepoLanguages = async (req: Request, res: Response) => {
    const { repoUrl } = req.query;
 
    if (!repoUrl) {
        return res.status(400).json({ error: 'Repository URL is required' });
    }
 
    try {
        // Convert the repoUrl to the GitHub API URL if necessary
        const apiUrl = (repoUrl as string).replace('https://github.com/', 'https://api.github.com/repos/');
        const response = await axios.get(`${apiUrl}/languages`);
 
        if (response.status !== 200) {
            return res.status(400).json({ error: `Error fetching languages: ${response.statusText}` });
        }
 
        res.json(response.data);
    } catch (error) {
        console.error('Error fetching languages:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
};