First JS script... appending to an existing draft

This is literally the first script I have ever put together in Java script. The idea is taken from the Add to List action in the directory, but instead of picking which one, I wanted to add it to a specific draft everytime, without having to find that draft to update it.

I consider myself an automator, not a programmer. And using URL schemes this would have been super easy for me, but as a learning experience I did it this way.

I’m sure it could be improved though so please tell me how.

[https://actions.getdrafts.com/a/1Ig](http://Add to Draft)

const template = `

`;
const currentContent = draft.content.trim();
// replace the UUID here with the UUID you want to append too.
var d = Draft.find('99D8294B-192D-465F-BBBD-AC29EAFAC6D6');
d.content = d.content + currentContent + template;
d.update();
2 Likes

Looks good.

I don’t know if you would like to handle the case where the UUID isn’t found, but if you experiment with a string that isn’t a well-formed UUID, or doesn’t match any local Draft, then you can confirm that an expression like:

alert(typeof strUUID) reveals Draft.find() to return the special value undefined when a UUID string is not found.

That leads to various ways of producing a heads-up when no match is found.

If, for example, you start by giving the UUID a name:

const strUUID = '99D8294B-192D-465F-BBBD-AC29EAFAC6D6';

you can check whether a matching Draft has actually been found, and branch on that condition.

For example, something like:

if (typeof d !== 'undefined') {
    d.content = d.content + currentContent + template;
    d.update();
} else {
    alert(`UUID not found:\n\n${strUUID}`)
}

Looks great!

Not sure if you have any need for this tip, but if you did want the appending to have some additional information like a timestamp, you can use Drafts’ template engine in a script as well. Something like:

const template = `[[date]]
[[draft]]

`;
const currentContent = draft.content.trim();
// replace the UUID here with the UUID you want to append too.
var d = Draft.find('99D8294B-192D-465F-BBBD-AC29EAFAC6D6');
d.content = d.content + draft.processTemplate(template);
d.update();
3 Likes

I guess in my head the existing UUID would always be there because the intent was someone would make a draft first of something they want to be a running list.

1 Like