Skip to content

Build your personal knowledge base with Trilium Notes

core: add API for note bulk creation date & time retrieval

Adorian Doran0286bc9a6ba9
diff --git a/apps/client/src/services/note-dates.spec.ts b/apps/client/src/services/note-dates.spec.ts
new file mode 100644
index 0000000000..c07b1d7409
--- /dev/null
+++ b/apps/client/src/services/note-dates.spec.ts
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { getCreationDate, loadCreationDates } from "./note-dates";
+import server from "./server";
+
+/** Names notes uniquely per test: the cache is module-level and is never emptied. */
+let counter = 0;
+
+function noteIds(count: number) {
+ return Array.from({ length: count }, () => `note${counter++}`);
+}
+
+function respondWith(dates: Record<string, string>) {
+ return vi.spyOn(server, "post").mockImplementation(async (_url, data) => {
+ const requested = (data as { noteIds: string[] }).noteIds;
+ return Object.fromEntries(requested
+ .filter((noteId) => dates[noteId])
+ .map((noteId) => [ noteId, { utcDateCreated: dates[noteId] } ]));
+ });
+}
+
+describe("loadCreationDates", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("loads dates and exposes them as milliseconds", async () => {
+ const [ first, second ] = noteIds(2);
+ respondWith({
+ [first]: "2026-01-05 09:30:00.000Z",
+ [second]: "2026-02-05 09:30:00.000Z"
+ });
+
+ expect(await loadCreationDates([ first, second ])).toBe(true);
+ expect(getCreationDate(first)).toBe(Date.parse("2026-01-05 09:30:00.000Z"));
+ expect(getCreationDate(second)).toBe(Date.parse("2026-02-05 09:30:00.000Z"));
+ });
+
+ it("asks only about the notes it does not know yet", async () => {
+ const [ known, fresh ] = noteIds(2);
+ const post = respondWith({
+ [known]: "2026-01-05 09:30:00.000Z",
+ [fresh]: "2026-01-06 09:30:00.000Z"
+ });
+ await loadCreationDates([ known ]);
+
+ post.mockClear();
+ expect(await loadCreationDates([ known, fresh ])).toBe(true);
+ expect(post.mock.calls[0][1]).toEqual({ noteIds: [ fresh ] });
+
+ post.mockClear();
+ expect(await loadCreationDates([ known, fresh ])).toBe(false);
+ expect(server.post).not.toHaveBeenCalled();
+ });
+
+ it("sends one request for two callers asking at the same time", async () => {
+ const [ shared ] = noteIds(1);
+ respondWith({ [shared]: "2026-01-05 09:30:00.000Z" });
+
+ await Promise.all([ loadCreationDates([ shared ]), loadCreationDates([ shared ]) ]);
+
+ expect(server.post).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not ask again about a note the server does not know", async () => {
+ const [ missing ] = noteIds(1);
+ respondWith({});
+
+ await loadCreationDates([ missing ]);
+ expect(getCreationDate(missing)).toBeUndefined();
+
+ expect(await loadCreationDates([ missing ])).toBe(false);
+ expect(server.post).toHaveBeenCalledTimes(1);
+ });
+
+ it("splits a large set into batches", async () => {
+ const many = noteIds(2500);
+ respondWith({});
+
+ await loadCreationDates(many);
+
+ expect(server.post).toHaveBeenCalledTimes(3);
+ const sizes = vi.mocked(server.post).mock.calls
+ .map(([ , data ]) => (data as { noteIds: string[] }).noteIds.length);
+ expect(sizes).toEqual([ 1000, 1000, 500 ]);
+ });
+});
diff --git a/apps/client/src/services/note-dates.ts b/apps/client/src/services/note-dates.ts
new file mode 100644
index 0000000000..bcc2105d60
--- /dev/null
+++ b/apps/client/src/services/note-dates.ts
@@ -0,0 +1,80 @@
+import type { MetadataResponse } from "@triliumnext/commons";
+
+import server from "./server";
+
+/** How many notes one request asks about. */
+const BATCH_SIZE = 1000;
+
+/**
+ * The creation time of every note asked about so far, in milliseconds.
+ *
+ * Notes the server does not know are stored with no time, so they are not requested again.
+ * Nothing is evicted: `utcDateCreated` does not change once a note exists.
+ */
+const creationDates = new Map<string, number | undefined>();
+
+/** The request covering each note being asked about, so two callers do not ask twice. */
+const requests = new Map<string, Promise<void>>();
+
+/**
+ * Loads the creation dates of the given notes, skipping the ones already known.
+ *
+ * @returns whether anything was loaded, so a caller can skip redrawing.
+ */
+export async function loadCreationDates(noteIds: Iterable<string>) {
+ const missing: string[] = [];
+ const pending = new Set<Promise<void>>();
+
+ for (const noteId of noteIds) {
+ if (creationDates.has(noteId)) {
+ continue;
+ }
+
+ const inFlight = requests.get(noteId);
+ if (inFlight) {
+ pending.add(inFlight);
+ } else {
+ missing.push(noteId);
+ }
+ }
+
+ for (let at = 0; at < missing.length; at += BATCH_SIZE) {
+ pending.add(load(missing.slice(at, at + BATCH_SIZE)));
+ }
+
+ if (!pending.size) {
+ return false;
+ }
+
+ await Promise.all(pending);
+ return true;
+}
+
+/** The creation time of a note in milliseconds, or undefined until it is loaded. */
+export function getCreationDate(noteId: string) {
+ return creationDates.get(noteId);
+}
+
+function load(noteIds: string[]) {
+ const request = fetchDates(noteIds).finally(() => {
+ for (const noteId of noteIds) {
+ requests.delete(noteId);
+ }
+ });
+
+ for (const noteId of noteIds) {
+ requests.set(noteId, request);
+ }
+
+ return request;
+}
+
+async function fetchDates(noteIds: string[]) {
+ const metadata = await server.post<Record<string, MetadataResponse>>(
+ "notes/metadata", { noteIds });
+
+ for (const noteId of noteIds) {
+ const created = Date.parse(metadata?.[noteId]?.utcDateCreated ?? "");
+ creationDates.set(noteId, Number.isNaN(created) ? undefined : created);
+ }
+}
diff --git a/packages/trilium-core/src/routes/api/notes.spec.ts b/packages/trilium-core/src/routes/api/notes.spec.ts
index 3ca0b904a7..2414114912 100644
--- a/packages/trilium-core/src/routes/api/notes.spec.ts
+++ b/packages/trilium-core/src/routes/api/notes.spec.ts
@@ -44,6 +44,31 @@ describe("Notes API (core)", () => {
});
});
+ it("returns the timestamps of several notes at once, skipping the ones it cannot find", async () => {
+ const note = await createTextNote(api, { title: "Bulk metadata" });
+
+ const res = await api.post<Record<string, { utcDateCreated: string }>>(
+ "/api/notes/metadata",
+ { body: { noteIds: [ "root", note.noteId, "missingNote123" ] } });
+
+ expect(res.status).toBe(200);
+ expect(Object.keys(res.body).sort()).toEqual([ note.noteId, "root" ].sort());
+ expect(res.body[note.noteId]).toMatchObject({
+ dateCreated: expect.any(String),
+ utcDateCreated: expect.any(String),
+ dateModified: expect.any(String),
+ utcDateModified: expect.any(String)
+ });
+ });
+
+ it("400s a bulk metadata request whose noteIds are not a list of strings", async () => {
+ expect((await api.post("/api/notes/metadata", { body: {} })).status).toBe(400);
+ expect((await api.post("/api/notes/metadata", { body: { noteIds: "root" } })).status)
+ .toBe(400);
+ expect((await api.post("/api/notes/metadata", { body: { noteIds: [ 1 ] } })).status)
+ .toBe(400);
+ });
+
it("returns the note blob", async () => {
const res = await api.get<{ blobId: string; content: string }>("/api/notes/root/blob");
expect(res.status).toBe(200);
diff --git a/packages/trilium-core/src/routes/api/notes.ts b/packages/trilium-core/src/routes/api/notes.ts
index 2abb4b5138..bd1b3870bb 100644
--- a/packages/trilium-core/src/routes/api/notes.ts
+++ b/packages/trilium-core/src/routes/api/notes.ts
@@ -104,6 +104,63 @@ function getNoteMetadata(req: Request<{ noteId: string }>) {
} satisfies MetadataResponse;
}
+/**
+ * @swagger
+ * /api/notes/metadata:
+ * post:
+ * summary: Retrieve the timestamps of several notes at once
+ * operationId: notes-metadata-bulk
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * noteIds:
+ * type: array
+ * items:
+ * $ref: "#/components/schemas/NoteId"
+ * responses:
+ * '200':
+ * description: The timestamps of each note found, keyed by note ID
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * additionalProperties:
+ * $ref: "#/components/schemas/Timestamps"
+ * security:
+ * - session: []
+ * tags: ["data"]
+ */
+function getNotesMetadata(req: Request) {
+ const { noteIds } = req.body as { noteIds?: unknown };
+ if (!Array.isArray(noteIds) || noteIds.some((noteId) => typeof noteId !== "string")) {
+ throw new ValidationError("Expected 'noteIds' to be an array of note IDs.");
+ }
+
+ const metadata: Record<string, MetadataResponse> = {};
+
+ for (const noteId of noteIds as string[]) {
+ // Unknown notes are skipped rather than refused: a caller asks about the notes it holds,
+ // and one of them can be deleted before the request lands.
+ const note = becca.notes[noteId];
+ if (!note) {
+ continue;
+ }
+
+ metadata[noteId] = {
+ dateCreated: note.dateCreated,
+ utcDateCreated: note.utcDateCreated,
+ dateModified: note.dateModified,
+ utcDateModified: note.utcDateModified
+ };
+ }
+
+ return metadata;
+}
+
function createNote(req: Request) {
const params = Object.assign({}, req.body); // clone
params.parentNoteId = req.params.parentNoteId;
@@ -406,6 +463,7 @@ export default {
getNote,
getNoteBlob,
getNoteMetadata,
+ getNotesMetadata,
updateNoteData,
deleteNote,
undeleteNote,
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 0434443c98..912767a5cc 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -99,6 +99,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTrans
apiRoute(GET, "/api/notes/:noteId", notesApiRoute.getNote);
apiRoute(GET, "/api/notes/:noteId/blob", notesApiRoute.getNoteBlob);
apiRoute(GET, "/api/notes/:noteId/metadata", notesApiRoute.getNoteMetadata);
+ apiRoute(PST, "/api/notes/metadata", notesApiRoute.getNotesMetadata);
apiRoute(PUT, "/api/notes/:noteId/data", notesApiRoute.updateNoteData);
apiRoute(DEL, "/api/notes/:noteId", notesApiRoute.deleteNote);
apiRoute(PUT, "/api/notes/:noteId/undelete", notesApiRoute.undeleteNote);