@logi.one/rest-client
Version:
This is a free, ultra-lightweight and easy to use rest client for node.js supporting JSON requests and streams with no external dependencies.
42 lines (41 loc) • 1.24 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.get = get;
exports.del = del;
exports.post = post;
exports.put = put;
exports.request = request;
const search_1 = require("./search");
const request_error_1 = require("./request-error");
async function get(url, options) {
return request('GET', url, options);
}
async function del(url, options) {
return request('DELETE', url, options);
}
async function post(url, options) {
return request('POST', url, options);
}
async function put(url, options) {
return request('PUT', url, options);
}
async function request(method, url, options = {}) {
const headers = options.headers || {};
headers['User-Agent'] = headers['User-Agent'] || 'node';
const requestInit = {
headers,
method
};
if (options.body) {
requestInit.body = options.body;
}
if (options.token) {
headers.Authorization = `Bearer ${options.token}`;
}
url = (0, search_1.appendSearchToURL)(url, options.search);
const result = await fetch(url, requestInit);
if (!result.ok) {
throw new request_error_1.RequestError(result.statusText, result.status, result.headers, result);
}
return result;
}
;