Skip to content

Commit

Permalink
fix(typegen): dont treat all document type refs as references (#7366)
Browse files Browse the repository at this point in the history
It's possible to reference a document the same way as an object is
referenced. However, they will not get the builtin attributes that are
available on a document stored in Content Lake. The Studio treats it as
a "normal" object. Since we are making some assumption around document
we are inlining the whole object whenever this happens, it's an edge
case and not a recommended pattern as it is mixing concerns.
  • Loading branch information
sgulseth authored and cngonzalez committed Aug 20, 2024
1 parent 5e723a4 commit d35f9ad
Show file tree
Hide file tree
Showing 3 changed files with 720 additions and 37 deletions.
16 changes: 12 additions & 4 deletions packages/@sanity/schema/src/sanity/extractSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export function extractSchema(
extractOptions: ExtractSchemaOptions = {},
): SchemaType {
const inlineFields = new Set<SanitySchemaType>()
const documentTypes = new Map<string, DocumentSchemaType>()
const schema: SchemaType = []

// get a list of all the types in the schema, sorted by their dependencies. This ensures that when we check for inline/reference types, we have already processed the type
Expand All @@ -83,6 +84,9 @@ export function extractSchema(
if (base.type === 'type') {
inlineFields.add(schemaType)
}
if (base.type === 'document') {
documentTypes.set(typeName, base)
}

schema.push(base)
})
Expand Down Expand Up @@ -147,10 +151,6 @@ export function extractSchema(
}

function convertSchemaType(schemaType: SanitySchemaType): TypeNode {
if (lastType(schemaType)?.name === 'document') {
return createReferenceTypeNode(schemaType.name)
}

// if we have already seen the base type, we can just reference it
if (inlineFields.has(schemaType.type!)) {
return {type: 'inline', name: schemaType.type!.name} satisfies InlineTypeNode
Expand Down Expand Up @@ -192,6 +192,14 @@ export function extractSchema(
return createObject(schemaType)
}

if (lastType(schemaType)?.name === 'document') {
const doc = documentTypes.get(schemaType.name)
if (doc === undefined) {
return {type: 'unknown'} satisfies UnknownTypeNode
}
return {type: 'object', attributes: doc?.attributes} satisfies ObjectTypeNode
}

throw new Error(`Type "${schemaType.name}" not found`)
}

Expand Down
Loading

0 comments on commit d35f9ad

Please sign in to comment.