# Load rows from GraphQL

> Back the server-side row model with a GraphQL query, passing sort, filters and the requested block as variables and cancelling stale queries.

The server-side row model only needs an object with a `getRows(request)` method that returns a promise, so a GraphQL API fits as well as REST. This recipe sends each block request as one query with variables.

> **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> Requires `ServerSideRowModelModule` from `@birchui/grid-pro`.

## 1. The schema

The recipe assumes a query like this on the server:

```graphql title="schema.graphql"
enum SortDirection { ASC DESC }

input OrderSort { field: String!, direction: SortDirection! }
input OrderFilter { field: String!, op: String!, value: String, values: [String!] }

type OrderPage { nodes: [Order!]!, totalCount: Int! }

type Query {
  orders(offset: Int!, limit: Int!, sort: [OrderSort!], filters: [OrderFilter!], search: String): OrderPage!
}
```

## 2. Build the variables

```ts title="orders-graphql.ts"
import type { FilterModel, ServerSideDatasource, ServerSideRequest } from '@birchui/core';
import type { Order } from './orders';

const ORDERS_QUERY = `
  query Orders($offset: Int!, $limit: Int!, $sort: [OrderSort!], $filters: [OrderFilter!], $search: String) {
    orders(offset: $offset, limit: $limit, sort: $sort, filters: $filters, search: $search) {
      totalCount
      nodes { id customer region status total placedAt }
    }
  }
`;

interface OrderFilter {
  field: string;
  op: string;
  value?: string;
  values?: string[];
}

function toFilter(field: string, model: FilterModel): OrderFilter | null {
  switch (model.type) {
    case 'text':
    case 'number':
      return model.value === undefined ? { field, op: model.op } : { field, op: model.op, value: String(model.value) };
    case 'date':
      return { field, op: model.op, value: model.value === undefined ? undefined : String(model.value) };
    case 'set':
      return { field, op: 'in', values: model.values.map(String) };
    case 'boolean':
      return { field, op: 'eq', value: String(model.value) };
    default:
      return null;
  }
}

function toVariables(request: ServerSideRequest) {
  return {
    offset: request.startRow,
    limit: request.endRow - request.startRow,
    sort: request.sort.map(({ colId, dir }) => ({ field: colId, direction: dir === 'desc' ? 'DESC' : 'ASC' })),
    filters: Object.entries(request.filterModel)
      .map(([field, model]) => toFilter(field, model))
      .filter((filter): filter is OrderFilter => filter !== null),
    search: request.quickFilter || null,
  };
}

interface OrdersResponse {
  data?: { orders: { nodes: Order[]; totalCount: number } };
  errors?: { message: string }[];
}

export const ordersDatasource: ServerSideDatasource<Order> = {
  async getRows(request) {
    const response = await fetch('/graphql', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query: ORDERS_QUERY, variables: toVariables(request) }),
      signal: request.signal,
    });
    const body = (await response.json()) as OrdersResponse;
    if (!response.ok || body.errors?.length || !body.data) {
      throw new Error(body.errors?.map((error) => error.message).join('; ') ?? `GraphQL request failed: ${response.status}`);
    }
    return { rows: body.data.orders.nodes, rowCount: body.data.orders.totalCount };
  },
};
```

GraphQL servers often answer errors with status 200, so check `errors` as well as `response.ok`. Throwing makes the grid show the block as failed and notify `onServerSideError` listeners.

## 3. Create the grid

```ts title="orders-grid.ts"
import { createGrid } from '@birchui/core';
import { ServerSideRowModelModule } from '@birchui/grid-pro';
import { ordersDatasource } from './orders-graphql';

createGrid(document.querySelector<HTMLElement>('#orders')!, {
  modules: [ServerSideRowModelModule],
  rowModel: 'server',
  serverSide: { datasource: ordersDatasource, blockSize: 200, debounceMs: 100 },
  getRowId: (order) => order.id,
  floatingFilters: true,
  columns: [
    { field: 'id', header: 'Order', width: 120 },
    { field: 'customer', header: 'Customer', flex: 1, filter: 'text' },
    { field: 'region', header: 'Region', filter: 'set', options: ['Europe', 'North America', 'Asia Pacific'] },
    { field: 'status', header: 'Status', filter: 'set', options: ['Pending', 'Shipped', 'Delivered'] },
    { field: 'placedAt', header: 'Placed', type: 'date', filter: 'date' },
    { field: 'total', header: 'Total', type: 'number', filter: 'number' },
  ],
});
```

## Pitfalls

- **Apollo, urql and other clients.** If you use a GraphQL client, pass the request's `signal` through its fetch options (for example `context: { fetchOptions: { signal } }` in Apollo) and turn off its normalized cache for this query; the grid already caches blocks.
- **Column ids are field names.** The request uses column ids. If they differ from your schema's field names, map them in `toVariables`.
- **Grouping.** With `groupBy`, requests carry `groupKeys` and `rowGroupCols`; your resolver must return group rows for the top levels. See the request type in the [REST recipe](https://docs.birchui.com/recipes/grid-server-side-rest.md#1-turn-a-request-into-a-query-string).

## Related

- [Load rows from a REST API](https://docs.birchui.com/recipes/grid-server-side-rest.md) covers caching, errors and refreshes.
- [Filter models](https://docs.birchui.com/grid/filtering.md#filter-models).
- [`@birchui/grid-pro` API reference](https://docs.birchui.com/api/grid-pro.md).
