Skip to content

Instantly share code, notes, and snippets.

@mrclay
Last active February 20, 2026 14:08
Show Gist options
  • Select an option

  • Save mrclay/4df196172405f0619c5ef72e18691c95 to your computer and use it in GitHub Desktop.

Select an option

Save mrclay/4df196172405f0619c5ef72e18691c95 to your computer and use it in GitHub Desktop.
[UNTESTED!] For a Drupal GraphQL text field, get a wrapped string with its type (plain or html)
/**
* Determine the type of text from GraphQL.
*
* In the query, make sure to request all 3 subfields:
* my_field {
* processed
* format
* value
* }
*/
function typedField(field: unknown): { type: 'plain' | 'html'; value: string } {
if (
field &&
typeof field === 'object' &&
'format' in field &&
typeof field.format === 'string'
) {
if (
field.format.endsWith('_html') &&
'processed' in field &&
typeof field.processed === 'string'
) {
return { type: 'html', value: field.processed };
}
if ('value' in field) {
return { type: 'plain', value: String(field.value) };
}
}
// string, number, null, undefined, or something unrecognized
return {
type: 'plain',
value: field === null || typeof field === 'undefined' ? '' : String(field),
};
}
export default typedField;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment