Created
July 20, 2022 18:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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