sync-request-curl
Version:
Fast way to send synchronous web requests in NodeJS. API is a subset of sync-request. Leverages node-libcurl for high performance. Cannot be used in a browser.
62 lines (59 loc) • 2.03 kB
JavaScript
import { CurlCode } from 'node-libcurl';
export const handleQs = (url, qs) => {
const urlObj = new URL(url);
Object.entries(qs).forEach(([key, value]) => {
if (Array.isArray(value)) {
urlObj.searchParams.delete(key);
value.forEach((item, i) => urlObj.searchParams.append(`${key}[${i}]`, String(item)));
}
else if (value === null) {
urlObj.searchParams.set(key, '');
}
else if (value !== undefined) {
urlObj.searchParams.set(key, String(value));
}
});
urlObj.search = urlObj.searchParams.toString();
return urlObj.href;
};
export const parseIncomingHeaders = (headers) => {
return headers
? Object.entries(headers)
.filter(([_, value]) => value !== undefined)
.map(([key, value]) => value === '' ? `${key};` : `${key}: ${value}`)
: [];
};
export const parseReturnedHeaders = (headerLines) => {
return headerLines.reduce((acc, header) => {
const [name, ...values] = header.split(':');
if (name && values.length > 0) {
acc[name.trim()] = values.join(':').trim();
}
return acc;
}, {});
};
export const checkValidCurlCode = (code, method, url, options) => {
if (code !== CurlCode.CURLE_OK) {
throw new Error(`
Curl request failed with code ${code}
Please look up libcurl error code!
- https://curl.se/libcurl/c/libcurl-errors.html
DEBUG: {
method: "${method}",
url: "${url}",
options: ${JSON.stringify(options)}
}
`);
}
};
export const checkGetBodyStatus = (statusCode, body) => {
if (statusCode >= 300) {
throw new Error(`
Server responded with status code ${statusCode}
Body: ${body.toString()}
Use 'res.body' instead of 'res.getBody()' to not have any errors thrown.
The status code (in this case, ${statusCode}) can be checked manually with res.statusCode.
`);
}
};
//# sourceMappingURL=utils.js.map