Skip to content

fix(adapter): throw helpful error for primitive arrays#1720

Open
Azarcodex wants to merge 1 commit intotypicode:mainfrom
Azarcodex:fix/better-primitive-arrays-error
Open

fix(adapter): throw helpful error for primitive arrays#1720
Azarcodex wants to merge 1 commit intotypicode:mainfrom
Azarcodex:fix/better-primitive-arrays-error

Conversation

@Azarcodex
Copy link

Fixes #1709

This PR improves the error message when json-server encounters arrays containing primitive values.

Previously, the server threw a low-level JavaScript error:
TypeError: Cannot create property 'id' on string 'role-1'

Now the server provides a clearer message explaining that arrays should contain objects so IDs can be generated.

Example valid format:
{ "roles": [{ "id": 1, "name": "role-1" }] }

This improves developer experience by making the issue easier to understand and debug.

@typicode
Copy link
Owner

Thanks for the PR. I think, instead of an error, any primitive could be wrapped into an object with an id.

Example:

[ "foo" ] -> [ { id: "...", value: "foo" } ]

@sachin-som
Copy link

Great work, and I think there can be one more edge case - we should also guard nested arrays.

In JS, arrays are objects, so a check like typeof item === 'object' && item !== null still allows []. Those entries can then get an id assigned and continue as if they were valid records.

Would it make sense to tighten the condition to explicitly reject arrays as well?

if (typeof item !== 'object' || item === null || Array.isArray(item)) {
  throw new Error(/* existing helpful message */)
}

Potential solution can be - also reject Array.isArray(item) in the validation guard so only plain object entries are accepted?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

I get TypeError: Cannot create property 'id' on string 'role-1' when use array of strings for an endpoint

3 participants