-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy pathcsv.ts
More file actions
65 lines (60 loc) · 1.73 KB
/
Copy pathcsv.ts
File metadata and controls
65 lines (60 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { createResponse } from '../utils'
import { DataSource } from '../types'
import { StarbaseDBConfiguration } from '../handler'
import {
createStreamingExportResponse,
formatCsvValue,
getTableExportPlan,
iterateTableRows,
tableExists,
TableExportPlan,
} from './streaming'
async function* csvTableChunks(
tableName: string,
columns: string[],
dataSource: DataSource,
config: StarbaseDBConfiguration,
exportPlan: TableExportPlan
): AsyncGenerator<string> {
if (columns.length) {
yield `${columns.map(formatCsvValue).join(',')}\n`
}
for await (const row of iterateTableRows(
tableName,
dataSource,
config,
undefined,
exportPlan
)) {
yield `${columns.map((column) => formatCsvValue(row[column])).join(',')}\n`
}
}
export async function exportTableToCsvRoute(
tableName: string,
dataSource: DataSource,
config: StarbaseDBConfiguration
): Promise<Response> {
try {
if (!(await tableExists(tableName, dataSource, config))) {
return createResponse(
undefined,
`Table '${tableName}' does not exist.`,
404
)
}
const exportPlan = await getTableExportPlan(
tableName,
dataSource,
config
)
const columns = exportPlan.columns
return createStreamingExportResponse(
csvTableChunks(tableName, columns, dataSource, config, exportPlan),
`${tableName}_export.csv`,
'text/csv'
)
} catch (error: any) {
console.error('CSV Export Error:', error)
return createResponse(undefined, 'Failed to export table to CSV', 500)
}
}