Skip to content

Commit 522477a

Browse files
authoredMar 18, 2024
refactor(core): use path toString function from @sanity/util/paths (#5987)
### Description When deriving search weights, we previously relied on a new `pathToString` function that replicated much of the functionality already implemented in the `toString` function from `@sanity/util/paths`. The one additional piece of functionality (handling segments that are `true`, `false`, or `null`) has now been implemented in #5986. Once merged, we can remove the redundant `pathToString` function and switch to the `toString` function from `@sanity/util/paths`. ### What to review - Search requests are constructed correctly. ### Testing There are tests for this functionality in `packages/sanity/src/core/search/common/__tests__/deriveSearchWeightsFromType.test.ts`.
1 parent 561ee14 commit 522477a

File tree

1 file changed

+2
-18
lines changed

1 file changed

+2
-18
lines changed
 

‎packages/sanity/src/core/search/common/deriveSearchWeightsFromType.ts

+2-18
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {type CrossDatasetType, type SchemaType, type SearchConfiguration} from '@sanity/types'
2+
import {toString as pathToString} from '@sanity/util/paths'
23

34
import {isRecord} from '../../util'
45
import {type SearchPath, type SearchSpec} from './types'
@@ -19,7 +20,6 @@ const BASE_WEIGHTS: Record<string, Omit<SearchWeightEntry, 'path'>> = {
1920
_id: {weight: 1, type: 'string'},
2021
_type: {weight: 1, type: 'string'},
2122
}
22-
const GROQ_RESERVED_KEYWORDS = ['true', 'false', 'null']
2323
const builtInObjectTypes = ['reference', 'crossDatasetReference']
2424

2525
const getTypeChain = (type: SchemaType | undefined): SchemaType[] =>
@@ -39,22 +39,6 @@ function isSchemaType(input: SchemaType | CrossDatasetType | undefined): input i
3939
return typeof input !== 'undefined' && 'name' in input
4040
}
4141

42-
/**
43-
* Serialize field path for GROQ query.
44-
*
45-
* Reserved keywords, such as `null`, cannot be accessed using dot notation. These fields will
46-
* instead be serialized using square bracket notation.
47-
*/
48-
function pathToString(...path: string[]): string {
49-
const cleanPath = path.filter(Boolean)
50-
return cleanPath.slice(1).reduce((nextPath, segment) => {
51-
if (GROQ_RESERVED_KEYWORDS.includes(segment)) {
52-
return `${nextPath}['${segment}']`
53-
}
54-
return `${nextPath}.${segment}`
55-
}, cleanPath[0])
56-
}
57-
5842
function getLeafWeights(
5943
schemaType: SchemaType | CrossDatasetType | undefined,
6044
maxDepth: number,
@@ -84,7 +68,7 @@ function getLeafWeights(
8468
)
8569
for (const objectType of objectTypes) {
8670
for (const field of objectType.fields) {
87-
const nextPath = pathToString(path, field.name)
71+
const nextPath = pathToString([path, field.name].filter(Boolean))
8872
results.push(...traverse(field.type, nextPath, depth + 1))
8973
}
9074
}

0 commit comments

Comments
 (0)
Please sign in to comment.