zadam / trilium

Build your personal knowledge base with Trilium Notes
GNU Affero General Public License v3.0
27.2k stars 1.9k forks source link

(Bug report) Old api code note not working anymore with awaits #2595

Closed PAK90 closed 2 years ago

PAK90 commented 2 years ago

Trilium Version

0.49.5

What operating system are you using?

Windows

What is your setup?

Local + server sync

Operating System Version

Win10 21H1

Description

I have an api code note I wrote when I was using 0.47.5. I've just upgraded to 0.49.5 and now when I call the api and it tries to run this code note, it says ERROR: Execution of script "api:create-note" (gecXcJoZUvt) failed with error: await is only valid in async functions and the top level bodies of modules.

const {req, res} = api;
const dayjs = require('dayjs');
const {secret, title, content, attributes} = req.body;

if (req.method == 'POST' && secret === 'secret') {
    const todayNote = await api.getTodayNote();

    const {note} = await api.createTextNote(todayNote.noteId, `${dayjs().format('HH:mm:ss')} - ${title}`, content);

    attributes.split('|').forEach(async attr => {
        await note.addAttribute('label', attr);  
    })

    res.status(201).json(note);
}
else {
    res.send(400);
}

I haven't touched this note's contents since last July, and it was working fine until I upgraded versions yesterday. Why's it suddenly broken?

wunter8 commented 2 years ago

Backend scripts cannot use async/await after v0.48: https://github.com/zadam/trilium/wiki/Release-notes-v0.48#all-backend-script-notes-should-avoid-being-async

PAK90 commented 2 years ago

I see... I took the code note and removed all awaits from it, tried to run it, and got this instead:

ERROR: Execution of script "api:create-note" (gecXcJoZUvt) failed with error: Load of script note "api:create-note" (gecXcJoZUvt) failed with: Converting circular structure to JSON
    --> starting at object with constructor 'Note'
    |     property 'children' -> object with constructor 'Array'
    |     index 0 -> object with constructor 'Note'
    |     property 'parents' -> object with constructor 'Array'
    --- index 0 closes the circle
wunter8 commented 2 years ago

Try changing the return statement to res.status(201).json(note.getPojo());

See https://github.com/zadam/trilium/issues/2289 and https://github.com/zadam/trilium/wiki/Custom-request-handler

PAK90 commented 2 years ago

That did the trick, thanks! I guess I should pay more attention to release notes, though I do wish existing code notes wouldn't silently break between updates...

zadam commented 2 years ago

I try to minimize the breakage, however the 0.48 was quite exceptional in the amount of changes. I don't see similar breakage repeating (soon).