Created
June 3, 2024 16:20
-
-
Save virtuallyunknown/0bc83ca660a39a0307c3e4156f5e5ef5 to your computer and use it in GitHub Desktop.
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
import type { KyselyPlugin, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, RootOperationNode, UnknownRow } from 'kysely'; | |
function toJsonb(func: unknown) { | |
if (typeof func !== 'string') { | |
throw new Error('Invalid function'); | |
} | |
switch (func) { | |
case 'json_agg': return 'jsonb_agg'; | |
case 'to_json': return 'to_jsonb'; | |
default: return func; | |
} | |
} | |
function transformFuncKey(obj: unknown): unknown { | |
if (typeof obj !== 'object' || obj === null) { | |
return obj; | |
} | |
if (Array.isArray(obj)) { | |
return obj.map(transformFuncKey); | |
} | |
return Object.fromEntries( | |
Object.entries(obj as Record<string, unknown>).map(([key, value]) => { | |
if (key === 'func' && typeof value === 'string') { | |
// eslint-disable-next-line no-param-reassign | |
value = toJsonb(value); | |
} | |
else { | |
// eslint-disable-next-line no-param-reassign | |
value = transformFuncKey(value); | |
} | |
return [key, value]; | |
}) | |
); | |
} | |
export class JSONBPlugin implements KyselyPlugin { | |
public transformQuery(args: PluginTransformQueryArgs): RootOperationNode { | |
if (args.node.kind !== 'SelectQueryNode') { | |
return args.node; | |
} | |
const res = transformFuncKey(args.node) as RootOperationNode; | |
console.log(JSON.stringify(res, null, 4)); | |
return transformFuncKey(args.node) as RootOperationNode; | |
} | |
// eslint-disable-next-line @typescript-eslint/require-await | |
public async transformResult(args: PluginTransformResultArgs): Promise<QueryResult<UnknownRow>> { | |
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | |
if (args.result.rows && Array.isArray(args.result.rows)) { | |
return { | |
...args.result, | |
rows: args.result.rows, | |
}; | |
} | |
return args.result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment