0

I've seen in a few apis where when an array value is expected, then when it's only one value the library/framework will unwrap it from its array and just send the single value.

What is the point of this?

At initial glance I would guess that it has the appearance of being cleaner and more intuitive, since why should an array have one value?

But now there needs to be double the work. The library/framework needs to write code to unwrap the single value from its array. And the one consuming the library/framework/api needs to handle either an array or single value.

Currently in Javascript when consuming this api https://swagger.io/docs/specification/serialization/, if the url looks like this /api/tasks?filter%5Bdue_date%5D=pastDue&filter%5Bdue_date%5D=dueToday&filter%5Bdue_date%5D=2022-11-09T14:57:35.303Z then the values get sent back as...

filter: { 
  due_date: [ 
    'pastDue',
    'dueToday',
    '2022-11-09T14:57:35.303Z',
  ], 
}, 

But if the url is /api/tasks?filter%5Bdue_date%5D=pastDue this it's sent back as...

filter: { 
  due_date: 'pastDue',
}, 

I handle it by doing [values].flat(). Like this it's always a one-dimensional array. (source- https://stackoverflow.com/a/58553894/9530790)

Another way can be [].concat(values). (source- https://stackoverflow.com/a/59220422/9530790)

Maybe I'm doing this wrong and there's a better way to handle this type of convention, that would make this more intuitive and understandable. But for now why not just keep it the same with everything being an array even if its only one value?

shmuels
  • 1,039
  • 1
  • 9
  • 22
  • Forgive my ignorance, I don't fully understand. Can you please explain how? Maybe with an example? – shmuels Nov 10 '22 at 15:10
  • I've seen function interfaces that can take both `items:T[]` but also `...items:T[]` where your input is always `T[]` but either as a single array, or as multiple seperate arguments. – Thomas Nov 10 '22 at 15:15
  • @MisterJojo: Completely lost me there. – Robert Harvey Nov 10 '22 at 15:18
  • I haven't encountered this as far as I can recall, but I'm with you: it seems like poor taste by the API. – danh Nov 10 '22 at 15:38

0 Answers0