npm / npm-registry-fetch

like fetch() but for the npm registry
Other
132 stars 41 forks source link

[QUESTION] How should body option be formatted? #34

Open markcellus opened 4 years ago

markcellus commented 4 years ago

Hey @isaacs. Trying to use package. But I'm not quite sure if I'm using it correctly 😀 . when trying to pass the contents of package-lock.json to opts.body like this...

  const json = await npmFetch.json('/-/npm/v1/security/audits',  {
    method: 'POST',
    body: packageLockJsonContents, // this is just the contents of a package-lock.json parsed as an object
  });
  console.log(JSON.stringify(json, '', 3));

But I get the following error:

Failed to fetch audit report for repo npm. status: 400 cause: {"statusCode":400,"error":"Bad Request","message":"Invalid request payload input"}

How should the opts.body be formatted? Thanks!

sosoba commented 3 years ago

What is

typeof packageLockJsonContents

?

markcellus commented 3 years ago

object. But I was assuming the package would automatically JSON.stringify with proper content-type.

markcellus commented 3 years ago

sorry didn't mean to close this

illicit-oblivion commented 2 years ago

How come it is not still answered? How to use it? What should be the type of body option?

sparrowt commented 4 days ago

The code here in npm cli gives some clues as to the expected structure, which it then passes to /-/npm/v1/security/audits/quick (it only does this if calling the bulk API endpoint /-/npm/v1/security/advisories/bulk failed just before; that one accepts a different format which comes from prepareBulkData in the same file).

I can't find any source for this but I have a feeling that /-/npm/v1/security/audits accepts very similar (if not identical) structure to /-/npm/v1/security/audits/quick.

sparrowt commented 4 days ago

FWIW I had success with the following code snippet, which demonstrates the body internals that the 'audits' API expects and shows how to do a simple "are there any vulns/advisories?" lookup for 1 package, in this case cookie:

// Actually you can omit the line below now that `fetch` is a built-in global, enabled by default since Node 18.
// const fetch = require('node-fetch');

const body = {
    'name': 'package-which-depends-on-cookie-but-this-string-is-irrelevant',
    'version': '0.0.0',
    'requires': {
        'cookie': '^0.4.2'
    },
    'dependencies': {
        'cookie': {
            'version': '0.4.2'
        }
    }
};

fetch('https://registry.npmjs.org/-/npm/v1/security/audits', {
    method: 'POST',
    body: JSON.stringify(body),
    headers: {'Content-Type': 'application/json'}
})
.then(res => {
    return res.json();
})
.then(res => {
    console.log(JSON.stringify(res, null, 2));
})
.catch(err => console.error(err));