mihawk
Version:
A tiny & simple mock server tool, support json,js,cjs,ts(typescript).
42 lines (41 loc) • 2.28 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonRequest = void 0;
function jsonRequest(url, options) {
return __awaiter(this, void 0, void 0, function* () {
const isHttps = url.startsWith('https://');
options = formatOptions(options, isHttps);
const apiRes = yield fetch(url, Object.assign(Object.assign({}, options), { headers: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.headers), { 'Content-Type': 'application/json', Cookie: options.headers.Cookie }) }));
const resContentType = apiRes.headers.get('content-type') || apiRes.headers.get('Content-Type') || '';
if (!resContentType || (!resContentType.includes('application/json') && !resContentType.includes('json') && !resContentType.includes('text'))) {
throw new Error(`Invalid content-type: ${resContentType || 'unknown'}`);
}
const res = yield apiRes.json();
return res;
});
}
exports.jsonRequest = jsonRequest;
function formatOptions(options, isHttps) {
var _a, _b;
options = options || {};
options.method = (options.method || 'GET');
if (['HEAD', 'GET'].includes(options.method.toUpperCase())) {
delete options.body;
}
if ((_a = options.headers) === null || _a === void 0 ? void 0 : _a['Content-Length']) {
delete options.headers['Content-Length'];
}
if ((_b = options.headers) === null || _b === void 0 ? void 0 : _b['content-length']) {
delete options.headers['content-length'];
}
return options;
}