# Server-Side Row Model - Exporting

Canonical page: https://www.adaptabletools.com/docs/dev-guide-row-models-server-exporting

- Exporting reports works fine when using the Server-Side Row Model
- AdapTable enables developers to create report data on the server and pass to client for export

When running reports, AdapTable typically gathers the data required to run a Report, and then exports it to the specified destination.

But when using the Server-Side Row Model, you will likely want to supply the data to be exported.

- AdapTable will then still take care of ensuring the data is sent to the appropriate destination
- Some reports - e.g. Selected Data - can be run fully on the client even when using Server-Side Row Model

This is done via the `processExport` property in [Export Options](https://www.adaptabletools.com/docs/technical-reference-exporting/index.md) - which takes the form of a function, which if provided, will be invoked when a Report is run.

The function receives a [`ProcessExportContext`](https://www.adaptabletools.com/docs/reference/processexportcontext.md) object, and returns (in the form of an [`ExportResultData`](https://www.adaptabletools.com/docs/reference/exportresultdata.md) object), the data for the Report which will be exported by AdapTable

See [Processing Reports](https://www.adaptabletools.com/docs/handbook-exporting-processing/index.md) for full information on how to process reports so they can be evaluated on the server

**Example: SSRM - Exporting**

Server-Side Row Model: Running Reports

- In this example we create a [Custom Report](https://www.adaptabletools.com/docs/handbook-exporting/index.md) called `US Golden Athletes` which exports all US Athletes who have won a Gold medal
- We provide an implementation for the `processExport` property in [Export Options](https://www.adaptabletools.com/docs/technical-reference-exporting/index.md) in order to gather the report data on the Server, and return it to AdapTable to be exported as needed

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableColumnBase,
  AdaptableOptions,
  ProcessExportContext,
  Report,
  ExportResultData,
  ReportData,
  SystemReportName,
} from '@adaptabletools/adaptable';

const API_BASE: string = process.env.NEXT_PUBLIC_ATHLETES_API_URL!;

const REPORTS_HANDLED_CLIENT_SIDE: (SystemReportName | string)[] = [
  'Current Layout',
  'Selected Data',
];

interface RequestReportConfig {
  report: Report;
  reportColumns: AdaptableColumnBase[];
  reportQueryAST?: any;
}

export async function handleExport(
  context: ProcessExportContext
): Promise<ExportResultData | boolean> {
  const {report, reportFormat} = context;
  if (REPORTS_HANDLED_CLIENT_SIDE.includes(report.Name)) {
    //  these reports are client-side specific and will be handled by the default behaviour (which is to export the client-side data)
    return true;
  }

  // everything else ('All Data' or any other custom Reports) will be handled server-side

  const reportColumns =
    report.Name === 'All Data'
      ? // sending an empty array will cause the server to use all columns
        []
      : context.getReportColumns().filter(column => {
          // for simplicity's sake, we're only going to filter out the special (synthetic) columns (Calculated, FreeText, Action)
          // otherwise we would have to evaluate them on the server as well
          return !context.adaptableApi.columnApi.isCalculatedColumn(
            column.columnId
          );
        });

  const reportConfig: RequestReportConfig = {
    report,
    reportColumns,
  };

  if (report.Expression) {
    reportConfig.reportQueryAST =
      context.adaptableApi.expressionApi.getASTForExpression(report.Expression);
  }

  const serverSideResponse = await fetch(`${API_BASE}/report`, {
    method: 'post',
    body: JSON.stringify(reportConfig),
    headers: {'Content-Type': 'application/json; charset=utf-8'},
  });
  const serverSideResultData: ExportResultData =
    await serverSideResponse.json();

  if (serverSideResultData.type !== 'json') {
    console.log(
      'In this showcase we always return JSON from the server, so this should never happen'
    );
    return serverSideResultData;
  }

  if (reportFormat === 'CSV') {
    const csvContent = context.convertToCsv(serverSideResultData.data);
    return {
      type: 'csv',
      data: csvContent,
    };
  }
  if (reportFormat === 'Excel' || reportFormat === 'VisualExcel') {
    const excelBLob = context.convertToExcel(serverSideResultData.data);
    return {
      type: 'excel',
      data: excelBLob,
    };
  }

  return serverSideResultData;
}

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'id',
  adaptableId: 'SSRM: Export',
  exportOptions: {
    processExport: handleExport,
    systemReportNames: ['All Data', 'Current Layout'],
    systemReportFormats: ['Excel', 'CSV', 'JSON'],
  },
  initialState: {
    Dashboard: {
      PinnedToolbars: ['Export'],
    },
    Theme: {
      CurrentTheme: 'dark',
    },
    Export: {
      CurrentReport: 'US Golden Athletes',
      CurrentFormat: 'Excel',
      Reports: [
        {
          Name: 'US Golden Athletes',
          ReportColumnScope: 'ScopeColumns',
          Scope: {
            ColumnIds: ['athlete', 'gold', 'sport', 'year', 'country'],
          },
          ReportRowScope: 'ExpressionRows',
          Expression: '[country]="United States" AND [gold]>0',
        },
      ],
    },
    Layout: {
      CurrentLayout: 'SSRM Layout',
      Layouts: [
        {
          Name: 'SSRM Layout',
          TableColumns: [
            'athlete',
            'gold',
            'silver',
            'bronze',
            'country',
            'sport',
            'year',
          ],
          ColumnSizing: {
            athlete: {Width: 175},
            bronze: {Width: 100},
            country: {Width: 125},
            gold: {Width: 100},
            silver: {Width: 100},
            sport: {Width: 175},
            year: {Width: 115},
          },
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo, AdaptableApi} from '@adaptabletools/adaptable';
import {
  ColDef,
  GridApi,
  IServerSideDatasource,
  IServerSideGetRowsParams,
  IServerSideGetRowsRequest,
} from 'ag-grid-enterprise';

export const onAdaptableReady = ({
  adaptableApi,
  agGridApi,
}: AdaptableReadyInfo) => {
  agGridApi.setGridOption(
    'serverSideDatasource',
    createDataSource(adaptableApi)
  );
};

const API_BASE: string = process.env.NEXT_PUBLIC_ATHLETES_API_URL!;

// v24 Column Filters are Expressions. The athletes mock server evaluates
// both Grid Filter and Column Filters from `gridFilterAST`.
function rewriteAutoGroupColumn(
  node: unknown,
  groupedColumnId?: string
): unknown {
  if (!groupedColumnId || node == null || typeof node !== 'object') {
    return node;
  }
  if (Array.isArray(node)) {
    return node.map(item => rewriteAutoGroupColumn(item, groupedColumnId));
  }
  const astNode = node as {type?: string; args?: unknown[]};
  if (astNode.type === 'COL' && astNode.args?.[0] === 'ag-Grid-AutoColumn') {
    return {
      ...astNode,
      args: [groupedColumnId, ...astNode.args.slice(1)],
    };
  }
  if (!astNode.args) {
    return node;
  }
  return {
    ...astNode,
    args: astNode.args.map(arg =>
      rewriteAutoGroupColumn(arg, groupedColumnId)
    ),
  };
}

function appendExpressionAst(
  astNodes: unknown[],
  ast: unknown,
  groupedColumnId?: string
) {
  if (ast == null) {
    return;
  }
  const nodes = Array.isArray(ast) ? ast : [ast];
  for (const node of nodes) {
    astNodes.push(rewriteAutoGroupColumn(node, groupedColumnId));
  }
}

function toServerFilterFields(
  adaptableApi: AdaptableApi,
  groupedColumnId?: string
) {
  const filterState = adaptableApi.stateApi.getAdaptableFilterState();
  const astNodes: unknown[] = [];
  appendExpressionAst(astNodes, filterState.gridFilterAST, groupedColumnId);
  for (const columnFilter of filterState.columnFilters ?? []) {
    if (!columnFilter.Expression) {
      continue;
    }
    appendExpressionAst(
      astNodes,
      adaptableApi.expressionApi.getASTForExpression(columnFilter.Expression),
      groupedColumnId
    );
  }
  return {
    adaptableFilters: [],
    gridFilterAST: astNodes.length ? astNodes : undefined,
  };
}

function createDataSource(adaptableApi: AdaptableApi): IServerSideDatasource {
  return {
    getRows(params: IServerSideGetRowsParams) {
      const getRowsRequest: IServerSideGetRowsRequest = params.request;
      const adaptableSortState = adaptableApi.stateApi.getAdaptableSortState();
      const groupedColumn = getRowsRequest.rowGroupCols?.[0];
      const serverFilters = toServerFilterFields(
        adaptableApi,
        groupedColumn?.field ?? groupedColumn?.id
      );

      const sortModel = getRowsRequest.sortModel.map(sort => {
        const customSort = adaptableSortState.customSorts.find(
          customSort => customSort.ColumnId === sort.colId
        );
        if (customSort) {
          return {
            ...sort,
            sortedValues: customSort.SortedValues,
          };
        }
        return sort;
      });

      const request = {
        ...getRowsRequest,
        sortModel,
        ...serverFilters,
        includeSQL: true,
      };
      console.log('request to server', request);

      fetch(API_BASE, {
        method: 'post',
        body: JSON.stringify(request),
        headers: {'Content-Type': 'application/json; charset=utf-8'},
      })
        .then(httpResponse => httpResponse.json())
        .then(response => {
          params.success({
            rowData: response.rows,
            rowCount: response.lastRow ?? 0,
          });

          if (response.pivotFields?.length) {
            addPivotColumnDefs(response, params.api);
          } else {
            if (!adaptableApi.layoutApi.isCurrentLayoutPivot()) {
              if (params.api.getPivotResultColumns() != null) {
                params.api.setPivotResultColumns(null);
              }
            }
          }

          adaptableApi.systemStatusApi.setInfoSystemStatus(
            `SQL: ${response.sql.slice(0, 40)}`,
            response.sql
          );
        })
        .catch(error => {
          params.fail();
        });
    },
  };
}

function addPivotColumnDefs(response: any, agGridApi: GridApi) {
  const existingPivotColDefs = agGridApi.getPivotResultColumns();
  if (existingPivotColDefs && existingPivotColDefs.length > 0) {
    return;
  }

  const pivotColDefs: ColDef[] = response.pivotFields.map(function (
    field: any,
    index: number
  ) {
    const [_key, value] = Object.entries(field)[0];
    const valueStr = `${value}`;
    return {
      headerName: valueStr,
      field: valueStr,
      filter: false,
      colId: `${Date.now()}_${index}`,
      cellDataType: 'number',
    };
  });

  agGridApi.setPivotResultColumns(pivotColDefs);
}
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    sortable: true,
    filter: true,
    floatingFilter: true,
    enableRowGroup: true,
  },
  rowModelType: 'serverSide',
  columnDefs: columnDefs,
  sideBar: ['adaptable', 'columns', 'filters'],
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {field: 'id', hide: true, cellDataType: 'text'},
  {
    field: 'athlete',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'country',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'sport',
    cellDataType: 'text',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'year',
    cellDataType: 'number',
    enableRowGroup: true,
    resizable: true,
  },
  {
    field: 'gold',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
  {
    field: 'silver',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
  {
    field: 'bronze',
    aggFunc: 'sum',
    cellDataType: 'number',
    enableValue: true,
    resizable: true,
  },
];
```
