Query by tag, sort, and combine Drafts

I am attempting to query Draft(s) based on it’s tag (today’s date), sort them from oldest-newest creation date, and combine the Drafts into a single Draft.

I’m running into an issue with this:

// Query Drafts tagged with Today's Date
var tag = draft.processTemplate("[[date|%Y-%-m-%-d]]");
var d = Draft.query("","inbox",[tag],"created");
editor.load(d);

I’m guessing what I’m missing here is fairly straightforward…

This is my first step in the script, so any tips or advice would be greatly appreciated!

Maybe try this?

let tag = draft.processTemplate("[[date|%Y-%-m-%-d]]");
let d = Draft.query("","inbox",[tag],"created");
if(d.length > 0) editor.load(d[0]);
else app.displayErrorMessage("No drafts today");

query would return an array of drafts, and the original code was treating the result as single draft.

I’m assuming also that you are not expecting this to combine any drafts as per your overall requirement and that this is just a step in your process.

Ahh, yes that makes sense! My plan, after this, is to simply combine these drafts (in order) into a new single draft.

Am I correct in assuming that, with the queried drafts loaded into the editor, I simply need to draft.content = editor.load(d[0]); ? Or is it a bit more complicated than that?

Thanks for the help.

the Draft.query() returns an array of Drafts.
If you execute draft.content = editor.load(d[0]) you’ll only have the first one.
if you take the script from @sylumer and add a for loop you’ll get what you wanted.
also I’d recommend, to create a new draft in the script. since draft is the current active Draft in the editor and you could overwrite something.
maybe you want to add the same tag afterwards, or trash every found draft. The script below is not tested but hopefully it points you into the right direction

let tag = draft.processTemplate("[[date|%Y-%-m-%-d]]");
let d = Draft.query("","inbox",[tag],"created");
if(d.length > 0)
{
  let newDraft = new Draft()
  newDraft.content = "# Drafts from " + tag
  for(cd of d){
    newDraft.content += "\n\n" + cd.content
  }
  newDraft.update()
  editor.load(newDraft);
} 
else app.displayErrorMessage("No drafts today");
2 Likes

This worked beautifully, thanks!

1 Like