@mochiapp/runner
Version:
A test runner used for Mochi modules.
136 lines (135 loc) • 4.03 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const js_1 = require("@mochiapp/js");
const axios_1 = __importDefault(require("axios"));
const globalObject = global;
const mapAxiosToMochiOptions = (ops) => {
if (ops) {
let body;
if (ops.body) {
if (typeof ops.body !== 'string') {
body = JSON.stringify(ops.body);
}
else {
body = ops.body;
}
}
return {
headers: ops.headers,
timeout: ops.timeout,
data: body,
};
}
else {
return {};
}
};
const mapAxiosToMochiResponse = (req, res) => {
const format = {
data: function () {
let value;
if (typeof res.data === 'string') {
value = res.data;
}
else {
value = JSON.stringify(res.data);
}
const buf = new ArrayBuffer(value.length * 2); // 2 bytes for each char
const bufView = new Uint16Array(buf);
for (let i = 0, strLen = value.length; i < strLen; i++) {
bufView[i] = value.charCodeAt(i);
}
return buf;
},
json: function () {
if (typeof res.data === 'string') {
return JSON.parse(res.data);
}
else {
return res.data;
}
},
text: function () {
if (typeof res.data === 'string') {
return res.data;
}
else {
return JSON.stringify(res.data);
}
},
};
const headers = {};
for (const key of Object.keys(res.headers)) {
const value = res.headers[key];
if (value !== undefined && value !== null) {
if (typeof value === 'string') {
headers[key] = value;
}
else if (typeof value === 'number') {
headers[key] = value.toString();
}
else if (typeof value === 'boolean') {
headers[key] = String(value);
}
else if (Array.isArray(value)) {
headers[key] = value.join(', ');
}
else {
console.log('header is an axiosheader type');
}
}
}
return {
status: res.status,
statusText: res.statusText,
headers: headers,
request: req,
...format,
};
};
const createRequest = () => ({
async get(url, options) {
const req = {
url: url,
method: js_1.MochiRequestMethod.get,
options: options,
};
return axios_1.default
.get(url, mapAxiosToMochiOptions(options))
.then((r) => mapAxiosToMochiResponse(req, r));
},
async post(url, options) {
const req = {
url: url,
method: js_1.MochiRequestMethod.post,
options: options,
};
return axios_1.default
.post(url, mapAxiosToMochiOptions(options))
.then((r) => mapAxiosToMochiResponse(req, r));
},
async put(url, options) {
const req = {
url: url,
method: js_1.MochiRequestMethod.put,
options: options,
};
return axios_1.default
.put(url, mapAxiosToMochiOptions(options))
.then((r) => mapAxiosToMochiResponse(req, r));
},
async patch(url, options) {
const req = {
url: url,
method: js_1.MochiRequestMethod.patch,
options: options,
};
return axios_1.default
.patch(url, mapAxiosToMochiOptions(options))
.then((r) => mapAxiosToMochiResponse(req, r));
},
});
globalObject.request = createRequest();