aws / aws-appsync-community

The AWS AppSync community
https://aws.amazon.com/appsync
Apache License 2.0
506 stars 32 forks source link

Add method to check if variable is of type array #295

Open vruffer opened 1 year ago

vruffer commented 1 year ago

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.

MarcusCramer91 commented 1 year ago

This would indeed be very helpful!

MarcusCramer91 commented 1 year ago

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";
}
BuildingFiles commented 8 months ago

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.