-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathroute.ts
69 lines (54 loc) · 2.12 KB
/
route.ts
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
import { type NextRequest, NextResponse } from 'next/server'
import { ErrorType } from '~/enums'
import { getValuableStatistics } from '~/helpers'
import { mockGraphData } from '~/mock-data'
import { fetchContributionsCollection, fetchGitHubUser } from '~/services'
import type { GraphData, ResponseData, ValuableStatistics } from '~/types'
interface GetContributionRequestParams {
username: string
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<GetContributionRequestParams> }
) {
const { username } = await params
const statistics = request.nextUrl.searchParams.get('statistics') === 'true'
const { searchParams } = new URL(request.url)
const queryYears = searchParams.getAll('years').map(Number)
if (process.env.NEXT_PUBLIC_DATA_MODE === 'mock') {
return NextResponse.json({ data: mockGraphData }, { status: 200 })
}
try {
const githubUser = await fetchGitHubUser(username)
const contributionYears = githubUser.contributionYears
const filteredYears =
Array.isArray(queryYears) && queryYears.length > 0
? contributionYears.filter((year) => queryYears.includes(year))
: contributionYears
const contributionCalendars = await Promise.all(
filteredYears.map((year) => fetchContributionsCollection(username, year))
)
const graphData: GraphData = {
...githubUser,
contributionYears: filteredYears,
contributionCalendars,
}
let valuableStatistics: ValuableStatistics | undefined
if (statistics) {
valuableStatistics = getValuableStatistics(graphData)
}
const data = valuableStatistics ? { ...graphData, statistics: valuableStatistics } : graphData
return NextResponse.json({ data }, { status: 200 })
} catch (err) {
if (err instanceof Error) {
const errorData: ResponseData = { errorType: ErrorType.BadRequest, message: err.message }
if (err.message === 'Bad credentials') {
return NextResponse.json(
{ ...errorData, errorType: ErrorType.BadCredentials },
{ status: 401 }
)
}
return NextResponse.json(errorData, { status: 400 })
}
}
}