fast_jsonapi
fast_jsonapi copied to clipboard
Why the "id" field is a string?
- How to change it nicely to integer?
- Is there a strong reason that this should be string?
It's dictated by the spec. ref: https://jsonapi.org/format/1.0/#document-resource-object-identification
Every resource object MUST contain an id member and a type member. The values of the id and type members MUST be strings.
You could think about type of id field in terms of operations defined on the type. Integers can be added, substracted, etc., while adding id's together bear no sense at all. IMO main reason why Rails cast id's as integers is because they are integers in the DB, and that's because of performance reasons - indexes on int's are more compact and faster
One argument for using ints as id's would be performance - it's faster to compare ints than strings. Now every client of my API works a little slower just because I send strings instead of integers. I guess it's a negligible difference but still worth asking about.
Good question to take up with the designers of the JSON API spec. I appreciate that this package sticks to the spec.
There are some cases when id
column could be GUID or have composite keys, e.g. in cases when clustering/sharding is necessary.
Making it integer by default means this package would not work nicely and all kind of weird behaviour could happen:
irb(main):024:0> SecureRandom.uuid
=> "757e81ad-755d-479c-aabe-640cb0860893"
irb(main):025:0> SecureRandom.uuid.to_i
=> 0