add response parser
This commit is contained in:
parent
83d0a84a6d
commit
8bc8f5551c
@ -31,21 +31,37 @@ export function createAiScriptEnv(opts) {
|
|||||||
return utils.jsToVal(res);
|
return utils.jsToVal(res);
|
||||||
}),
|
}),
|
||||||
'Mk:restApi': values.FN_NATIVE(async ([url, method, body, headers]) => {
|
'Mk:restApi': values.FN_NATIVE(async ([url, method, body, headers]) => {
|
||||||
|
const init: {method?: string, body?: string, headers?: Headers} = new Object();
|
||||||
utils.assertString(url);
|
utils.assertString(url);
|
||||||
utils.assertString(method);
|
if (method) {
|
||||||
utils.assertString(body);
|
utils.assertString(method);
|
||||||
utils.assertObject(headers);
|
init.method = method.value;
|
||||||
|
}
|
||||||
const typedHeaders = new Headers();
|
if (body) {
|
||||||
headers.value.forEach((value, key) => {
|
utils.assertString(body);
|
||||||
typedHeaders.set(key, utils.valToString(value));
|
init.body = body.value;
|
||||||
});
|
}
|
||||||
const response = await fetch(url.value, {
|
if (headers) {
|
||||||
method: method.value,
|
utils.assertObject(headers);
|
||||||
headers: typedHeaders,
|
const typedHeaders = new Headers();
|
||||||
body: body.value,
|
headers.value.forEach((value, key) => {
|
||||||
});
|
typedHeaders.set(key, utils.valToString(value));
|
||||||
return utils.jsToVal(response.json());
|
});
|
||||||
|
init.headers = typedHeaders;
|
||||||
|
}
|
||||||
|
const response = await fetch(url.value, init);
|
||||||
|
const contentType = response.headers.get('Content-Type');
|
||||||
|
if (contentType === null) {
|
||||||
|
return utils.jsToVal(await response.text());
|
||||||
|
}
|
||||||
|
if (contentType.includes('application/json')) {
|
||||||
|
return utils.jsToVal(await response.json());
|
||||||
|
}
|
||||||
|
if (contentType.includes('application/xml') || contentType.includes('text/xml')) {
|
||||||
|
const parser = new DOMParser();
|
||||||
|
return utils.jsToVal(parser.parseFromString((await response.text()), 'application/xml'));
|
||||||
|
}
|
||||||
|
return utils.jsToVal(await response.text());
|
||||||
}),
|
}),
|
||||||
'Mk:save': values.FN_NATIVE(([key, value]) => {
|
'Mk:save': values.FN_NATIVE(([key, value]) => {
|
||||||
utils.assertString(key);
|
utils.assertString(key);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user