Apps Script, Redis and GraphQL – together

I’m a great fan of both Redis and GraphQL. You’ll find plenty of articles about them around on this site. Although I’ve showed many examples of GraphQL and Apps Script, it was never possible to connect up Apps Script to Redis, because redis doesn’t use HTTP to communicate between Client and Server. I’ve come across upstash.com (with a free tier), that fronts a redis database with a GraphQL API.

Motivation

Redis is a great caching solution, and using it means we are not limited to caching within the same platform. This means you can easily share data between Apps Script and Node and well, anything.  Here’s how.

Getting started

You’ll need to register with upstash.com and choose the free database option and then create a database. Next go to the GraphQL Explorer and choose CONFIGURE API

upstash graphql

You’ll see there are 3 access keys you can choose from.  Pick the READ WRITE on and copy that access key.

Create an Apps Script project

I’ve already written a library bmUpstash, so you don’t really need to write much code.

  1. Include that library in your project: 1GBZYWotLe5-pVord4fe5DCl6pwGz1BiDjAqA0AE812_qy6XTWmWeZNX-
  2. Put that READ WRITE key somewhere safe – I have it in my property service
const storeKey = () => {
PropertiesService.getUserProperties().setProperty('usrwkey', 'xxxxxxxx')
}
store the readwrite key

Try it out

You’ll see that Upstash supports most redis commands, but for demonstration here, I’ve only implemented these in my library for now

  • Set – set a key value pair
  • Get – get a value given a key
  • Del – delete a key value pair
  • SetEX – set a key value pair with an expiration time in seconds

Initialize the library

The library is dependency free, so you need to pass UrlFetch.fetch over from your script, along with how to get your access key.

  const ug = bmUpstash.gqlRedis({
fetcher: UrlFetchApp.fetch,
tokenService: () => PropertiesService.getUserProperties().getProperty('usrwkey')
})
create an upstash client

And seriously, that’s it. Now we can write stuff to the redis database.

Some examples

ug.execute ('Set', 'mykey', 'someData')
const data = ug.execute('Get', 'mykey')
ug.execute('SetEX', 'anotherkey', 'some data that expires', 60)
ug.execute('Del', ['anotherkey', 'mykey'])

The responses are standard redis.

Large objects

Upstash has a stated max size of 1mb per value, but anything over 400k doesn’t work at time of writing. See Upstash as an Apps Script cache platform for how to deal with large objects

Links

Upstash: https://upstash.com

bmUpstash library id: 1GBZYWotLe5-pVord4fe5DCl6pwGz1BiDjAqA0AE812_qy6XTWmWeZNX-

scrviz: https://scrviz.web.app/?repo=brucemcpherson%2FbmUpstash

github: https://github.com/brucemcpherson/bmUpstash