Property service as a setting
.. more settings, props: { store:PropertiesService.getScriptProperties(), get: function (key) { var r = this.store.getProperty (key); try { var ob = r ? JSON.parse(r) : null; } catch (err) { var ob = r; } return ob; }, set: function (key , ob) { return this.store.setProperty (key , JSON.stringify(ob)); } }, .. more settings
Using
Elsewhere in my code if I want to read or write to the property service, I don’t need to know anything about how it’s done, and can change the store or even the entire service by simply changing the settings, without disturbing the code that uses it.
ns.settings.props.set (key , value);
and
var value = ns.settings.props.get (key);
Using a closure
Of course you could just write a couple of functions to set and get properties to abstract them away too, but this approach seems an altogether more appropriate one. Hopefully you’ll see in a moment why.
function makeService (service) { return { store:service, get: function (key) { var r = this.store.getProperty (key); try { var ob = r ? JSON.parse(r) : null; } catch (err) { var ob = r; } return ob; }, set: function (key , ob) { return this.store.setProperty (key , JSON.stringify(ob)); } }; }
So we can create a service like this
var scriptProps = makeService (PropertiesService.getScriptProperties());
and later on, invoke it like this.
scriptProps.set (key, value)
and
var value = scriptProps.get(key)
But… you can also use exactly the same function to create another service, with the same methods, that writes to the User properties instead.
var userProps = makeService (PropertiesService.getUserProperties());
Of course you still need to keep these somewhere, so I’ll modify my original settings like this
... more settings, props: { script: makeService (PropertiesService.getScriptProperties()), doc: makeService (PropertiesService.getDocumentProperties()), user: makeService (PropertiesService.getUserProperties()) }, .. more settings
Now I can entirely change my property service source – add exponential backoff everywhere, maybe use cache or perhaps a database service simply by modifying my one makeService function.