Skip to content

Commit

Permalink
fix: handle npm search api window
Browse files Browse the repository at this point in the history
Npm search api windows the results to max 250 results, so keep
fetching repeatedly until we have retrieved all search results.

Fixes #1881.
  • Loading branch information
tkurki committed Feb 8, 2025
1 parent cb60ce0 commit 81e0284
Showing 1 changed file with 39 additions and 7 deletions.
46 changes: 39 additions & 7 deletions src/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ import path from 'path'
import semver, { SemVer } from 'semver'
import { Config } from './config/config'
import { createDebug } from './debug'
import { nextTick } from 'process'
const debug = createDebug('signalk:modules')
const npmDebug = createDebug('signalk:modules:npm')

interface ModuleData {
module: string
Expand Down Expand Up @@ -219,13 +221,12 @@ function findModulesWithKeyword(keyword: string): Promise<NpmModuleData[]> {
return
}

fetch(
'http://registry.npmjs.org/-/v1/search?size=250&text=keywords:' + keyword
)
.then((r) => r.json())
.then((parsed) => {
const data = parsed.results || parsed.objects || []
const result = data.reduce(
searchByKeyword(keyword)
.then((moduleData) => {
npmDebug(
`npm search returned ${moduleData.length} modules with keyword ${keyword}`
)
const result = moduleData.reduce(
(
acc: { [packageName: string]: NpmModuleData },
module: NpmModuleData
Expand Down Expand Up @@ -254,6 +255,37 @@ function findModulesWithKeyword(keyword: string): Promise<NpmModuleData[]> {
})
}

function searchByKeyword(keyword: string): Promise<NpmModuleData[]> {
return new Promise((resolve, reject) => {
let fetchedCount = 0
let toFetchCount = 1
let moduleData: NpmModuleData[] = []
const npmFetch = () => {
npmDebug(
`searching ${keyword} from ${fetchedCount + 1} of ${toFetchCount}`
)
fetch(
`http://registry.npmjs.org/-/v1/search?size=250&from=${
fetchedCount > 0 ? fetchedCount : 0
}&text=keywords:${keyword}`
)
.then((r) => r.json())
.then((parsed) => {
moduleData = moduleData.concat(parsed.objects)
fetchedCount += parsed.objects.length
toFetchCount = parsed.total
if (fetchedCount < toFetchCount) {
nextTick(() => npmFetch())
} else {
resolve(moduleData)
}
})
.catch(reject)
}
npmFetch()
})
}

function doFetchDistTags() {
return fetch('http://registry.npmjs.org/-/package/signalk-server/dist-tags')
}
Expand Down

0 comments on commit 81e0284

Please sign in to comment.