aws-appsync-community icon indicating copy to clipboard operation
aws-appsync-community copied to clipboard

Add method to check if variable is of type array

Open vruffer opened this issue 1 year ago • 3 comments

Currently, there is no way to check whether a variable is an array in JS resolver functions.

Here are a couple of approaches as to how you would go about it in a browser or Nodejs environment:

  1. Use Array.isArray, which doesn't exist in APPSYNC_JS.
  2. Use arr.constructor === Array. That doesn't work, because arr.constructor is undefined in APPSYNC_JS.
  3. Check for multiple array functions. Ex:
    function isArray(x) {
      return (
        typeof x.find === 'function' &&
        typeof x.length === 'number' &&
        typeof x.sort === 'function'
      );
    }
    
    This also doesn't work because typeof any function is 'undefined' in APPSYNC_JS. This is also (IMO) the worst solution.

The functionality is present in vtl resolvers with $util.isList, so it would be nice if it was available in the JS runtime as well.

vruffer avatar May 26 '23 08:05 vruffer

This would indeed be very helpful!

MarcusCramer91 avatar Jul 13 '23 13:07 MarcusCramer91

After some trial and error I went for this hack now. Probably does not cover all cases but seems to work fine for all our use cases:

function isArray(input) {
  return typeof input === "object" && input !== null && typeof input.length === "number";
}

MarcusCramer91 avatar Jul 19 '23 07:07 MarcusCramer91

I have the same issue. In V1 of graphql we were able to work around this.

But in V2 the resolver lacks any way of detecting a json array.

BuildingFiles avatar Dec 19 '23 18:12 BuildingFiles