FormidableLabs / groqd

A schema-unaware, runtime and type-safe query builder for GROQ.
https://commerce.nearform.com/open-source/groqd
MIT License
222 stars 17 forks source link

I wanna return just one result instead an array? #199

Closed williamneves closed 1 year ago

williamneves commented 1 year ago

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?

markomitranic commented 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);
}
williamneves commented 1 year ago

I found a way. Just put filter(0) and works. The filter opens a [] so put 0 and done 😀

heggemsnes commented 1 year ago

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)
williamneves commented 1 year ago

But the slice return array with 1 element. Filter (0) get back an object.

heggemsnes commented 1 year ago

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:

https://formidable.com/open-source/groqd/arcade?data=pokemon&code=JYWwDg9gTgLgBAbzlArgOwIooKZQJ5wC%2BcAZlBCHAERgA2AhngObnoAmVA3AFCiSyI4ARyKlylKiwhCOPbqkw58ACm5xhyqgCoqASjVwAdCWC0YuAEJ4AKnjDZNkANbYQENHoOGAzrWABjBwAGfXVDFnoAI2UEA3U0ehBsAC5hHxgoYDQmZV0AGji4ehgYen8nVIBtKkj6b2xDAEESsqcqPLS0FBBI3FyAXQL1Qn1dTiA

williamneves commented 1 year ago

Ow. Yeah. Thanks !!!

gksander commented 1 year ago

Marking this as resolved, thanks for the help @heggemsnes!