Skip to content

Commit

Permalink
feat(typeEvaluator): implement proper support for defined in filters
Browse files Browse the repository at this point in the history
  • Loading branch information
sgulseth committed Aug 29, 2024
1 parent f133d6f commit d319f1c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
9 changes: 8 additions & 1 deletion src/typeEvaluator/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,14 @@ export function handleFuncCallNode(node: FuncCallNode, scope: Scope): TypeNode {
return {type: 'string'}
}
case 'global.defined': {
return {type: 'boolean'}
const arg = walk({node: node.args[0], scope})
return mapNode(arg, scope, (node) => {
if (node.type === 'unknown') {
return {type: 'boolean'}
}

return {type: 'boolean', value: node.type !== 'null'}
})
}
case 'global.path': {
const arg = walk({node: node.args[0], scope})
Expand Down
17 changes: 14 additions & 3 deletions test/typeEvaluate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ t.test('no projection', (t) => {
t.end()
})
t.test('pipe func call', (t) => {
const query = `*[_type == "author" && defined(slug.current)] | order(_createdAt desc)`
const query = `*[_type == "author" && defined(optionalObject.subfield)] | order(_createdAt desc)`
const ast = parse(query)
const res = typeEvaluate(ast, schemas)
t.strictSame(res, {
Expand Down Expand Up @@ -650,7 +650,7 @@ t.test('attribute access', (t) => {
})

t.test('coerce reference', (t) => {
const query = `*[_type == "post" && defined(author.name)][].author`
const query = `*[_type == "post" && defined(sluger.current)][].author`
const ast = parse(query)
const res = typeEvaluate(ast, schemas)
t.strictSame(res, {
Expand Down Expand Up @@ -1696,7 +1696,7 @@ t.test('object', (t) => {
})

t.test('filter with function', (t) => {
const query = `*[_type == "author" && defined(slug.current)]`
const query = `*[_type == "author" && defined(optionalObject.subfield)]`
const ast = parse(query)
const res = typeEvaluate(ast, schemas)
t.strictSame(res, {
Expand Down Expand Up @@ -2244,6 +2244,17 @@ t.test('function: global::now', (t) => {
t.end()
})

t.test('function: global::defined', (t) => {
const query = `*[defined(sluger.current)]`
const ast = parse(query)
const res = typeEvaluate(ast, [postDocument, authorDocument, slugType])
t.strictSame(res, {
type: 'array',
of: findSchemaType('post'),
})
t.end()
})

t.test('function: global::length', (t) => {
const query = `*[_type == "author"] {
"name": global::length(name),
Expand Down

0 comments on commit d319f1c

Please sign in to comment.