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
46 lines (41 loc) · 1.31 KB
/
[...pkg].get.ts
File metadata and controls
46 lines (41 loc) · 1.31 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
44
45
46
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' })
}
const packageName = decodeURIComponent(pkgParam)
try {
const parsed = await fetchNpmVersionDownloadsFromApi(packageName)
if (parsed.versions.length === 0) {
throw createError({
statusCode: 502,
message: 'Failed to fetch version download data',
})
}
return {
packageName,
source: 'npm-api',
sourceUrl: `https://api.npmjs.org/versions/${encodePackageName(packageName)}/last-week`,
fetchedAt: new Date().toISOString(),
weeklyDownloads: parsed.weeklyDownloads,
versions: parsed.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}`
},
},
)