forked from npmx-dev/npmx.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path[...pkg].get.ts
More file actions
43 lines (39 loc) · 1.06 KB
/
[...pkg].get.ts
File metadata and controls
43 lines (39 loc) · 1.06 KB
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
import { CACHE_MAX_AGE_ONE_HOUR } from '#shared/utils/constants'
import { fetchNpmVersionDownloadsFromApi } from '#server/utils/npm-website-versions'
export default defineCachedEventHandler(
async event => {
const pkgParam = getRouterParam(event, 'pkg')
if (!pkgParam) {
throw createError({ statusCode: 404, message: 'Package name is required' })
}
let packageName: string
try {
packageName = decodeURIComponent(pkgParam)
} catch {
throw createError({
statusCode: 400,
message: 'Invalid package name',
})
}
try {
const versions = await fetchNpmVersionDownloadsFromApi(packageName)
return {
packageName,
versions,
}
} catch (error: unknown) {
handleApiError(error, {
statusCode: 502,
message: 'Failed to fetch version download data from npm API',
})
}
},
{
maxAge: CACHE_MAX_AGE_ONE_HOUR,
swr: true,
getKey: event => {
const pkg = getRouterParam(event, 'pkg') ?? ''
return `npmjs-versions:v2:${pkg}`
},
},
)