π₯ π₯ π₯ A Free & Self-hostable Airtable Alternative
TypeScript airtableairtable-alternativeautomatic-apihacktoberfestlow-codeno-codeno-code-databaseno-code-platformpostgresqlrest-apirestful-apispreadsheetsqliteswagger
feat: Add JSON download option for data export
claude[bot]ab747294f374
diff --git a/packages/nc-gui/components/smartsheet/toolbar/ExportSubActions.vue b/packages/nc-gui/components/smartsheet/toolbar/ExportSubActions.vueindex d5c209c21c..27220284d6 100644--- a/packages/nc-gui/components/smartsheet/toolbar/ExportSubActions.vue+++ b/packages/nc-gui/components/smartsheet/toolbar/ExportSubActions.vue@@ -109,7 +109,7 @@ const exportFile = async (exportType: ExportTypes) => {)}- message.info('Preparing CSV for download...')+ message.info(`Preparing ${exportType.toUpperCase()} for download...`)$poller.subscribe({ id: jobData.id },@@ -160,4 +160,13 @@ const exportFile = async (exportType: ExportTypes) => {CSV</div></NcMenuItem>++ <NcMenuItem v-e="['a:download:json']" @click.stop="exportFile(ExportTypes.JSON)">+ <div class="flex flex-row items-center nc-base-menu-item !py-0 children:flex-none">+ <GeneralLoader v-if="isExporting" size="regular" />+ <component :is="iconMap.ncFileTypeJson" v-else class="w-4" />+ <!-- Download as JSON -->+ JSON+ </div>+ </NcMenuItem></template>diff --git a/packages/nocodb-sdk/src/lib/globals.ts b/packages/nocodb-sdk/src/lib/globals.tsindex a2709d0f6e..9343d91c8a 100644--- a/packages/nocodb-sdk/src/lib/globals.ts+++ b/packages/nocodb-sdk/src/lib/globals.ts@@ -91,6 +91,7 @@ export type ExpandedFormModeType =export enum ExportTypes {EXCEL = 'excel',CSV = 'csv',+ JSON = 'json',}export enum PluginCategory {diff --git a/packages/nocodb/src/modules/jobs/jobs/data-export/data-export.processor.ts b/packages/nocodb/src/modules/jobs/jobs/data-export/data-export.processor.tsindex 95f7b18f36..bea01a6d69 100644--- a/packages/nocodb/src/modules/jobs/jobs/data-export/data-export.processor.ts+++ b/packages/nocodb/src/modules/jobs/jobs/data-export/data-export.processor.ts@@ -37,7 +37,7 @@ export class DataExportProcessor {ncSiteUrl,} = job.data;- if (exportAs !== 'csv') NcError.notImplemented(`Export as ${exportAs}`);+ if (exportAs !== 'csv' && exportAs !== 'json') NcError.notImplemented(`Export as ${exportAs}`);const hrTime = initTime();@@ -62,7 +62,8 @@ export class DataExportProcessor {view,)}) ${date}`;- const destPath = `nc/uploads/data-export/${dateFolder}/${modelId}/${filename}.csv`;+ const fileExtension = exportAs === 'json' ? 'json' : 'csv';+ const destPath = `nc/uploads/data-export/${dateFolder}/${modelId}/${filename}.${fileExtension}`;let url = null;@@ -99,44 +100,66 @@ export class DataExportProcessor {error = e;});- this.exportService- .streamModelDataAsCsv(context, {- dataStream,- linkStream: null,- baseId: model.base_id,- modelId: model.id,- viewId: view.id,- ncSiteUrl: ncSiteUrl,- delimiter: options?.delimiter,- includeCrossBaseColumns: true,- filterArrJson: options.filterArrJson,- sortArrJson: options.sortArrJson,- })- .catch((e) => {- this.logger.debug(e);- dataStream.push(null);- error = e;- });+ if (exportAs === 'json') {+ this.exportService+ .streamModelDataAsJson(context, {+ dataStream,+ baseId: model.base_id,+ modelId: model.id,+ viewId: view.id,+ ncSiteUrl: ncSiteUrl,+ includeCrossBaseColumns: true,+ filterArrJson: options.filterArrJson,+ sortArrJson: options.sortArrJson,+ })+ .catch((e) => {+ this.logger.debug(e);+ dataStream.push(null);+ error = e;+ });+ } else {+ this.exportService+ .streamModelDataAsCsv(context, {+ dataStream,+ linkStream: null,+ baseId: model.base_id,+ modelId: model.id,+ viewId: view.id,+ ncSiteUrl: ncSiteUrl,+ delimiter: options?.delimiter,+ includeCrossBaseColumns: true,+ filterArrJson: options.filterArrJson,+ sortArrJson: options.sortArrJson,+ })+ .catch((e) => {+ this.logger.debug(e);+ dataStream.push(null);+ error = e;+ });+ }url = await uploadFilePromise;// if url is not defined, it is local attachment+ const mimetype = exportAs === 'json' ? 'application/json' : 'text/csv';+ const filenameWithExt = `${filename}.${fileExtension}`;+if (!url) {url = await PresignedUrl.getSignedUrl({pathOrUrl: path.join(destPath.replace('nc/uploads/', '')),- filename: `${filename}.csv`,+ filename: filenameWithExt,expireSeconds: 3 * 60 * 60, // 3 hourspreview: false,- mimetype: 'text/csv',+ mimetype,encoding: options?.encoding || 'utf-8',});} else {url = await PresignedUrl.getSignedUrl({pathOrUrl: url,- filename: `${filename}.csv`,+ filename: filenameWithExt,expireSeconds: 3 * 60 * 60, // 3 hourspreview: false,- mimetype: 'text/csv',+ mimetype,encoding: options?.encoding || 'utf-8',});}diff --git a/packages/nocodb/src/modules/jobs/jobs/export-import/export.service.ts b/packages/nocodb/src/modules/jobs/jobs/export-import/export.service.tsindex a56c7b16e2..d0d307c3a1 100644--- a/packages/nocodb/src/modules/jobs/jobs/export-import/export.service.ts+++ b/packages/nocodb/src/modules/jobs/jobs/export-import/export.service.ts@@ -1132,6 +1132,235 @@ export class ExportService {}}+ async streamModelDataAsJson(+ context: NcContext,+ param: {+ dataStream: Readable;+ baseId: string;+ modelId: string;+ viewId?: string;+ handledMmList?: string[];+ _fieldIds?: string[];+ ncSiteUrl?: string;+ excludeUsers?: boolean;+ includeCrossBaseColumns?: boolean;+ filterArrJson?: any;+ sortArrJson?: any;+ },+ ) {+ context = { ...context, cache: true };++ const { dataStream, handledMmList } = param;++ const { model, view } = await getViewAndModelByAliasOrId(context, {+ baseName: param.baseId,+ tableName: param.modelId,+ viewName: param.viewId,+ });++ const source = await Source.get(context, model.source_id);++ await model.getColumns(context);++ if (!param.includeCrossBaseColumns) {+ model.columns = this.filterOutCrossBaseColumns(model);+ } else {+ model.columns = [...model.columns];+ }++ let fields = param._fieldIds+ ? model.columns+ .filter((c) => param._fieldIds?.includes(c.id))+ .map((c) => c.title)+ : model.columns+ .filter((c) => !isLinksOrLTAR(c) && !isVirtualCol(c))+ .map((c) => c.title);++ const refView =+ view ?? (await View.getFirstCollaborativeView(context, model.id));++ const viewCols = await refView.getColumns(context);++ const hideSystemFields = view.show_system_fields+ ? // at minimum filter mm fields used in Links field+ model.columns+ .filter(+ (c) =>+ isSystemColumn(c) &&+ c.uidt === UITypes.LinkToAnotherRecord &&+ c.colOptions?.fk_related_model_id !== model.id,+ )+ .map((c) => c.id)+ : model.columns.filter((c) => isSystemColumn(c)).map((c) => c.id);++ fields = viewCols+ .sort((a, b) => a.order - b.order)+ .filter((c) => c.show && !hideSystemFields.includes(c.fk_column_id))+ .map((vc) => model.columns.find((c) => c.id === vc.fk_column_id)?.title)+ // to filter out undefined values(cross base link)+ .filter(Boolean);++ dataStream.setEncoding('utf8');++ const formatAndSerializeForJson = async (data: any) => {+ const includedColumns: {+ col: Column;+ viewOrder: number;+ }[] = [];+ for (const row of data) {+ for (const [k, v] of Object.entries(row)) {+ const col = model.columns.find((c) => c.title === k);+ if (col) {+ row[k] = await serializeCellValue(context, {+ value: v,+ column: col,+ siteUrl: param.ncSiteUrl,+ });+ includedColumns.push({+ col,+ viewOrder:+ viewCols.find((vCol) => vCol.fk_column_id === col.id)?.order ??+ includedColumns.length + 1,+ });+ }+ }+ }+ const orderedColumns = includedColumns.sort(+ (a, b) => a.viewOrder - b.viewOrder,+ );+ return {+ data: data.map((row) => {+ return orderedColumns.reduce((acc, cur) => {+ acc[cur.col.title] = row[cur.col.title];+ return acc;+ }, {});+ }),+ };+ };++ const baseModel = await Model.getBaseModelSQL(context, {+ id: model.id,+ viewId: view?.id,+ dbDriver: await NcConnectionMgrv2.get(source),+ });++ const limit = 200;+ const offset = 0;++ try {+ await this.recursiveReadForJson(+ context,+ formatAndSerializeForJson,+ baseModel,+ dataStream,+ model,+ view,+ offset,+ limit,+ fields,+ true,+ {+ filterArrJson: param.filterArrJson,+ sortArrJson: param.sortArrJson,+ },+ );+ } catch (e) {+ this.debugLog(e);+ throw e;+ }+ }++ async recursiveReadForJson(+ context: NcContext,+ formatter: (data: any) => Promise<{ data: any }>,+ baseModel: BaseModelSqlv2,+ stream: Readable,+ model: Model,+ view: View,+ offset: number,+ limit: number,+ fields: string[],+ isFirst = false,+ param?: {+ filterArrJson: any;+ sortArrJson: any;+ },+ ): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ this.datasService+ .dataList(context, {+ model,+ view,+ query: {+ limit,+ offset,+ fields,+ filterArrJson: param?.filterArrJson,+ sortArrJson: param?.sortArrJson,+ },+ baseModel,+ ignoreViewFilterAndSort: false,+ limitOverride: limit,+ skipSortBasedOnOrderCol: true,+ })+ .then(async (result) => {+ try {+ if (result.list.length === 0 && offset === 0) {+ // Empty result, just return empty array+ stream.push('[]');+ stream.push(null);+ resolve();+ return;+ }++ const { data } = await formatter(result.list);++ if (isFirst) {+ // Start JSON array+ stream.push('[\n');+ }++ if (data.length > 0) {+ // Add comma if not the first batch+ if (offset > 0) {+ stream.push(',\n');+ }++ // Write JSON objects+ const jsonRows = data.map(row => JSON.stringify(row)).join(',\n');+ stream.push(jsonRows);+ }++ if (result.pageInfo.isLastPage) {+ // Close JSON array+ stream.push('\n]');+ stream.push(null);+ resolve();+ } else {+ this.recursiveReadForJson(+ context,+ formatter,+ baseModel,+ stream,+ model,+ view,+ offset + limit,+ limit,+ fields,+ false,+ param,+ )+ .then(resolve)+ .catch(reject);+ }+ } catch (e) {+ reject(e);+ }+ })+ .catch(reject);+ });+ }+private filterOutCrossBaseColumns(model: Model) {const crossbaseLinkIds = new Set(model.columns.filter((c) => isCrossBaseLink(c)).map((c) => c.id),