aws / aws-appsync-community

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

Array.prototype.sort() with a compare function throwing errors #325

Open jbschooley opened 11 months ago

jbschooley commented 11 months ago

I have a list of objects that I need to sort, for example

const scores = [
  { name: "Alice", score: 85 },
  { name: "Bob", score: 92 },
  { name: "Charlie", score: 78 },
  { name: "David", score: 95 },
];

// Sort the scores array by the "score" property in ascending order
scores.sort((a, b) => a.score - b.score);

However, AppSync errors out when I try to save my code

@aws-appsync/no-function-passing: Functions can not be passed as an argument

This is problematic and doesn't make a ton of sense because 1) passing functions as arguments to other stuff like Array.prototype.reduce works fine, and 2) VTL had a sort function that could sort objects in a list by an attribute. I'm trying to rewrite all my functions in Javascript but there are some that I've had to continue using VTL for and others where I've had to find ugly creative workarounds to get sorting to work.

onlybakam commented 8 months ago

Hey @jbschooley, we currently do not support passing functions as arguments. You mentioned other issues that are not allowing you to move from VTL? could you share some of those? we'd appreciate your feedback.

jbschooley commented 8 months ago

could you share some of those?

Just talking about sorting issues. VTL can sort a list of objects based on a property, and that is essential to some of my functions. In JS that is done with Array.prototype.sort with a compare function, and since AppSync blocks that, I have to find a workaround or keep those functions in VTL.

we currently do not support passing functions as arguments

map, reduce, forEach also take functions as arguments and work perfectly fine in AppSync, so I'm not sure why sort would be singled out, especially since out of all those functions, that (and forEach) could be done with VTL.

fdesoye commented 4 days ago

@jbschooley, did you find a solution eventually? We try to sort an array of items in a DynamoDB result using a custom sort function. I took us ~.5d to find reason why our items.sort(mySortFunction); did not work. https://docs.aws.amazon.com/appsync/latest/devguide/supported-features.html#built-in-objects-functions says

Array.prototype.sort() doesn't support arguments.

As you mention, this does not make a lot of sense as map and reduce accept functions.

I wonder if there is a recommended workaround to this limitation (which should not be VTL)