@@ -15,6 +15,8 @@ import {
1515 GetFieldNodeResultName ,
1616 IsAny ,
1717 IsRelationNullable ,
18+ IsStringUnion ,
19+ JsonPathToType ,
1820 ResolveRelationship ,
1921 SelectQueryError ,
2022} from './utils'
@@ -239,6 +241,30 @@ type ProcessFieldNode<
239241 ? ProcessEmbeddedResource < Schema , Relationships , Field , RelationName >
240242 : ProcessSimpleField < Row , RelationName , Field >
241243
244+ type ResolveJsonPathType <
245+ Value ,
246+ Path extends string | undefined ,
247+ CastType extends PostgreSQLTypes
248+ > = Path extends string
249+ ? JsonPathToType < Value , Path > extends never
250+ ? // Always fallback if JsonPathToType returns never
251+ TypeScriptTypes < CastType >
252+ : JsonPathToType < Value , Path > extends infer PathResult
253+ ? PathResult extends string
254+ ? // Use the result if it's a string as we know that even with the string accessor ->> it's a valid type
255+ PathResult
256+ : IsStringUnion < PathResult > extends true
257+ ? // Use the result if it's a union of strings
258+ PathResult
259+ : CastType extends 'json'
260+ ? // If the type is not a string, ensure it was accessed with json accessor ->
261+ PathResult
262+ : // Otherwise it means non-string value accessed with string accessor ->> use the TypeScriptTypes result
263+ TypeScriptTypes < CastType >
264+ : TypeScriptTypes < CastType >
265+ : // No json path, use regular type casting
266+ TypeScriptTypes < CastType >
267+
242268/**
243269 * Processes a simple field (without embedded resources).
244270 *
@@ -261,8 +287,8 @@ type ProcessSimpleField<
261287 }
262288 : {
263289 // Aliases override the property name in the result
264- [ K in GetFieldNodeResultName < Field > ] : Field [ 'castType' ] extends PostgreSQLTypes // We apply the detected casted as the result type
265- ? TypeScriptTypes < Field [ 'castType' ] >
290+ [ K in GetFieldNodeResultName < Field > ] : Field [ 'castType' ] extends PostgreSQLTypes
291+ ? ResolveJsonPathType < Row [ Field [ 'name' ] ] , Field [ 'jsonPath' ] , Field [ 'castType' ] >
266292 : Row [ Field [ 'name' ] ]
267293 }
268294 : SelectQueryError < `column '${Field [ 'name' ] } ' does not exist on '${RelationName } '.`>
0 commit comments