@@ -71,7 +71,7 @@ export class Key {
7171 parseableField = Key . getKeyDirectiveFields ( parseableField ) ;
7272 }
7373 (
74- Key . parseKeyFields ( parseableField )
74+ Key . parseKeyFields ( this . typename , parseableField )
7575 . definitions [ 0 ] as OperationDefinitionNode
7676 ) ?. selectionSet ?. selections ?. forEach ( ( selection ) =>
7777 this . addSelection ( selection )
@@ -174,6 +174,7 @@ export class Key {
174174 */
175175 public toString ( ) : string {
176176 return Key . getSortedSelectionSetFields (
177+ this . typename ,
177178 this . _fields . map ( ( field ) => field . toString ( ) ) . join ( ' ' )
178179 ) ;
179180 }
@@ -210,10 +211,22 @@ export class Key {
210211 * Parses a key fields string into AST.
211212 *
212213 * @param {string } keyFields - The key fields string
214+ * @param {string } typename - The typename of the node the directive belongs to
213215 * @returns {DocumentNode } The key fields represented in AST
214216 */
215- private static parseKeyFields ( keyFields : string ) : DocumentNode {
216- return parse ( `{${ keyFields } }` , { noLocation : true } ) ;
217+ private static parseKeyFields (
218+ typename : string ,
219+ keyFields : string
220+ ) : DocumentNode {
221+ try {
222+ return parse ( `{${ keyFields } }` , { noLocation : true } ) ;
223+ } catch ( error ) {
224+ throw new Error (
225+ `Failed to parse key fields "${ keyFields } " for type "${ typename } " due to error: ${
226+ ( error as Error ) . message
227+ } `
228+ ) ;
229+ }
217230 }
218231
219232 /**
@@ -234,12 +247,18 @@ export class Key {
234247 * Sorts the selection set fields.
235248 *
236249 * @param {string } fields - The selection set fields.
250+ * @param {string } typename - The typename of the node the directive belongs to
237251 * @returns {string } The sorted selection set fields.
238252 */
239- public static getSortedSelectionSetFields ( fields : string ) : string {
253+ public static getSortedSelectionSetFields (
254+ typename : string ,
255+ fields : string
256+ ) : string {
240257 const selections = Key . sortSelectionSetByNameAscending (
241- ( Key . parseKeyFields ( fields ) . definitions [ 0 ] as OperationDefinitionNode )
242- . selectionSet
258+ (
259+ Key . parseKeyFields ( typename , fields )
260+ . definitions [ 0 ] as OperationDefinitionNode
261+ ) . selectionSet
243262 ) ;
244263 return Key . formatSelectionSetFields ( print ( selections ) ) ;
245264 }
0 commit comments