Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion packages/core/src/storages/dataset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,11 @@ export interface DatasetIteratorOptions
export interface DatasetExportToOptions extends DatasetExportOptions {
fromDataset?: string;
toKVS?: string;
/**
* If true, includes all unique keys from all dataset items in the CSV export.
* If omitted or false, only keys from the first item are used.
*/
collectAllKeys?: boolean;
}

/**
Expand Down Expand Up @@ -349,7 +354,16 @@ export class Dataset<Data extends Dictionary = Dictionary> {
const items = await this.export(options);

if (contentType === 'text/csv') {
const keys = Object.keys(items[0]);
// To handle empty dataset exports gracefully.
if (items.length === 0) {
await kvStore.setValue(key, '', { contentType });
return items;
}

const keys = options?.collectAllKeys
? Array.from(new Set(items.flatMap(Object.keys)))
: Object.keys(items[0]);

const value = stringify([
keys,
...items.map((item) => {
Expand Down
22 changes: 22 additions & 0 deletions test/core/storages/dataset.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,28 @@ describe('dataset', () => {
const kvData = await KeyValueStore.getValue('TEST-123-123-csv');
expect(kvData).toEqual('hello,foo\nworld 1,bar 1\nworld 2,bar 2\nworld 3,bar 3\n');
});
it('should export all fields when collectAllKeys is true', async () => {
const dataset = await Dataset.open();
await dataset.pushData([
{ id: 1, name: 'Alice' },
{ id: 2, age: 30 },
]);

const kvStore = await KeyValueStore.open();
await dataset.exportTo(
'test.csv',
{
toKVS: kvStore.name,
collectAllKeys: true,
},
'text/csv',
);

const exported = await kvStore.getValue('test.csv');
expect(exported).toContain('id');
expect(exported).toContain('name');
expect(exported).toContain('age');
});
});
});
});
Loading