Accidentally accessing non-existent properties and tracking down where that is happening is a big time waster that a JavaScript proxy can help you track down.
In Fix Apps Script file order problems with Exports I described how to organize your Apps Script code better using an Exports object to describe and modify the classes and namespaces in your project, or in libraries your project uses. Now that you have this centralized view, it’s easy to add checks on attempts to access properties that don’t exist in your target object.
Proxy and Reflect
I’ve done a few articles on the usefulness of JavaScript Proxy – for example (SuperFetch – a proxy enhancement to Apps Script UrlFetch, JavaScript proxy, fiddling with Apps Script objects and custom errors, Proxy implementation of Apps Script GraphQL Class, Resuscitating the Apps Script execution transcript – JavaScript Proxy and Reflect to the rescue).
This is a very basic one, and will show how to modify your Exports object to validate and report on accidental attempts to access missing properties in an object.
Example
Let’s say we have an Exports object that contains this reference to a class
We’d create an instance like this
So far so good, but let’s say that you later try to access a non existent property
The first would fail silently and the second would complain about ‘undefined not a function’. It would be much handier if instead it warned you that you were trying to access ‘badProperty’ and ‘getBadly’. That’s where a JavaScript proxy comes in.
Applying a Proxy
Let’s now enhance the Exports to generate a new instance of the store class
And create an instance like this
We’ll get a new instance of the Store class, but still with no protection for invalid property access. Let’s add a proxy to that.
Now, instead of an instance of the Store, we get an instance of Proxy, which has a Store instance as its target. However, we still haven’t done anything about detecting invalid property accesses. The second argument to Proxy() allows you to set up an intercept to property accesses.
The same ‘validateProperty’ object in Exports can now be applied to any other of your Exported classes or namespaces in the same way to check that any property you try to access.
If you do it will throw an error and explain which property was invalid – like this.
Unit testing
When developing a project I always do unit testing as I go along – right from the start. See Simple but powerful Apps Script Unit Test library for the library I use. Here’s a small clip on how to use it to test the proxy implementation.
Summary
I recommend adding this kind of validation from the beginning. It’ll make life easier.