Closed williamneves closed 1 year ago
@williamneves afaik there is no built in way to do this. There should be.
I use a manual check in my repository level functions, like this:
function firstResult<T>(results: T[]): T {
const result = results[0];
if (!result || results.length !== 1) throw Error("No results found.");
return result;
}
Then later in my repository code:
/**
* Fetches a single post object with exact slug match.
* Throws if no objects found.
*
* @example
* const post = await getPost();
* { _id: "123", title: "Lorem Ipsum", slug: "lorem-ipsum" }
*/
export async function getPost(slug: string) {
const posts = await runQuery(
q("*")
.filterByType("post")
.filter("slug.current == $slug")
.grab(PostSelection),
{slug}
);
return firstResult(posts);
}
I found a way. Just put filter(0) and works. The filter opens a [] so put 0 and done 😀
I guess you could do this but, the reccomended would be to do slice(0)
like this:
q("*").filterByType("post").grab({_id: q.string()}).slice(0)
But the slice return array with 1 element. Filter (0) get back an object.
What version are you using? You can see that the returned data when using slice(0) is a object and not an array with a single item:
Ow. Yeah. Thanks !!!
Marking this as resolved, thanks for the help @heggemsnes!
I wanna return just one result instead an array, normally I put [0] at the end of the groq query, but how to do with grod?