Skip to content

Instantly share code, notes, and snippets.

@SimeonGriggs
Created July 20, 2022 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimeonGriggs/0b890d6be5f5fb943c3e07b5fc9fc6fa to your computer and use it in GitHub Desktop.
Save SimeonGriggs/0b890d6be5f5fb943c3e07b5fc9fc6fa to your computer and use it in GitHub Desktop.
Takes in a Sanity schema.get(`type`) to return a flat list of every possible field path
function getInnerFieldTypeNames(of = []) {
if (!of?.find((field) => field.fields)) {
return ``
}
const arrayObjectTypeNames = of.map((field) => field.name)
return arrayObjectTypeNames.join(`|`)
}
function getFieldPathsFromArray(arr = [], prefix = ``) {
return arr.reduce((acc, cur) => {
const newPath = [
prefix ? `${prefix}${cur.name}` : cur.name,
// Is an array of objects
cur.type.jsonType === `array` && cur?.type?.of?.find((type) => type.fields) ? `[]` : ``,
]
.filter(Boolean)
.join(``)
const arrayRootPath =
cur.type.jsonType === `array`
? newPath.replace(`[]`, `[${getInnerFieldTypeNames(cur.type.of)}]`)
: ``
if (cur.name && !acc.includes(newPath)) {
if (arrayRootPath) {
acc.push(arrayRootPath)
} else {
acc.push(newPath)
}
}
// Retrieve nested object fields
if (cur.type.fields) {
acc.push(...getFieldPathsFromArray(cur.type.fields, `${newPath}.`))
}
// Retrieve nested arrays of objects
if (cur.type.of) {
cur.type.of
.filter((type) => type.fields)
.forEach((type) => {
// Put the _type name in each in array
type.fields.forEach((field) => {
const newPathWithType = newPath.replace(`[]`, `[_type == "${type.name}"]`)
acc.push(...getFieldPathsFromArray([field], `${newPathWithType}.`))
})
})
}
return acc
}, [])
}
export default function getUniqueFieldPaths(type) {
const paths = new Set()
if (type.fields) {
const newPaths = getFieldPathsFromArray(type.fields)
if (newPaths.length) {
newPaths.forEach((path) => paths.add(path))
}
}
return paths.size ? Array.from(paths) : []
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment