Skip to content

Commit 54b12ad

Browse files
committed
Support raw queries in afterQuery
1 parent 72837fe commit 54b12ad

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

src/operation.ts

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,43 @@ async function beforeQuery(sql: string, params?: any[], dataSource?: DataSource,
4343
}
4444

4545
async function afterQuery(sql: string, result: any, isRaw: boolean, dataSource?: DataSource, env?: Env): Promise<any> {
46+
result = isRaw ? transformRawResults(result, 'from') : result;
47+
4648
// ## DO NOT REMOVE: POST QUERY HOOK ##
4749

48-
return result;
50+
return isRaw ? transformRawResults(result, 'to') : result;
51+
}
52+
53+
function transformRawResults(result: any, direction: 'to' | 'from'): Record<string, any> {
54+
if (direction === 'from') {
55+
// Convert our result from the `raw` output to a traditional object
56+
result = {
57+
...result,
58+
rows: result.rows.map((row: any) =>
59+
result.columns.reduce((obj: any, column: string, index: number) => {
60+
obj[column] = row[index];
61+
return obj;
62+
}, {})
63+
)
64+
};
65+
66+
return result.rows
67+
} else if (direction === 'to') {
68+
// Convert our traditional object to the `raw` output format
69+
const columns = Object.keys(result[0] || {});
70+
const rows = result.map((row: any) => columns.map(col => row[col]));
71+
72+
return {
73+
columns,
74+
rows,
75+
meta: {
76+
rows_read: rows.length,
77+
rows_written: 0
78+
}
79+
};
80+
}
81+
82+
return result
4983
}
5084

5185
// Outerbase API supports more data sources than can be supported via Cloudflare Workers. For those data

0 commit comments

Comments
 (0)