214 lines
6.3 KiB
JavaScript
Raw Normal View History

import utils from './utils.js';
import ValidationError from "./validation_error.js";
2019-05-05 10:59:34 +02:00
const REQUEST_LOGGING_ENABLED = false;
2020-11-23 22:52:48 +01:00
async function getHeaders(headers) {
2022-12-01 13:07:23 +01:00
const appContext = (await import('../components/app_context.js')).default;
2021-05-22 12:35:41 +02:00
const activeNoteContext = appContext.tabManager ? appContext.tabManager.getActiveContext() : null;
2020-11-23 22:52:48 +01:00
// headers need to be lowercase because node.js automatically converts them to lower case
// also avoiding using underscores instead of dashes since nginx filters them out by default
2019-10-19 15:12:25 +02:00
const allHeaders = {
'trilium-component-id': glob.componentId,
'trilium-local-now-datetime': utils.localNowDateTime(),
2021-05-22 12:26:45 +02:00
'trilium-hoisted-note-id': activeNoteContext ? activeNoteContext.hoistedNoteId : null,
2020-01-28 21:54:28 +01:00
'x-csrf-token': glob.csrfToken
};
2020-01-28 21:54:28 +01:00
for (const headerName in headers) {
if (headers[headerName]) {
allHeaders[headerName] = headers[headerName];
}
}
if (utils.isElectron()) {
// passing it explicitely here because of the electron HTTP bypass
2019-10-19 15:12:25 +02:00
allHeaders.cookie = document.cookie;
}
2019-10-19 15:12:25 +02:00
return allHeaders;
}
async function get(url, componentId) {
return await call('GET', url, null, {'trilium-component-id': componentId});
}
async function post(url, data, componentId) {
return await call('POST', url, data, {'trilium-component-id': componentId});
}
async function put(url, data, componentId) {
return await call('PUT', url, data, {'trilium-component-id': componentId});
}
2022-01-10 17:09:20 +01:00
async function patch(url, data, componentId) {
return await call('PATCH', url, data, {'trilium-component-id': componentId});
}
async function remove(url, componentId) {
return await call('DELETE', url, null, {'trilium-component-id': componentId});
}
let i = 1;
const reqResolves = {};
2021-02-14 11:43:31 +01:00
const reqRejects = {};
let maxKnownEntityChangeId = 0;
2019-10-19 15:12:25 +02:00
async function call(method, url, data, headers = {}) {
let resp;
const start = Date.now();
2020-11-23 22:52:48 +01:00
headers = await getHeaders(headers);
2018-03-24 23:37:55 -04:00
if (utils.isElectron()) {
2020-04-12 14:22:51 +02:00
const ipc = utils.dynamicRequire('electron').ipcRenderer;
const requestId = i++;
resp = await new Promise((resolve, reject) => {
reqResolves[requestId] = resolve;
2021-02-14 11:43:31 +01:00
reqRejects[requestId] = reject;
2019-05-05 10:59:34 +02:00
if (REQUEST_LOGGING_ENABLED) {
console.log(utils.now(), `Request #${requestId} to ${method} ${url}`);
2019-05-05 10:59:34 +02:00
}
ipc.send('server-request', {
requestId: requestId,
2020-11-23 22:52:48 +01:00
headers: headers,
method: method,
url: `/${baseApiUrl}${url}`,
data: data
});
});
}
else {
resp = await ajax(url, method, data, headers);
}
const end = Date.now();
if (glob.PROFILING_LOG) {
console.log(`${method} ${url} took ${end - start}ms`);
}
const maxEntityChangeIdStr = resp.headers['trilium-max-entity-change-id'];
if (maxEntityChangeIdStr && maxEntityChangeIdStr.trim()) {
maxKnownEntityChangeId = Math.max(maxKnownEntityChangeId, parseInt(maxEntityChangeIdStr));
}
return resp.body;
}
2022-12-18 16:12:29 +01:00
async function reportError(method, url, statusCode, response) {
2021-02-14 11:43:31 +01:00
const toastService = (await import("./toast.js")).default;
2022-12-22 14:57:00 +01:00
let message = response;
2022-12-18 16:12:29 +01:00
if (typeof response === 'string') {
try {
response = JSON.parse(response);
2022-12-22 14:57:00 +01:00
message = response.message;
2022-12-18 16:12:29 +01:00
}
2022-12-22 14:57:00 +01:00
catch (e) {}
2022-12-18 16:12:29 +01:00
}
if ([400, 404].includes(statusCode) && response && typeof response === 'object') {
2022-12-22 14:57:00 +01:00
toastService.showError(message);
throw new ValidationError(response);
2022-12-18 16:12:29 +01:00
} else {
2022-12-22 14:57:00 +01:00
const title = `${statusCode} ${method} ${url}`;
toastService.showErrorTitleAndMessage(title, message);
toastService.throwError(`${title} - ${message}`);
}
2021-02-14 11:43:31 +01:00
}
function ajax(url, method, data, headers) {
return new Promise((res, rej) => {
const options = {
url: baseApiUrl + url,
type: method,
2020-11-23 22:52:48 +01:00
headers: headers,
timeout: 60000,
success: (body, textStatus, jqXhr) => {
const respHeaders = {};
jqXhr.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(line => {
const parts = line.split(': ');
const header = parts.shift();
respHeaders[header] = parts.join(': ');
});
res({
body,
headers: respHeaders
});
},
2022-12-18 16:12:29 +01:00
error: async jqXhr => {
await reportError(method, url, jqXhr.status, jqXhr.responseText);
rej(jqXhr.responseText);
}
};
if (data) {
try {
options.data = JSON.stringify(data);
} catch (e) {
console.log("Can't stringify data: ", data, " because of error: ", e)
}
options.contentType = "application/json";
2018-03-27 21:46:38 -04:00
}
$.ajax(options);
});
}
2018-04-05 23:17:19 -04:00
if (utils.isElectron()) {
2020-04-12 14:22:51 +02:00
const ipc = utils.dynamicRequire('electron').ipcRenderer;
2018-03-25 13:13:26 -04:00
2021-02-14 11:43:31 +01:00
ipc.on('server-response', async (event, arg) => {
2019-05-05 10:59:34 +02:00
if (REQUEST_LOGGING_ENABLED) {
console.log(utils.now(), `Response #${arg.requestId}: ${arg.statusCode}`);
2019-05-05 10:59:34 +02:00
}
2018-03-25 13:13:26 -04:00
2021-02-14 11:43:31 +01:00
if (arg.statusCode >= 200 && arg.statusCode < 300) {
if (arg.headers['Content-Type'] === 'application/json') {
arg.body = JSON.parse(arg.body);
}
if (!(arg.requestId in reqResolves)) {
// this can happen when reload happens between firing up the request and receiving the response
throw new Error(`Unknown requestId="${arg.requestId}"`);
}
2021-02-14 11:43:31 +01:00
reqResolves[arg.requestId]({
body: arg.body,
headers: arg.headers
});
}
else {
await reportError(arg.method, arg.url, arg.statusCode, arg.body);
reqRejects[arg.requestId]();
}
2018-03-25 13:13:26 -04:00
2018-04-05 23:17:19 -04:00
delete reqResolves[arg.requestId];
2021-02-14 11:43:31 +01:00
delete reqRejects[arg.requestId];
2018-04-05 23:17:19 -04:00
});
}
2018-03-25 13:13:26 -04:00
export default {
get,
post,
put,
2022-01-10 17:09:20 +01:00
patch,
remove,
ajax,
// don't remove, used from CKEditor image upload!
getHeaders,
getMaxKnownEntityChangeId: () => maxKnownEntityChangeId
};