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
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.
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
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.
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.
I recommend adding this kind of validation from the beginning. It’ll make life easier.