Javascript: don't send value to API if blank?

I need a bit of help with a script I use to send highlights to Readwise. Basically, I create a prompt in drafts, fill out the details, then it send to Readwise. However, not every highlight needs all the fields. Yet, if I try to send a blank field to the Readwise API, it fails. How can I detect a blank field and not send that to the API?

// readwise


let t = draft.processTemplate("[[display_title]]");
let h = draft.processTemplate("[[line|3..]]");


var p = Prompt.create();
p.title="Parse draft for readwise";
p.addTextField("pTitle","Title",t);
p.addTextField("pAuthor","Author","");
p.addTextView("pText","Highlight",h,{"height":150});
p.addTextField("pLoc","Location","");
p.addTextField("pURL","URL","");
p.addTextField("pNote","Note","");
p.addSelect("pType","Type",["book","article","podcast"],[""],false);
p.addButton("OK");



//p.fieldValues["pNote"],p.fieldValues["pType"],
if(p.show()){
    
        let pT = p.fieldValues["pType"].toString();
        postToReadwise(p.fieldValues["pTitle"],p.fieldValues["pAuthor"],p.fieldValues["pText"],p.fieldValues["pLoc"],p.fieldValues["pURL"],p.fieldValues["pNote"],pT,draft.createdAt.toISOString());

    
}
else
{
    context.cancel();
}

function postToReadwise(pTitle,pAuthor,pText,pLoc,pURL,pNote,pType,pDate)
{
	const BASEURL = "https://readwise.io/api/v2/highlights/";
	
	let credReadwise = Credential.create("Readwise", "Highlight surfacing service.");
	credReadwise.addPasswordField("token", "API Token");
	credReadwise.authorize();

	let httpMain = HTTP.create();
	let respMain = httpMain.request(
	{
		"url" : BASEURL,
		"method" : "POST",
		"data": 
		{
			"highlights" : [{
                "text" : pText,
                "title": pTitle,
                "author":pAuthor,
                "location":pLoc,
				"source_url":pURL,
                "note":pNote,
                "source_type":pType,
                "highlighted_at":pDate
            }]
		},
		"headers" :
		{
			"Authorization" : `Token ${credReadwise.getValue("token")}`
		}
	});

    if (respMain.success) {
        console.log("yep");
        return true;
    }
	else
	{
        alert(`[${respMain.statusCode}] ${respMain.error}`);
        console.log(`[${respMain.statusCode}] ${respMain.error}`);
		return false;
	}
}

You would have to construct your data object to only contain the fields with values. In your postToReadwise function, so something like:

// create object to hold values, with only empty `highlights` key
let data = {"highlights": {}};
// test for and add values from parameters
if (pText && pText.length > 0) {
    data["highlights"]["text"] = pText
}
if (pTitle && pTitle.length > 0) {
    data["highlights"]["title"] = pTitle
}
// etc. for each param

Then pass the data variable as the value for “data” in the HTTP request.

1 Like