70 lines
2.4 KiB
TypeScript
70 lines
2.4 KiB
TypeScript
import { Observable, map } from 'rxjs';
|
|
import { FileKind, FileOptions, PreviewResponse, SourceLocator } from '../api/api.types';
|
|
import { fileToBase64 } from '../api/file-encoding';
|
|
import { SourceGateway } from '../api/source-gateway';
|
|
import { DataConnection, EncodedFile, SourceTable } from './data-source';
|
|
|
|
const FILE_PRESENTATION: Record<FileKind, { icon: string; typeLabel: string }> = {
|
|
csv: { icon: 'table_view', typeLabel: 'Texto / CSV' },
|
|
excel: { icon: 'grid_on', typeLabel: 'Libro de Excel' },
|
|
json: { icon: 'data_object', typeLabel: 'JSON' },
|
|
};
|
|
|
|
/** A CSV, Excel or JSON file. Excel exposes one table per sheet; CSV/JSON exactly one. */
|
|
export class FileConnection extends DataConnection {
|
|
readonly icon: string;
|
|
readonly typeLabel: string;
|
|
readonly encoded: EncodedFile;
|
|
|
|
constructor(
|
|
readonly file: File,
|
|
readonly fileKind: FileKind,
|
|
) {
|
|
super(file.name);
|
|
this.icon = FILE_PRESENTATION[fileKind].icon;
|
|
this.typeLabel = FILE_PRESENTATION[fileKind].typeLabel;
|
|
this.encoded = new EncodedFile(file, fileToBase64);
|
|
}
|
|
|
|
override get singleTable(): boolean {
|
|
return this.fileKind !== 'excel';
|
|
}
|
|
|
|
protected discover(gateway: SourceGateway): Observable<SourceTable[]> {
|
|
// A target-less preview proves the file parses and lists its sub-tables (Excel sheets).
|
|
return gateway.file.preview(this.file, this.fileKind, null).pipe(
|
|
map((preview) => {
|
|
const tables = preview.tables ?? [];
|
|
if (!tables.length) return [new FileTable(this, this.file.name, {})];
|
|
return tables.map((table) => new FileTable(this, table.name, table.options as FileOptions));
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
export class FileTable extends SourceTable {
|
|
readonly icon: string;
|
|
readonly kindLabel: string;
|
|
|
|
constructor(
|
|
override readonly connection: FileConnection,
|
|
name: string,
|
|
readonly options: FileOptions,
|
|
) {
|
|
super(connection, name);
|
|
this.icon = connection.fileKind === 'excel' ? 'tab' : connection.icon;
|
|
this.kindLabel = connection.fileKind === 'excel' ? 'Hoja' : 'Archivo';
|
|
}
|
|
|
|
preview(gateway: SourceGateway, target: string | null): Observable<PreviewResponse> {
|
|
return gateway.file.preview(this.connection.file, this.connection.fileKind, target, this.options);
|
|
}
|
|
|
|
async locator(): Promise<SourceLocator> {
|
|
return {
|
|
source_type: this.connection.fileKind,
|
|
payload: { file_base64: await this.connection.encoded.base64(), options: this.options },
|
|
};
|
|
}
|
|
}
|