Skip to content

Commit

Permalink
refactor(core): use path toString function from @sanity/util/paths (
Browse files Browse the repository at this point in the history
#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`.
  • Loading branch information
juice49 authored Mar 18, 2024
1 parent 561ee14 commit 522477a
Showing 1 changed file with 2 additions and 18 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {type CrossDatasetType, type SchemaType, type SearchConfiguration} from '@sanity/types'
import {toString as pathToString} from '@sanity/util/paths'

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

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

/**
* Serialize field path for GROQ query.
*
* Reserved keywords, such as `null`, cannot be accessed using dot notation. These fields will
* instead be serialized using square bracket notation.
*/
function pathToString(...path: string[]): string {
const cleanPath = path.filter(Boolean)
return cleanPath.slice(1).reduce((nextPath, segment) => {
if (GROQ_RESERVED_KEYWORDS.includes(segment)) {
return `${nextPath}['${segment}']`
}
return `${nextPath}.${segment}`
}, cleanPath[0])
}

function getLeafWeights(
schemaType: SchemaType | CrossDatasetType | undefined,
maxDepth: number,
Expand Down Expand Up @@ -84,7 +68,7 @@ function getLeafWeights(
)
for (const objectType of objectTypes) {
for (const field of objectType.fields) {
const nextPath = pathToString(path, field.name)
const nextPath = pathToString([path, field.name].filter(Boolean))
results.push(...traverse(field.type, nextPath, depth + 1))
}
}
Expand Down

0 comments on commit 522477a

Please sign in to comment.