Skip to content

Build your personal knowledge base with Trilium Notes

core: log search queries in backend log

Adorian Doranad7504ad7967
diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.json
index f80e5443a1..e9a6fa04f1 100644
--- a/apps/server/src/assets/help/help_content.json
+++ b/apps/server/src/assets/help/help_content.json
@@ -188,7 +188,7 @@
"_help_wy8So3yZZlH9": "<p>Go to <a href=\"https://github.com/TriliumNext/Trilium/issues\">Issues · TriliumNext/Trilium</a> and press “New issue”.</p><p>If you are reporting a bug, select “Bug Report” and fill in the details.</p>",
"_help_x59R8J8KV5Bp": "<p><img src=\"{{helpAssets}}/User%20Guide/Troubleshooting/Anonymized%20Database_image.jpg\"></p><p>In certain scenarios, understanding the structure of a database is crucial for troubleshooting issues. However, sharing your actual <a href=\"#root/_help_wX4HbRucYSDD\">database</a> file with personal notes is not advisable. To address this, Trilium offers a feature to anonymize the database. This feature can be accessed via Menu -&gt; Options -&gt; Advanced tab.</p><p>This feature creates a copy of your database with all sensitive data removed. Specifically, it strips out note titles, contents, revisions, history, and some non-system attributes while retaining the overall structure and metadata, such as modification dates. After anonymization, the database undergoes a <a href=\"https://sqlite.org/lang_vacuum.html\">vacuuming process</a> to ensure no sensitive data remnants remain in the file. The anonymized database is saved in the <code>anonymized</code> directory within the <a href=\"#root/_help_tAassRL4RSQL\">data directory</a>, making it safe to share with bug reports.</p><p>This will create a copy of your document and remove all sensitive data (currently note titles, contents, revisions, history and some of the options, and non-system attributes) while leaving all structure and metadata (e.g. date of last change). After this is done, the database is <a href=\"https://sqlite.org/lang_vacuum.html\">VACUUMed</a> to make sure there's no stale sensitive data in the document file. The resulting file is stored in <code>anonymized</code> directory (placed in the <a href=\"#root/_help_tAassRL4RSQL\">data directory</a>). You can safely attach it to a bug report.</p><h2>Command Line Anonymization</h2><p>If your <a href=\"#root/_help_wX4HbRucYSDD\">database</a> is corrupted to the point where Trilium cannot start, the anonymization process can still be executed via the command line:</p><pre><code class=\"language-text-x-trilium-auto\">node src/anonymize.js</code></pre><p>Run this command from the directory containing Trilium's source files, typically found in the <code>resources/app</code> directory for desktop builds.</p>",
"_help_qzNzp9LYQyPT": "<p>It's important to provide all available error logs together with bug reports.</p><p>There are two types of error logs, both of which are useful when reporting bugs.</p><ul><li><a class=\"reference-link\" href=\"#root/_help_bnyigUA2UK7s\">Backend (server) logs</a></li><li><a class=\"reference-link\" href=\"#root/_help_9yEHzMyFirZR\">Frontend logs</a></li></ul><h2>Providing sensitive data</h2><p>If you don't feel comfortable attaching the logs or anything sensitive to the public GitHub issues, feel free to contact the devs in our Matrix <a href=\"https://github.com/TriliumNext/Trilium#-discuss-with-us\">support channel</a>.</p><p>Use this email to also provide anything which could assist in analysing the bug - e.g. files/images/ZIPs being imported or <a href=\"#root/_help_x59R8J8KV5Bp\">anonymized database</a>.</p><h3>Exporting note subtree for reproduction</h3><p>Often times, bugs manifest themselves in specific notes and having them would greatly ease reproduction and fixing.</p><p>In such case, please export the relevant note subtree by right-clicking it on the left tree, choosing Export - HTML as ZIP:</p><p><img src=\"{{helpAssets}}/User%20Guide/Troubleshooting/Error%20logs_error-logs-export-subtree.png\"></p>",
- "_help_bnyigUA2UK7s": "<h2>Accessing via the backend log</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_x3i7MxGccDuM\">Global menu</a>, go to <em>Advanced</em> → <em>Show backend log</em>. This will display the current backend log (i.e. today's), with the historical information available only on disk (see below).</p><p>The log is colored to make it easier to read: request status codes by class, slow SQL queries, and errors in red. The statement of a slow SQL query is highlighted the same way as in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_YKWqdJhzi2VY\">SQL Console</a>, using the color scheme of code notes (see <em>Color schemes</em> in&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>).</p><p>Interaction since v0.104.0:</p><ul><li>The file can be downloaded as a text file using the&nbsp;<span class=\"tn-icon bx bx-download\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a>&nbsp;area.</li><li>The file can also be searched just like a normal&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note.</li></ul><h2>Location on the disk</h2><p>Backend logs are stored on the file system. To find them, open the&nbsp;<a class=\"reference-link\" href=\"#root/_help_tAassRL4RSQL\">Data directory</a>, go to the <code>log</code> subdirectory and find the latest log file, e.g. <code>trilium-2022-12-14.log</code>.&nbsp;</p><h2>In the terminal</h2><p>The server also prints every log entry to its standard output, which is what <code>docker logs</code> or <code>journalctl</code> show. When that output is a terminal, each entry starts with its time and is colored like the backend log in the app: request status codes by class, slow SQL queries, and errors in red. The statement of a slow SQL query is shown in a single color there. The startup banner with the Trilium logo and version information is colored too. Output to a file, a pipe or a container log stays plain text without the time, since those tools add their own.</p><p>To turn the colors off in a terminal, set the <code>NO_COLOR</code> environment variable; to force them on elsewhere, set <code>FORCE_COLOR=1</code>.</p><h2>Reporting backend bugs</h2><p>You can attach the whole file to the bug report (preferable) or open it and copy-paste only the last lines / lines you believe are relevant.</p><h2>Customizing the retention of logs</h2><p>The backend logs are fully managed by the Trilium server. By default the last 90 days worth of logs are kept; the logs older than that are deleted in order to reduce the space consumption.</p><p>It's possible to change the retention period by modifying the&nbsp;<a class=\"reference-link\" href=\"#root/_help_Gzjqa934BdH4\">Configuration (config.ini or environment variables)</a>&nbsp;via the <code>.ini</code> file:</p><pre><code class=\"language-text-x-trilium-auto\">[Logging]\nretentionDays=7</code></pre><p>Or via the environment variable <code>TRILIUM_LOGGING_RETENTION_DAYS</code>.</p><p>Special cases:</p><ul><li>Positive values indicate the number of days worth of logs to keep</li><li>A value of 0 results with the default value (90 days) to be used</li><li>Negative values (e.g. <code>-1</code>) result with all logs to be kept, irrespective how ancient and numerous (and</li></ul><aside class=\"admonition note\"><p>If you set the retention days to a low number, you might notice that not all the log files are being deleted. This is because a minimum number of logs (7 at the time of writing) is maintained at all times.</p></aside>",
+ "_help_bnyigUA2UK7s": "<h2>Accessing via the backend log</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_x3i7MxGccDuM\">Global menu</a>, go to <em>Advanced</em> → <em>Show backend log</em>. This will display the current backend log (i.e. today's), with the historical information available only on disk (see below).</p><p>The log is colored to make it easier to read: request status codes by class, slow SQL queries, and errors in red. The statement of a slow SQL query is highlighted the same way as in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_YKWqdJhzi2VY\">SQL Console</a>, using the color scheme of code notes (see <em>Color schemes</em> in&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>).</p><p>A search that the app runs in the background, for example to filter a collection, or that a script runs is followed by a <code>Search:</code> line with its query and the number of notes it returned. The query is highlighted the same way as in a&nbsp;<a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>. Quick search and saved searches don't add this line.</p><p>Interaction since v0.104.0:</p><ul><li>The file can be downloaded as a text file using the&nbsp;<span class=\"tn-icon bx bx-download\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a>&nbsp;area.</li><li>The file can also be searched just like a normal&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note.</li></ul><h2>Location on the disk</h2><p>Backend logs are stored on the file system. To find them, open the&nbsp;<a class=\"reference-link\" href=\"#root/_help_tAassRL4RSQL\">Data directory</a>, go to the <code>log</code> subdirectory and find the latest log file, e.g. <code>trilium-2022-12-14.log</code>.&nbsp;</p><h2>In the terminal</h2><p>The server also prints every log entry to its standard output, which is what <code>docker logs</code> or <code>journalctl</code> show. When that output is a terminal, each entry starts with its time and is colored like the backend log in the app: request status codes by class, slow SQL queries, and errors in red. The statement of a slow SQL query and the query of a search are shown without syntax highlighting there. The startup banner with the Trilium logo and version information is colored too. Output to a file, a pipe or a container log stays plain text without the time, since those tools add their own.</p><p>To turn the colors off in a terminal, set the <code>NO_COLOR</code> environment variable; to force them on elsewhere, set <code>FORCE_COLOR=1</code>.</p><h2>Reporting backend bugs</h2><p>You can attach the whole file to the bug report (preferable) or open it and copy-paste only the last lines / lines you believe are relevant.</p><h2>Customizing the retention of logs</h2><p>The backend logs are fully managed by the Trilium server. By default the last 90 days worth of logs are kept; the logs older than that are deleted in order to reduce the space consumption.</p><p>It's possible to change the retention period by modifying the&nbsp;<a class=\"reference-link\" href=\"#root/_help_Gzjqa934BdH4\">Configuration (config.ini or environment variables)</a>&nbsp;via the <code>.ini</code> file:</p><pre><code class=\"language-text-x-trilium-auto\">[Logging]\nretentionDays=7</code></pre><p>Or via the environment variable <code>TRILIUM_LOGGING_RETENTION_DAYS</code>.</p><p>Special cases:</p><ul><li>Positive values indicate the number of days worth of logs to keep</li><li>A value of 0 results with the default value (90 days) to be used</li><li>Negative values (e.g. <code>-1</code>) result with all logs to be kept, irrespective how ancient and numerous (and</li></ul><aside class=\"admonition note\"><p>If you set the retention days to a low number, you might notice that not all the log files are being deleted. This is because a minimum number of logs (7 at the time of writing) is maintained at all times.</p></aside>",
"_help_9yEHzMyFirZR": "<p>To provide frontend logs, we need to open the Developer Console. Often the easiest way is to press <kbd>Ctrl</kbd>-<kbd>Shift</kbd>-<kbd>I</kbd> which should work in most browsers (and desktop app). Make sure that the error producing action happened right before you copy&amp;paste the errors, the console is cleared on app restart.</p><p>If that doesn't work, then:</p><ul><li>in Trilium desktop app, go to top-left menu button -&gt; Advanced -&gt; Open dev tools</li><li>In Firefox/Chrome right-click anywhere in the page and click Inspect:</li></ul><p><img src=\"{{helpAssets}}/User%20Guide/Troubleshooting/Error%20logs/Frontend%20logs_error-logs-firefox-context-men.png\"></p><p>Once you have Dev Tools open, click on \"Console\" tab:</p><p><img src=\"{{helpAssets}}/User%20Guide/Troubleshooting/Error%20logs/Frontend%20logs_image.jpg\"></p><p>Copy-paste (or screenshot) the logs. It's better to provide not just errors, but the whole log, which might provide context while analyzing the bug.</p>",
"_help_vdlYGAcpXAgc": "<p>Synchronization can sometimes take a long amount of time in order to compute the items that require update. When running behind a reverse proxy, the request can time out.</p><p>The solution is to increase the timeout at proxy level.</p><h2>Nginx</h2><p>Add the following to the configuration file:</p><pre><code class=\"language-text-x-nginx-conf\">proxy_connect_timeout 300;\nproxy_send_timeout 300;\nproxy_read_timeout 300;\nsend_timeout 300;</code></pre><p>And restart the server.</p><p>See&nbsp;<a href=\"#root/_help_ud6MShXL4WpO\">Nginx Proxy Setup</a>&nbsp;for more information about the Nginx setup.</p><p>If it still doesn't work, try increasing the timeout.</p>",
"_help_s8alTXmpFR61": "<p>Some changes to the application will not take effect immediately and as such it might require to manually reload or refresh the application.</p><p>To do so, simply press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd>.</p>",
diff --git a/apps/server/src/log_provider.spec.ts b/apps/server/src/log_provider.spec.ts
index ddd3c5f548..5e67ac3799 100644
--- a/apps/server/src/log_provider.spec.ts
+++ b/apps/server/src/log_provider.spec.ts
@@ -31,6 +31,13 @@ describe("colorizeLogEntry", () => {
);
});
+ it("colours searches, leaving the query in the default colour", () => {
+ expect(colorizeLogEntry("Search: #book (returned 3 items)", "12:34:56.789")).toBe(
+ `${ts} ${paint([ "bold", "cyan" ], "Search")}: #book `
+ + paint("gray", "(returned 3 items)")
+ );
+ });
+
it("colours a whole error entry red, stack trace included", () => {
for (const message of [ "ERROR: boom\n at foo (bar.js:1:1)", "JS Error: boom\r\nStack: at x" ]) {
expect(colorizeLogEntry(message, "12:34:56.789")).toBe(`${ts} ${paint("red", message)}`);
@@ -143,11 +150,30 @@ describe("ServerLogService request logging", () => {
writeEntry.mockRestore();
}
});
+
+ it("writes the summary a route leaves in res.locals after the request's own line", () => {
+ const log = new ServerLogService();
+ const writes: string[] = [];
+ const writeEntry = vi
+ .spyOn(log as unknown as { writeEntry(entry: string): void }, "writeEntry")
+ .mockImplementation((entry: string) => void writes.push(entry));
+
+ try {
+ const summary = "Search: #book (returned 3 items)";
+ logRequest(log, "/api/search?searchString=%23book", summary);
+
+ expect(writes).toHaveLength(2);
+ expect(writes[0]).toContain("200 GET /api/search?searchString=%23book with 15 bytes");
+ expect(writes[1]).toContain(" Search: #book (returned 3 items)");
+ } finally {
+ writeEntry.mockRestore();
+ }
+ });
});
-function logRequest(log: ServerLogService, url: string) {
+function logRequest(log: ServerLogService, url: string, logSummary?: string) {
const req = { url, method: "GET" } as unknown as Request;
- const res = { statusCode: 200 } as unknown as Response;
+ const res = { statusCode: 200, locals: { logSummary } } as unknown as Response;
log.request(req, res, 1, 15);
}
diff --git a/apps/server/src/log_provider.ts b/apps/server/src/log_provider.ts
index f89e4d2bb7..54cc7889da 100644
--- a/apps/server/src/log_provider.ts
+++ b/apps/server/src/log_provider.ts
@@ -1,4 +1,4 @@
-import { FileBasedLogService, type LogFileInfo } from "@triliumnext/core";
+import { FileBasedLogService, type LogFileInfo, type ResponseLocals } from "@triliumnext/core";
import type { Request, Response } from "express";
import fs from "fs";
import { EOL } from "os";
@@ -153,6 +153,11 @@ export default class ServerLogService extends FileBasedLogService {
}
this.info(`${timeMs >= 10 ? "Slow " : ""}${res.statusCode} ${req.method} ${req.url} with ${responseLength} bytes took ${timeMs}ms`);
+
+ const { logSummary }: ResponseLocals = res.locals;
+ if (logSummary) {
+ this.info(logSummary);
+ }
}
}
@@ -166,6 +171,7 @@ const VERB_STYLE: Style = [ "bold", "blueBright" ];
const URL_STYLE: Style = "cyan";
const QUERY_VERB_STYLE: Style = [ "bold", "magenta" ];
const SQL_STYLE: Style = "magentaBright";
+const SEARCH_STYLE: Style = [ "bold", "cyan" ];
const ERROR_STYLE: Style = "red";
const WARNING_STYLE: Style = "yellow";
// The green of the leaves in `icon-color.svg`.
@@ -180,6 +186,7 @@ const STATUS_STYLES: Record<string, Style> = {
const HTTP_REQUEST = /^(Slow )?(\d{3}) (GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) (\S+)/;
const SLOW_QUERY = /^(Slow (?:recursive )?query)( took \d+ms)(?:(: )(.+))?/;
+const SEARCH = /^(Search): .* {2}(\(returned \d+ items\))$/;
const ERROR_ENTRY = /^(?:JS Error|ERROR):/;
const WARNING_ENTRY = /^WARNING:/;
// The `📦 Versions: …` rows of the startup intro.
@@ -219,6 +226,14 @@ function colorizeMessage(message: string): string {
].join("");
}
+ const search = SEARCH.exec(message);
+ if (search) {
+ const [ , searchVerb, count ] = search;
+ return paint(SEARCH_STYLE, searchVerb)
+ + message.slice(searchVerb.length, -count.length)
+ + paint(MUTED_STYLE, count);
+ }
+
if (message.startsWith(LOGO_PREFIX)) {
const version = message.slice(LOGO_PREFIX.length).trimEnd();
return `\n${paint(LOGO_STYLE, TRILIUM_LOGO)} ${paint(MUTED_STYLE, version)}\n`;
diff --git a/docs/User Guide/User Guide/Troubleshooting/Error logs/Backend (server) logs.md b/docs/User Guide/User Guide/Troubleshooting/Error logs/Backend (server) logs.md
index 44837849c6..76a713622a 100644
--- a/docs/User Guide/User Guide/Troubleshooting/Error logs/Backend (server) logs.md
+++ b/docs/User Guide/User Guide/Troubleshooting/Error logs/Backend (server) logs.md
@@ -5,6 +5,8 @@ In the <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/
The log is colored to make it easier to read: request status codes by class, slow SQL queries, and errors in red. The statement of a slow SQL query is highlighted the same way as in the <a class="reference-link" href="../../Advanced%20Usage/Database/Manually%20altering%20the%20database/SQL%20Console.md">SQL Console</a>, using the color scheme of code notes (see _Color schemes_ in <a class="reference-link" href="../../Note%20Types/Code.md">Code</a>).
+A search that the app runs in the background, for example to filter a collection, or that a script runs is followed by a `Search:` line with its query and the number of notes it returned. The query is highlighted the same way as in a <a class="reference-link" href="../../Note%20Types/Saved%20Search.md">Saved Search</a>. Quick search and saved searches don't add this line.
+
Interaction since v0.104.0:
* The file can be downloaded as a text file using the <span class="tn-icon bx bx-download"></span> button in the <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20menu.md">Note menu</a> area.
@@ -16,7 +18,7 @@ Backend logs are stored on the file system. To find them, open the <a class="re
## In the terminal
-The server also prints every log entry to its standard output, which is what `docker logs` or `journalctl` show. When that output is a terminal, each entry starts with its time and is colored like the backend log in the app: request status codes by class, slow SQL queries, and errors in red. The statement of a slow SQL query is shown in a single color there. The startup banner with the Trilium logo and version information is colored too. Output to a file, a pipe or a container log stays plain text without the time, since those tools add their own.
+The server also prints every log entry to its standard output, which is what `docker logs` or `journalctl` show. When that output is a terminal, each entry starts with its time and is colored like the backend log in the app: request status codes by class, slow SQL queries, and errors in red. The statement of a slow SQL query and the query of a search are shown without syntax highlighting there. The startup banner with the Trilium logo and version information is colored too. Output to a file, a pipe or a container log stays plain text without the time, since those tools add their own.
To turn the colors off in a terminal, set the `NO_COLOR` environment variable; to force them on elsewhere, set `FORCE_COLOR=1`.
diff --git a/packages/trilium-core/src/http_interface.ts b/packages/trilium-core/src/http_interface.ts
index 5411dfaaad..207c49bf24 100644
--- a/packages/trilium-core/src/http_interface.ts
+++ b/packages/trilium-core/src/http_interface.ts
@@ -57,4 +57,12 @@ export interface Response {
*/
write(chunk: string): boolean;
end(): unknown;
+ /** Express's `res.locals`. Standalone logs no requests, so its responses have none. */
+ locals?: ResponseLocals;
+}
+
+/** The values a shared route handler leaves in {@link Response.locals}. */
+export interface ResponseLocals {
+ /** A line that the server's request log writes after the request's own line. */
+ logSummary?: string;
}
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index 7e8a4fbc79..2babd1f13a 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -165,7 +165,9 @@ export { default as imageService } from "./services/image";
export { t } from "i18next";
export type { RequestProvider, ExecOpts, CookieJar, FetchApiOpts, FetchResourceOpts, FetchedResource } from "./services/request";
export type * from "./meta";
-export type { QueryString, QueryValue, Request, RequestHeaders, Response } from "./http_interface";
+export type {
+ QueryString, QueryValue, Request, RequestHeaders, Response, ResponseLocals
+} from "./http_interface";
export * as routeHelpers from "./routes/helpers";
export { resolveYouTubePreview, storeFavicon } from "./routes/api/link_embed";
diff --git a/packages/trilium-core/src/routes/api/search.spec.ts b/packages/trilium-core/src/routes/api/search.spec.ts
index 67b984436f..e9ae5cb46c 100644
--- a/packages/trilium-core/src/routes/api/search.spec.ts
+++ b/packages/trilium-core/src/routes/api/search.spec.ts
@@ -44,6 +44,17 @@ describe("Search API (core)", () => {
expect(res.body).toContain(createdNoteId);
});
+ it("describes a full search on one line for the request log", async () => {
+ const token = "ZzLoggedSearchQwerty";
+ await createTextNote(api, { title: `${token} one` });
+ await createTextNote(api, { title: `${token} two` });
+
+ const res = await api.get("/api/search", {
+ query: { searchString: ` note.title *=*\n ${token} ` }
+ });
+ expect(res.locals?.logSummary).toBe(`Search: note.title *=* ${token} (returned 2 items)`);
+ });
+
it("restricts a full search to the given ancestor's subtree", async () => {
const token = "ZzScopedSearchQwerty";
const board = await createTextNote(api, { title: "Board" });
diff --git a/packages/trilium-core/src/routes/api/search.ts b/packages/trilium-core/src/routes/api/search.ts
index 6df93a6f38..9773fb0d14 100644
--- a/packages/trilium-core/src/routes/api/search.ts
+++ b/packages/trilium-core/src/routes/api/search.ts
@@ -3,7 +3,7 @@ import {
type SearchResultDetails, type SearchResultDetailsRequest, type SearchResultDetailsResponse,
type SearchWithTokensResponse, type TemplatesResponse
} from "@triliumnext/commons";
-import type { Request } from "../../http_interface";
+import type { Request, Response } from "../../http_interface";
import becca from "../../becca/becca.js";
import becca_service from "../../becca/becca_service.js";
@@ -158,7 +158,8 @@ function search(
req: Request<{}, {
searchString?: string, ancestorNoteId?: string, includeTokens?: string,
includeArchivedNotes?: string
- }>
+ }>,
+ res: Response
): string[] | SearchWithTokensResponse {
const searchString = getSearchString(req);
const { ancestorNoteId, includeTokens, includeArchivedNotes } = req.query;
@@ -178,6 +179,12 @@ function search(
const noteIds = searchService.findResultsWithQuery(searchString, searchContext)
.map((sr) => sr.noteId);
+ // The request line carries the query URL-encoded, so the log repeats it in a readable form.
+ if (res.locals) {
+ const query = searchString.trim().replace(/\s+/g, " ");
+ res.locals.logSummary = `Search: ${query} (returned ${noteIds.length} items)`;
+ }
+
if (includeTokens !== "true") {
return noteIds;
}
diff --git a/packages/trilium-core/src/test/api_tester.ts b/packages/trilium-core/src/test/api_tester.ts
index ebec3f0557..3cfd8f3548 100644
--- a/packages/trilium-core/src/test/api_tester.ts
+++ b/packages/trilium-core/src/test/api_tester.ts
@@ -1,6 +1,7 @@
import { Writable } from "node:stream";
import { HttpError } from "../errors";
+import type { ResponseLocals } from "../http_interface";
import * as routes from "../routes";
import { getContext } from "../services/context";
import entityChanges from "../services/entity_changes";
@@ -60,6 +61,8 @@ export interface TestResponse<T = unknown> {
body: T;
/** The file a handler asked Express to send rather than write itself, if it did. */
sentFile?: string;
+ /** What an `apiRoute` handler left in `res.locals`. */
+ locals?: ResponseLocals;
}
export interface RequestOptions {
@@ -149,6 +152,7 @@ class MockResponse extends Writable {
used = false;
statusCode = 200;
headers: Record<string, string> = {};
+ locals: ResponseLocals = {};
sentFile?: string;
@@ -215,11 +219,12 @@ export class CoreApiTester {
private registerAll() {
const apiRoute = (method: HttpMethod, path: string, handler: Handler) =>
this.add(method, path, async (req) => {
+ const mockRes = createMockResponse();
const result = await getContext().init(() => {
seedContext(req);
- return getSql().transactional(() => handler(req));
+ return getSql().transactional(() => handler(req, mockRes));
});
- return formatApiResult(result);
+ return { ...formatApiResult(result), locals: mockRes.locals };
});
const asyncApiRoute = (method: HttpMethod, path: string, handler: Handler) =>