forked from sveltejs/community-legacy
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add script to update npm stats for code resources
- Loading branch information
Showing
2 changed files
with
66 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
// Fetches and updates the number of monthly npm downloads on each resource. | ||
// api docs: https://github.com/npm/registry/blob/master/docs/download-counts.md | ||
|
||
const fs = require("fs"); | ||
const yaml = require("js-yaml"); | ||
const fetch = require("node-fetch"); | ||
|
||
const filePath = "data/code.yml"; | ||
const period = "point/last-month"; | ||
const extractNpmPackage = resource => { | ||
const matches = resource.name.match(/^`(.+)`$/); | ||
return matches && matches[1]; | ||
}; | ||
|
||
async function updateDownloads() { | ||
const data = yaml.safeLoad(fs.readFileSync(filePath, "utf8")); | ||
|
||
const updatedResources = []; | ||
for (const resource of data.resources) { | ||
const npmPackage = extractNpmPackage(resource); | ||
if (!npmPackage) { | ||
updatedResources.push(resource); | ||
continue; | ||
} | ||
|
||
let result = await fetch( | ||
`https://api.npmjs.org/downloads/${period}/${npmPackage}` | ||
); | ||
result = await result.json(); | ||
|
||
if (result.error) { | ||
if (result.error.includes("not found")) { | ||
throw Error( | ||
`npm package "${npmPackage}" not found.` + | ||
" If the resource is not supposed to be an npm package," + | ||
" remove the backticks from its name." | ||
); | ||
} else { | ||
throw Error(`npm error: ${JSON.stringify(result)}`); | ||
} | ||
} | ||
|
||
updatedResources.push({ | ||
...resource, | ||
downloads: result.downloads | ||
}); | ||
console.log(`updated ${npmPackage}`); | ||
} | ||
|
||
const finishedYaml = { | ||
...data, | ||
resources: updatedResources | ||
}; | ||
|
||
fs.writeFile(filePath, yaml.safeDump(finishedYaml), err => { | ||
if (err) { | ||
console.log(err); | ||
} | ||
}); | ||
} | ||
|
||
updateDownloads() | ||
.then(() => console.log("done!")) | ||
.catch(err => console.error(err)); |