Giter Site home page Giter Site logo

groq-js's Introduction

GROQ-JS

npm stat npm version gzip size size

GROQ-JS is a JavaScript implementation of GROQ which follows the official specification.

import {parse, evaluate} from 'groq-js'

let input = '*[_type == "user"]{name}'

// Returns an ESTree-inspired syntax tree
let tree = parse(input)

let dataset = [
  {_type: 'user', name: 'Michael'},
  {_type: 'company', name: 'Bluth Company'},
]

// Evaluate a tree against a dataset
let value = await evaluate(tree, {dataset})

// Gather everything into one JavaScript object
let result = await value.get()

console.log(result)

Table of contents:

Installation

npm i groq-js
yarn add groq-js
pnpm install groq-js

Documentation

See API.md for the public API.

Learn GROQ

Free egghead GROQ introduction course by John Lindquist

Versioning

GROQ

The GROQ spec version is independent of the groq-js library version. When you import groq-js you need to be explicit on which GROQ version you want to use. The GROQ version is tied to the groq-spec. This allows us to update the library and its API independent of the GROQ version.

GROQ-JS

GROQ-JS follows SemVer. See the changelog for recent changes. This is an "experimental" release and anything may change at any time, but we're trying to keep changes as minimal as possible:

  • The public API of the parser/evaluator will most likely stay the same in future versions.
  • The syntax tree is not considered a public API and may change at any time.
  • This package always implements the latest version of GROQ according to the specification.

Releasing a new version of GROQ-JS

Run the "CI & Release" workflow. Make sure to select the main branch and check "Release new version".

Version will be automatically bumped based on conventional commits since the last release.

Semantic release will only release on configured branches, so it is safe to run release on any branch.

Note: commits with chore: will be ignored. If you want updated dependencies to trigger a new version, use fix(deps): instead.

License

MIT © Sanity.io

Tests

Tests are written in Jest:

# Install dependencies
npm i

# Run tests
npm test

You can also generate tests from the official GROQ test suite:

# Fetch and generate test file:
./test/generate.sh

# Run tests as usual:
npm test

You can generate tests from a specific version:

GROQTEST_SUITE_VERSION=v0.1.33 ./test/generate.sh

or from a file (as generated by the test suite):

GROQTEST_SUITE=suite.ndjson ./test/generate.sh

The test arguments are passed to tap, so you can use arguments, e.g. to run a specific set of tests:

npm test -g "array::join"

groq-js's People

Contributors

armandabric avatar asbjornh avatar atombender avatar billymoon avatar codebymatt avatar dcilke avatar dios-david avatar ecospark[bot] avatar j33ty avatar judofyr avatar kmelve avatar renovate[bot] avatar rexxars avatar runeb avatar saiichihashimoto avatar semantic-release-bot avatar sgulseth avatar stipsan avatar tzhelyazkova avatar zacjones93 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

groq-js's Issues

.Net support for groq

Hi,

Good work on this repo. I was curious if anybody has attempted a groq.net yet. Kindly let me know.

Syntax error when using dereferencing operator

Hi, I spent a few hours fighting this issue when trying to use next-sanity's previewSubscriptionHook. I traced it down to this package. Basically there is a syntax error for this query:

*[_id == 'siteSettings'][0] {
    ...,
    icon {
        ..., 
        asset -> { _id, metadata }
    }
}

Everything works when I remove the spaces in between the deferencing operator ->:

*[_id == 'siteSettings'][0] {
    ...,
    icon {
        ..., 
        asset->{ _id, metadata }
    }
}

This is a problem because the Sanity Studio Vision plugin allows the spaces. Fetching using Sanity Client also allows spaces between the derefencing operator.

This leads me to believe that the spaces between the operator is valid syntax, which means that it's a bug in groq-js.

If it is actually not valid syntax to have the spaces, then I think the aforementioned libraries and studio plugin should reject the syntax or print a warning for the developer.

Accept different dataset names

Right now the only acceptable name for the data is dataset. It would be much more useful to accept other names.

Usign let dataset works as expected:

...
let dataset = await fs.readJson("./places.json");
...
let value = await evaluate(tree, { dataset });

Using let places doesn't work:

...
let places = await fs.readJson("./places.json");
...
let value = await evaluate(tree, { places });

This will help to call data that is already available.


Below is the example code with changed dataset name. It doesn't work and returns null:

import { parse, evaluate } from "groq-js";

let input = `*[_type == 'user']{name}`;

let dataset2 = [
  { _type: "user", name: "Michael" },
  { _type: "company", name: "Bluth Company" },
];

// Returns an ESTree-inspired syntax tree
let tree = parse(input);

// Evaluate a tree against a dataset
let value = await evaluate(tree, { dataset2 });

// Gather everything into one JavaScript object
let result = await value.get();

console.log(result);

filtering performance question

More of a performance question than a bug report, but I don't see a more suitable location.

I get that groq has capabilities that JMESPath does not, but as they do share some similarities I'm comparing them.

I need to filter some JSONs. For this test I'm working with 10k entries. Here is an example that shows 2 records. The real data has a few more columns, some with a bit of nested complexity, but my queries don't touch any of that.

[{
  "base__uid": 1664200,
  "base__chrom": "chr6",
  "base__pos": 1312763,
  "base__ref_base": "T"
},{
  "base__uid": 1669279,
  "base__chrom": "chr6",
  "base__pos": 4116028,
  "base__ref_base": "G"
}]

In JMESPath this query:

[?base__chrom=='chr6']|[?base__pos>=`1000000`]|[?base__pos<=`5000000`]

takes 7ms

and it seems to be equivalent to this groq query

*[base__chrom=='chr6' && base__pos>= 1000000 && base__pos <= 5000000]

which takes 5662ms.

So far my queries aren't particularly complex, but regardless of their complexity, runtime for groq seems linear and dominated by the number of records in my input. At 100k records, it always takes ~30s. 10k records = ~3s. etc.

I'm filtering with this code

       value = await evaluate(groqtree, {  dataset: allrec  });
       accepted = await value.get();

Do my performance numbers seem appropriate? Anything I should dig into in hopes of getting better performance from groq?

License?

There doesn't seem to be a LICENSE / COPYING file in the project, nor does it look like the license field in package.json is set.

The Readme does mention the license but it would be nice if there was both a LICENSE file as well as the appropriate field in package.json.

Groq query stops to support parameters in slicing expression

Description
Starting from 0.3.0 version groq-js doesn't support

To Reproduce
Make query:
evaluate(parse('*[$start..$end]'), { dataset: [], params: { start: 0, end: 1 } })

Expected behavior
The result should be the same as for:
evaluate(parse('*[0..1]'), { dataset: [] })

Actual behavior
GroqQueryError: slicing must use constant numbers

GroqJS version:
0.3.0 oor highere

Problem is not reproducible with groq-js version 0.2.0.

Export DateTime class

I'd love to have the DateTime class exported. I'm working on @sanity-typed/groq-js and my testing would be more complete/possible with instances of the DateTime class to compare against.

references() function does not traverse arrays

References does not seem to find references nested under arrays, this works when querying against sanity proper.
an example to illustrate:

const { parse, evaluate } = require('groq-js');

const fetch = async (dataset, query, params) => {
    const tree = parse(query);
    const value = await evaluate(tree, { dataset, params });
    return value.get();
};
const test = async () => {
    const res = await fetch(
        [
            {
                _type: 'myObj',
                _id: '123',
            },
            {
                _type: 'container',
                _id: '321',
                myRef: {
                    _type: 'reference',
                    _ref: '123',
                },
            },
        ],
        `*[references("123")]`
    );
    console.log('direct result', res);

    const resNested = await fetch(
        [
            {
                _type: 'myObj',
                _id: '123',
            },
            {
                _type: 'container',
                _id: '321',
                myContainer: {
                    _type: 'nestedContainer',
                    myRef: {
                        _type: 'reference',
                        _ref: '123',
                    },
                },
            },
        ],
        `*[references("123")]`
    );
    console.log('nested result', resNested);

    const resArray = await fetch(
        [
            {
                type: 'myObj',
                _id: '123',
            },
            {
                type: 'container',
                _id: '321',
                myRefs: [
                    {
                        _type: 'reference',
                        _ref: '123',
                    },
                ],
            },
        ],
        `*[_type == references("123")]`
    );
    console.log('array result', resArray);
};
test();

this outputs

direct result [
  {
    _type: 'container',
    _id: '321',
    myRef: { _type: 'reference', _ref: '123' }
  }
]
nested result [
  {
    _type: 'container',
    _id: '321',
    myContainer: { _type: 'nestedContainer', myRef: [Object] }
  }
]
array result []

i would have expected array result also to be the container.

using groq-js 0.1.4

Top-level `OpCall` does not return expected results

I'm building some tooling on top of groq-js, and have discovered that the evaluator does not correctly evaluate top-level OpCall nodes:

(() => {
    const condition = parse(`_type == "123"`);
    return Promise.all([
    	{_type: '123'},
    	{_type: 'Something else'}
    ].map(x => evaluate(condition, {dataset:x}).then(r => r.get())));
})(); // seems to be a bug in `groq-js`; should return [true, false] but presently returns [false, false]

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.


Using a curated preset maintained by


Sanity: The Composable Content Cloud

Pending Approval

These branches will be created by Renovate only once you click their checkbox below.

  • chore(deps): update non-major (@sanity/pkg-utils, @typescript-eslint/eslint-plugin, @typescript-eslint/parser)
  • chore(deps): lock file maintenance
  • 🔐 Create all pending approval PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/browserslist.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/create-github-app-token v1
  • peter-evans/create-pull-request v6@9153d834b60caba6d51c9b9510b087acf9f33f83
.github/workflows/test.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/create-github-app-token v1
  • actions/checkout v4
  • actions/setup-node v4
npm
package.json
  • @sanity/pkg-utils 6.7.1
  • @sanity/semantic-release-preset ^4.1.7
  • @types/tap ^15.0.11
  • @typescript-eslint/eslint-plugin ^7.7.0
  • @typescript-eslint/parser ^7.7.0
  • eslint ^8.57.0
  • eslint-config-prettier ^9.1.0
  • eslint-config-sanity ^7.1.2
  • eslint-plugin-prettier ^5.1.3
  • eslint-plugin-simple-import-sort ^12.1.0
  • ndjson ^2.0.0
  • prettier ^3.2.5
  • prettier-plugin-packagejson ^2.5.0
  • rimraf ^5.0.0
  • tap ^16.3.10
  • tsx ^4.7.2
  • typescript 5.4.5
  • node >= 14

  • Check this box to trigger a request for Renovate to run again on this repository

Missing feature: string concatenation

This works:

$ curl -s http://api.nobelprize.org/v1/laureate.json | jq .laureates | groq '*[gender == "female" && "physics" in prizes[].category]{firstname, surname}' --pretty

I'm pretty sure that the very similar query (with string concatenation of firstname and surname)

$ curl -s http://api.nobelprize.org/v1/laureate.json | jq .laureates | groq '*[gender == "female" && "physics" in prizes[].category]{firstname + surname}' --pretty

should work as per https://www.sanity.io/docs/query-cheat-sheet#arithmetic-and-concatenation-5a9dcaf4e63e . I'm not sure if the following should work but it'd be great if it did (string concat with space in between):

$ curl -s http://api.nobelprize.org/v1/laureate.json | jq .laureates | groq '*[gender == "female" && "physics" in prizes[].category]{firstname + " " + surname}' --pretty

T'would be great to add this. Thanks!

All of a sudden receiving heap limit errors in node

Very strange issue here. I've been using groq-js to run queries during Gatsby's build process and so far everything has worked fine. Then all of a sudden today I getting the following error:

success building schema - 0.151s
⠋ createPages

<--- Last few GCs --->

[6052:0x1045ed000]    35701 ms: Scavenge 4057.2 (4064.9) -> 4057.0 (4065.4) MB, 3.6 / 0.0 ms  (average mu = 0.137, current mu = 0.134) allocation failure 
[6052:0x1045ed000]    35705 ms: Scavenge 4057.8 (4065.4) -> 4057.6 (4066.1) MB, 3.4 / 0.0 ms  (average mu = 0.137, current mu = 0.134) allocation failure 
[6052:0x1045ed000]    35709 ms: Scavenge 4058.4 (4066.1) -> 4058.2 (4066.4) MB, 3.4 / 0.0 ms  (average mu = 0.137, current mu = 0.134) allocation failure 


<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0x10123d2a5 node::Abort() (.cold.1) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
 2: 0x10009dd29 node::Abort() [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
 3: 0x10009de8f node::OnFatalError(char const*, char const*) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
 4: 0x1001d9db7 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
 5: 0x1001d9d57 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
 6: 0x10036c885 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
 7: 0x10036e11a v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
 8: 0x10036a075 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
 9: 0x100367afe v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
10: 0x100374e3a v8::internal::Heap::AllocateRawWithLightRetrySlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
11: 0x100374ec1 v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
12: 0x1003412a7 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
13: 0x1006a8050 v8::internal::Runtime_AllocateInOldGeneration(int, unsigned long*, v8::internal::Isolate*) [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]
14: 0x1009f3899 Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit [/Users/kmcaloon/.nvm/versions/node/v14.4.0/bin/node]

After much debugging, I found that by removing the following code everything works fine:

const groq = require( 'groq-js' );
...
const parsedQuery = groq.parse( query );
const value = await groq.evaluate( parsedQuery, { dataset } );
const result = await value.get();

It gets stuck and then eventually throws the error during value.get(). What's strange is that it has been fine until now, and it breaks with any query or dataset. I tried running the example from the docs and it caused the same issue. Nothing that I can think of changed on my system since it last worked, and I have tried using different versions of the package. Has anyone run into a similar issue before?

Possible issue with new GROQ functions

In my getStaticProps my query works great, except when I introduce projections making use of string::startsWith or array::unique.

There's a spot midway down the page component where I say

if (router.isFallback || !singleVendorSanityData) {
        return <main><Spinner /></main>
}

and it hangs endlessly with nothing indicating an error except for, only sometimes,
TypeError: Cannot read properties of undefined (reading 'getReader')

It's a rather large query so I figured maybe there was a silent timeout or something, but the only thing that seems to make the difference is the inclusion of those two functions. The syntax highlighting when using the groq function with the backticks highlights one of the double-colons with red.

I used "match" instead of "startsWith" and cull the duplicates on the front end, so there is a workaround, but it'd be lovely to be able to use the feature set as is.

I thought maybe it would be an API thing but config is at or past the one in Vision from late 2021.

Support for parameters

Hi, understand this is work in progress, but are parameters supported yet?
when i run this snippet

const input = '*[name == $name]{name}';
const tree = parse(input);

i get this error

Error: Unknown handler: param
    at MarkProcessor.process (/Users/henrik.rudstrom/Dev/amedia/orientering/web/node_modules/groq-js/src/markProcessor.js:29:22)

and more generally is this library going to be usable in the near future? would love to use it to write unit tests for my groq queries.

Throw on missing parameters

I expected the following to throw an error:

let query = `name == $name`
let tree = parse(query)
let value = await evaluate(tree, {dataset: [], params: {}})
let data = await value.get()

...but it actually results in true

I think it'd be better if undefined parameters would throw an error:

Param $name referenced, but not provided

I can not figure out how to fetch data from GROQ

I may be wrong, but your API seems to be built only for pushing data to GROQ. I need is to fetch data from Sanity GROQ and use it in my demo Svelt app. Maybe I am using the API wrong.

  onMount(async () => {
    // let dataset = [{_type: "cms", name: "sanity"}]
    let dataset = "*"
    // ^ neither of these are giving me usable data
    let tree = parse(query)
    console.log({tree});
    let value = await evaluate(tree, {dataset})
    console.log({value});
    let data = await value.get()
    console.log(data);
  });

yeilds: null

  onMount(async () => {
    let dataset = [{_type: "cms", name: "sanity"}]
    //let dataset = "*"
    // ^ neither of these are giving me usable data
    let tree = parse(query)
    console.log({tree});
    let value = await evaluate(tree, {dataset})
    console.log({value});
    let data = await value.get()
    console.log(data);
  });

yeilds:

  (1) […]
​    0: Object { name: "sanity" }
​       length: 1
​        <prototype>: [

Is your API able to give me an array of objects containing all the data in my Sanity GROQ database? If so, how. If not, is there another resource that can help me?

Filter on a non-array should return the base value.

const query = "false[true]";
const tree = parse(query);
const result = await (await evaluate(tree)).get();

console.log(result);
// Should be false, is null

According to the GROQ spec's section on Filter, if the base is not an array, the base should be returned. In this case, it's returning a null, which isn't correct.

Bug: can't combine filtering and attribute value array creation with no object wrapper

To reproduce:

  1. Visit https://groq.dev/4927196f-b502-4a75-a962-39c6dcc2e4ef
  2. Replace middle textarea's content with this text:
// Works
*[completed == true]{title}

// Works
//*[].title

// But combining them doesn't work
//*[completed == true].title
  1. Uncomment each of the 3 examples in turn (and comment out the one above it)

  2. You'll see that *[completed == true].title results in null rather than a populated array of strings that are the titles of completed tasks.

filtering after following a reference breaking

First of all, thank you all for the work that you're doing. Sanity is awesome and I love working with GROQ.

I've ran into an issue where I'm a little confused what changed/why a query of mine is breaking.

We have course pages on egghead that grab meta data from sanity. Here's the query on GitHub.

The part in question is the instructor field.

'instructor': collaborators[]->[role == 'instructor'][0]{
    'full_name': person->name,
    'avatar_url': person->image.url,
    'slug': person->slug.current
  },

On a course we have a reference to collaborators that have a role. We want to grab the first instructor on each course and display their information.

Up until recently, this query has been working but now if we apply any filters after following the reference it returns null

I recorded a quick video showing the behavior

https://www.loom.com/share/09b3b0d577fd4b079fbfeee032962fb9

Am I missing something? I'm not sure how to debug this.

Unknown function: path

Got another one:
running this query

const query = groq`*[
        _type == 'staticPage' &&
        !(_id in path("drafts.**")) &&
        slug.current == $slug &&
        publication._ref == $publicationId
    ][0]`

produces this error:

Unknown function: path

at FuncCall (node_modules/groq-js/src/evaluator/index.js:78:22)
      at execute (node_modules/groq-js/src/evaluator/index.js:46:10)
      at inop (node_modules/groq-js/src/evaluator/operators.js:75:23)
      at Parenthesis (node_modules/groq-js/src/evaluator/index.js:220:21)
      at Not (node_modules/groq-js/src/evaluator/index.js:382:17)
      at And (node_modules/groq-js/src/evaluator/index.js:365:22)
      at And (node_modules/groq-js/src/evaluator/index.js:364:21)
      at And (node_modules/groq-js/src/evaluator/index.js:364:21)
      at StreamValue._generator (node_modules/groq-js/src/evaluator/index.js:98:27)
      at fetch (node_modules/groq-js/src/evaluator/value.js:131:22)

is this just as quick a fix? ;)

GROQ `| order(name asc)` sorts uppercase then lowercase e.g. ABGc not ABcG

I’m not sure if this is a bug; but it’s not what I would expect personally. Is there a logic for this decision that makes sense in other contexts/cultures/languages? I’m doing in the limited context of ordering a list of ‘collaborator’ documents alphabetically. It’s important they’re alphabetised irrespective of case because some people use lowercase as a stylistic decision but you’d still expect to find them listed under ‘c’.

To be clear, current order sorted by GROQ is:

A
Akera Engineers

G
Gardiner and Theobald
Gerald Eve

C
cc|be

But I would expect:

A
Akera Engineers

C
cc|be

G
Gardiner and Theobald
Gerald Eve

Accessing nested objects fails

First of all, thank you for the amazing work.

When accessing properties deep nested inside object, query fails silently with null data.

simple way to reproduce :

describe('failing', () => {
  it('array', async () => {
    const dataset = {
      users: [
        { name: 'foo', age: 12 },
        { name: 'bar', age: 30 },
      ],
    };
    const query = `*.users`;
    const tree = parse(query);
    const value = await evaluate(tree, { dataset });
    const data = await value.get();
    expect(data).toStrictEqual([
      { name: 'foo', age: 12 },
      { name: 'bar', age: 30 },
    ]);
  });
});

Behaviour in GROQ playground

image

Behaviour in jest

image

Unknown function: now()

now() is currently not implemented. I'm considering implementing it together with the planned new DateTime functions: sanity-io/GROQ#7.

Feel free to comment here if you need it even before that.

Allow reference resolution to be configured

I would like to specify what key that the _ref implementation searches on.

Right now, the following data structure:

[
  {
    _id: "1",
    text: "Foo",
    parent: {
      _ref: "2"
    }
  },
  {
    _id: "1",
    text: "Bar"
  },
]

When running it through a groq query like so: * { parent-> } it only resolve on _id. I want to be able to resolve on any key.

groq-js results inconsistent with "GROQ Arcade"

Hello! I was looking for an easy way to query and filter JSON data and I discovered your library a couple days ago. I really like the expression syntax and after playing around with it on groq.dev, I was really encouraged that it was the answer to all my prayers :) I installed groq-js in my project and created a test using the example code here (https://www.npmjs.com/package/groq-js) replacing the data with my own. (Slightly transformed data from Overpass/OSM.)

Using the same dataset and expression, I found that the results in my local test were not the same as what I got on GROQ Arcade. The local test results were missing an attibute. (See attached code with data: groqTest.zip)

On GROQ Arcade, the result was (as expected):
[ [ { "name": "111A Avenue", "total": 3 } ], [ { "name": "153B Street", "total": 3 } ], [ { "name": "109 Avenue", "total": 3 } ] ]

But the local test produced:
[ { total: 3 }, { total: 3 }, { total: 3 } ]

What happened to the "name" attribute? It also seems to have removed the inner, single-element arrays. Am I doing something wrong? Is GROQ Arcade using a different version?

Thanks!

FuncCallNode should retain namespace

The FuncCallNode, when parsed, strips the namespace from the name. Even though the correct func is applied to the parsed node, it's impossible to be certain of which function it is, notably with something like now() that could be global or dateTime.

I'm mainly focused on this because I'm making @sanity-typed/groq-js, that concerns itself with the types, not the runtime result of func. The FuncCallNode becomes impossible with that.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.