Skip to content

Commit

Permalink
refactor(core): rename parentType to rootType, add clarifying comment
Browse files Browse the repository at this point in the history
  • Loading branch information
robinpyon committed Jul 20, 2023
1 parent c0aa906 commit c2ee773
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions packages/@sanity/schema/src/legacy/searchConfig/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,48 +51,49 @@ type SchemaTypeReducer = (

// eslint-disable-next-line max-params
function reduceType(
parentType: ObjectSchemaType,
rootType: ObjectSchemaType,
type: SchemaType,
reducer: SchemaTypeReducer,
acc: SearchPath[],
path = [],
maxDepth: number
) {
if (maxDepth < 0 || parentType[pathCountSymbol] < 0) {
if (maxDepth < 0 || rootType[pathCountSymbol] < 0) {
return acc
}

const accumulator = reducer(acc, type, path)
if (isArraySchemaType(type) && Array.isArray(type.of)) {
return reduceArray(parentType, type, reducer, accumulator, path, maxDepth)
return reduceArray(rootType, type, reducer, accumulator, path, maxDepth)
}

if (isObjectSchemaType(type) && Array.isArray(type.fields) && !isReferenceSchemaType(type)) {
return reduceObject(parentType, type, reducer, accumulator, path, maxDepth)
return reduceObject(rootType, type, reducer, accumulator, path, maxDepth)
}

parentType[pathCountSymbol] -= 1
// Store and mutate count on the root type to handle circular recursive structures
rootType[pathCountSymbol] -= 1
return accumulator
}

// eslint-disable-next-line max-params
function reduceArray(
parentType: ObjectSchemaType,
rootType: ObjectSchemaType,
arrayType: ArraySchemaType,
reducer: SchemaTypeReducer,
accumulator: SearchPath[],
path: SearchPath['path'],
maxDepth: number
) {
return arrayType.of.reduce(
(acc, ofType) => reduceType(parentType, ofType, reducer, acc, path, maxDepth - 1),
(acc, ofType) => reduceType(rootType, ofType, reducer, acc, path, maxDepth - 1),
accumulator
)
}

// eslint-disable-next-line max-params
function reduceObject(
parentType: ObjectSchemaType,
rootType: ObjectSchemaType,
objectType: ObjectSchemaType,
reducer: SchemaTypeReducer,
accumulator: SearchPath[],
Expand Down Expand Up @@ -121,7 +122,7 @@ function reduceObject(
const segment = ([field.name] as SearchPath['path']).concat(
isArraySchemaType(field.type) ? [[]] : []
)
return reduceType(parentType, field.type, reducer, acc, path.concat(segment), maxDepth - 1)
return reduceType(rootType, field.type, reducer, acc, path.concat(segment), maxDepth - 1)
}, accumulator)
}

Expand Down

0 comments on commit c2ee773

Please sign in to comment.