herbsjs / gotu

Entities - Create your Entity and enjoy an elegant validation and serialization
Other
11 stars 19 forks source link

Bug at toJSON method when trying to return an entity that has an array of strings #41

Closed cpp-vortx closed 3 years ago

cpp-vortx commented 3 years ago

Describe the bug When trying to return an entity that has an array of strings the gotu method "toJSON" treats each value of the array as an object and turn them into objects.

To Reproduce Steps to reproduce the behavior:

  1. Create an entity that has an array of strings
  2. Instance the entity
  3. use the toJSON method from the instance
  4. See error

Expected behavior Expected the array of strings to continue being an array of strings.

Screenshots Entity image

Entity toJSON response image

jhomarolo commented 3 years ago

Thanks @cpp-vortx for the contribution.

But I wanted to understand the issue a little better. What is the entrance to the entity, the actual response and the expected response? Because I saw you just put the response.

Thanks

cpp-vortx commented 3 years ago

Right, I've made this example to show you the issue but its not the exactly one in which I discovered the bug.

Entity definition:

const Ent = entity("Testing primitive type arrays", {
  field1: field(String),
  array: field([String]),
})

Entity instance:

const testing = new Ent()

testing.field1 = "Normal field"

testing.array = ["This", "is", "an", "array"]

Now using the toJSON method thats the current response:

{
  field1: 'Normal field',
  array: [
    { '0': 'T', '1': 'h', '2': 'i', '3': 's' },
    { '0': 'i', '1': 's' },
    { '0': 'a', '1': 'n' },
    { '0': 'a', '1': 'r', '2': 'r', '3': 'a', '4': 'y' }
  ]
}

It turns the strings into a tuple like object...

The expected response would be: { field1: 'Normal field', array: [ 'This', 'is', 'an', 'array' ] }

And this is caused by these two lines in toJSON method of BaseEntity: https://github.com/herbsjs/gotu/blob/master/src/baseEntity.js#L79-L80

jhomarolo commented 3 years ago

Now I understand perfectly, thank you.

Can you open a PR to fix this bug? Need some help?

cpp-vortx commented 3 years ago

Sure!

I already have the fix made, just gonna open the PR

Thanks