@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.
54 lines (53 loc) • 1.77 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.getJSON = getJSON;
exports.deleteJSON = deleteJSON;
exports.putJSON = putJSON;
exports.postJSON = postJSON;
const fetch_1 = require("./fetch");
const schema_validation_error_1 = require("./schema-validation-error");
function getJSON(url, options) {
return requestJSON('GET', url, options);
}
function deleteJSON(url, options) {
return requestJSON('DELETE', url, options);
}
function putJSON(url, options) {
return requestJSON('PUT', url, options);
}
function postJSON(url, options) {
return requestJSON('POST', url, options);
}
async function requestJSON(method, url, options = {}) {
options.headers = options.headers || {};
options.headers.Accept = 'application/json';
if (options.body) {
options.headers['Content-Type'] = 'application/json';
if (typeof options.body !== 'string') {
options.body = JSON.stringify(options.body);
}
}
const result = await (0, fetch_1.request)(method, url, options);
const contentType = result.headers.get('content-type');
let parsedResult;
if (contentType && contentType.startsWith('application/json')) {
parsedResult = await result.json();
}
else {
parsedResult = await result.text();
}
if (options && 'schema' in options) {
return validateSchema(options.schema, parsedResult);
}
return parsedResult;
}
async function validateSchema(schema, input) {
let result = schema['~standard'].validate(input);
if (result instanceof Promise) {
result = await result;
}
if (result.issues) {
throw new schema_validation_error_1.SchemaValidationError(result.issues);
}
return result.value;
}
;