realm-js
realm-js copied to clipboard
Feature suggestion: first() to fetch first available object
A lot of times, when I query realm, I only expect a single object ( for example filtering by a primary key) However, because query always returns Ream.Results (Which is array), I first need to check if the length is greater than 0 before trying to access the first item (or it will throw exception).
So instead of doing
const dogs = realm.objects('dog').filtered('id == 123')
if(dogs.length > 0){
return dogs[0]
}
return null
I propose first() which simply returns first Realm.Object or returns null
return realm.objects('dog').filtered('id == 123').first()
Furthermore, I would also recommend last() and get(index: int)
last() equivalent will be as follows
const dogs = realm.objects('dog').filtered('id == 123').slice(-1)
if(dogs.length >0){
return dogs[0]
}
return null
// or
return realm.objects('dog').filtered('id == 123').last()
get(2) equivalent will be as follows
const dogs = realm.objects('dog').filtered('id == 123')
if(dogs.length > 2){
return dogs[2]
}
return null
// or
return realm.objects('dog').filtered('id == 123').get(2)
Normally you would want a wrapper for realm so I'm adding those shorthands to my wrapper class like get(), first(), etc. I loop through all my schema classes and inject these useful functions.