Last active
February 20, 2026 14:08
-
-
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)
This file contains hidden or 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
| /** | |
| * 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