1.1.62 • Published 2 months ago

@sanity-typed/groq-js v1.1.62

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

@sanity-typed/groq-js

NPM Downloads GitHub commit activity (branch) GitHub Repo stars GitHub contributors GitHub issues by-label Minified Size License

GitHub Sponsors

groq-js with typed GROQ Results

Page Contents

Install

npm install groq-js @sanity-typed/groq-js

Usage

Use parse and evaluate exactly as you would from groq-js. Then, use the results with the typescript types!

Typically, this isn't used directly, but via @sanity-typed/client-mock's methods that produce groq results. But it can be done directly:

your-typed-groq-js.ts:

// import { evaluate, parse } from "groq-js";
import { evaluate, parse } from "@sanity-typed/groq-js";

const input = '*[_type == "product"]{productName}';

const tree = parse(input);
/**
 *  typeof tree === {
 *    type: "Projection";
 *    base: {
 *      type: "Filter";
 *      base: {
 *        type: "Everything";
 *      };
 *      expr: {
 *        type: "OpCall";
 *        op: "==";
 *        left: {
 *          name: "_type";
 *          type: "AccessAttribute";
 *        };
 *        right: {
 *          type: "Value";
 *          value: "product";
 *        };
 *      };
 *    };
 *    expr: {
 *      type: "Object";
 *      attributes: [{
 *        type: "ObjectAttributeValue";
 *        name: "productName";
 *        value: {
 *          type: "AccessAttribute";
 *          name: "productName";
 *        };
 *      }];
 *    };
 *  }
 */

const value = await evaluate(tree, {
  dataset: [
    {
      _type: "product",
      productName: "Some Cool Product",
      // ...
    },
    {
      _type: "someOtherType",
      otherField: "foo",
      // ...
    },
  ],
});

const result = await value.get();
/**
 *  typeof result === [{
 *    productName: "Some Cool Product";
 *  }]
 */

Considerations

Using your derived types

You can also use your typed schema to keep parity with the types your typed client would receive.

npm install sanity groq-js @sanity-typed/types @sanity-typed/groq-js

product.ts:

// import { defineArrayMember, defineField, defineType } from "sanity";
import {
  defineArrayMember,
  defineField,
  defineType,
} from "@sanity-typed/types";

/** No changes using defineType, defineField, and defineArrayMember */
export const product = defineType({
  name: "product",
  type: "document",
  title: "Product",
  fields: [
    defineField({
      name: "productName",
      type: "string",
      title: "Product name",
      validation: (Rule) => Rule.required(),
    }),
    defineField({
      name: "tags",
      type: "array",
      title: "Tags for item",
      of: [
        defineArrayMember({
          type: "object",
          name: "tag",
          fields: [
            defineField({ type: "string", name: "label" }),
            defineField({ type: "string", name: "value" }),
          ],
        }),
      ],
    }),
  ],
});

sanity.config.ts:

import { deskTool } from "sanity/desk";

// import { defineConfig } from "sanity";
import { defineConfig } from "@sanity-typed/types";
import type { InferSchemaValues } from "@sanity-typed/types";

import { post } from "./schemas/post";
import { product } from "./schemas/product";

/** No changes using defineConfig */
const config = defineConfig({
  projectId: "59t1ed5o",
  dataset: "production",
  plugins: [deskTool()],
  schema: {
    types: [
      product,
      // ...
      post,
    ],
  },
});

export default config;

/** Typescript type of all types! */
export type SanityValues = InferSchemaValues<typeof config>;
/**
 *  SanityValues === {
 *    product: {
 *      _createdAt: string;
 *      _id: string;
 *      _rev: string;
 *      _type: "product";
 *      _updatedAt: string;
 *      productName: string;
 *      tags?: {
 *        _key: string;
 *        _type: "tag";
 *        label?: string;
 *        value?: string;
 *      }[];
 *    };
 *    // ... all your types!
 *  }
 */

your-typed-groq-js-with-sanity-types.ts:

// import { evaluate, parse } from "groq-js";
import { evaluate, parse } from "@sanity-typed/groq-js";
import type { DocumentValues } from "@sanity-typed/types";

import type { SanityValues } from "./sanity.config";

const input = '*[_type == "product"]{productName}';

const tree = parse(input);

const value = await evaluate(tree, {
  dataset: [
    {
      _type: "product",
      productName: "Some Cool Product",
      // ...
    },
    {
      _type: "someOtherType",
      otherField: "foo",
      // ...
    },
  ] satisfies DocumentValues<SanityValues>[],
});

const result = await value.get();
/**
 *  typeof result === {
 *    productName: string;
 *  }[]
 */

// Notice how `productName` is inferred as a `string`, not as `"Some Cool Product"`.
// Also, it's in an array as opposed to a tuple.
// This resembles the types you'd receive from @sanity-typed/client,
// which wouldn't be statically aware of `"Some Cool Product"` either.

The parsed tree changes in seemingly breaking ways

@sanity-typed/groq attempts to type its parsed types as close as possible to groq-js's parse function output. Any fixes to match it more correctly won't be considered a major change and, if groq-js changes it's output in a version update, we're likely to match it. If you're using the parsed tree's types directly, this might cause your code to break. We don't consider this a breaking change because the intent of these groq libraries is to match the types of a groq query as closely as possible.

GROQ Query results changes in seemingly breaking ways

Similar to parsing, evaluating groq queries will attempt to match how sanity actually evaluates queries. Again, any fixes to match that or changes to groq evaluation will likely not be considered a major change but, rather, a bug fix.

Typescript Errors in IDEs

Often you'll run into an issue where you get typescript errors in your IDE but, when building workspace (either you studio or app using types), there are no errors. This only occurs because your IDE is using a different version of typescript than the one in your workspace. A few debugging steps:

VSCode

Type instantiation is excessively deep and possibly infinite

🚨 CHECK Typescript Errors in IDEs FIRST!!! ISSUES WILL GET CLOSED IMMEDIATELY!!! 🚨

You might run into the dreaded Type instantiation is excessively deep and possibly infinite error when writing GROQ queries. This isn't too uncommon with more complex GROQ queries. Unfortunately, this isn't a completely avoidable problem, as typescript has limits on complexity and parsing types from a string is an inherently complex problem. A set of steps for a workaround:

  1. While not ideal, use @ts-expect-error to disable the error. You could use @ts-ignore instead, but ideally you'd like to remove the comment if a fix is released.
  2. You still likely want manual types. Intersect the returned type with whatever is missing as a patch.
  3. Create a PR in groq/src/specific-issues.test.ts with your issue. #642 is a great example for this. Try to reduce your query and config as much as possible. The goal is a minimal reproduction.
  4. If a PR isn't possible, make an issue with the same content. ie, the query and config you're using. Again, reduce them as much as possible. And then, now that you've done all the work, move it into a PR instead!
  5. I'm one person and some of these issues are quite complex. Take a stab at fixing the bug! There's a ridiculous amount of tests so it's relatively safe to try things out.

People will sometimes create a repo with their issue. Please open a PR with a minimal test instead. Without a PR there will be no tests reflecting your issue and it may appear again in a regression. Forking a github repo to make a PR is a more welcome way to contribute to an open source library.

1.1.62

2 months ago

1.1.61

3 months ago

1.1.59

3 months ago

1.1.60

3 months ago

1.1.58

4 months ago

1.1.56

4 months ago

1.1.57

4 months ago

1.1.55

5 months ago

1.1.54

5 months ago

1.1.53

5 months ago

1.1.52

5 months ago

1.1.51

5 months ago

1.1.49

5 months ago

1.1.48

5 months ago

1.1.50

5 months ago

1.1.47

5 months ago

1.1.46

5 months ago

1.1.45

5 months ago

1.1.44

5 months ago

1.1.43

5 months ago

1.1.42

5 months ago

1.1.41

5 months ago

1.1.40

5 months ago

1.1.39

5 months ago

1.1.38

5 months ago

1.1.37

5 months ago

1.1.36

5 months ago

1.1.35

5 months ago

1.1.34

5 months ago

1.1.33

6 months ago

1.1.32

6 months ago

1.1.31

6 months ago

1.1.30

6 months ago

1.1.29

6 months ago

1.1.28

7 months ago

1.1.27

7 months ago

1.1.26

7 months ago

1.1.25

7 months ago

1.1.24

7 months ago

1.1.23

7 months ago

1.1.22

7 months ago

1.1.21

7 months ago

1.1.20

7 months ago

1.1.19

7 months ago

1.1.18

7 months ago

1.1.17

7 months ago

1.1.16

7 months ago

1.1.15

7 months ago

1.1.14

7 months ago

1.1.13

8 months ago

1.1.12

8 months ago

1.1.11

8 months ago

1.1.10

8 months ago

1.1.9

8 months ago

1.1.8

8 months ago

1.1.7

8 months ago

1.1.6

8 months ago

1.1.5

8 months ago

1.1.4

8 months ago

1.1.3

8 months ago

1.1.2

8 months ago

1.1.1

8 months ago

1.1.0

8 months ago

1.0.12

8 months ago

1.0.11

8 months ago

1.0.10

8 months ago

1.0.9

8 months ago

1.0.8

8 months ago

1.0.7

8 months ago

1.0.6

8 months ago

1.0.5

8 months ago

1.0.4

8 months ago

1.0.3

8 months ago

1.0.2

8 months ago

1.0.1

8 months ago

1.0.0

8 months ago