Using Attachments as Cache in ServiceNow

I’ve been working on a pet project (or well, several pet projects) lately, and I have been researching thoroughly how the ServiceNow App Repo functions, and stores data in ServiceNow from the App Repo instance.

I stumbled across some very clever code, in the AppManagerCache script include, for storing plugin and store app data JSON into a txt file as an attachment. This could be a very strong alternative for storing larger data sets than in a property, while minimizing custom table usage.

Let’s break it down how to do it.

Step 1. Make your JSON object/string of what you want to store.

var myJSON = {"snowunderground":"is the best blog around"};

Step 2. Pick the record you want to link the cache to (in this example we will pick sys_user)

var grUser = new GlideRecord('sys_user');
grUser.get('user_name','admin');

Step 3. Write the Cache

var gsa = new GlideSysAttachment();
var attachmentId = gsa.write(grUser, "response.txt", 
'text/plain', JSON.stringify(myJSON));

Step 4. Read the cache and delete (as needed)

var grAttachment = new GlideRecord('sys_attachment');
grAttachment.get("table_sys_id", grUser.sys_id.toString());
var reader = new global.AttachmentReader();
var content = reader.getContent(grAttachment);
var parsedContent = JSON.parse(content); //use this!

//Now to clean it up...
//Note: Alternatively you could use GlideSysAttachment.deleteAttachment
var grAttachment = new GlideRecord("sys_attachment");
grAttachment.addQuery("table_sys_id", grUser.sys_id.toString());
grAttachment.setWorkflow(false);
grAttachment.query();
if (grAttachment.getRowCount() > 0){
  grAttachment.deleteMultiple();
}

Step 5. Profit

In Summary

For those out there with limits on tables, or just want to keep your instance really light, this is a pretty useful tool to keep in the tool belt. It may not perform as well as a high performance cache, and maybe not handle extremely large amount of data (for that, you really should just have an indexed table), but nevertheless, it’s a good concept to keep in mind. Unlike other caching mechanisms in ServiceNow, this one can be shared across multiple users, and is permanent until specifically deleted.