📘
Slickgrid-React
Live DemoGitHub
  • Introduction
  • Getting Started
    • Quick start
  • Styling
    • Dark Mode
    • Styling CSS/SASS/Themes
  • Column Functionalities
    • Cell Menu (Action Menu)
    • Editors
      • Autocomplete
      • new Date Picker (vanilla-calendar)
      • LongText (textarea)
      • Select Dropdown Editor (single/multiple)
    • Filters
      • Autocomplete
      • Input Filter (default)
      • Select Filter (dropdown)
      • Compound Filters
      • Range Filters
      • Custom Filter
      • Styling Filled Filters
      • Single Search Filter
    • Formatters
    • Sorting
  • Events
    • Available events
    • On Events
  • Slick Grid/DataView Objects
    • Slick Grid/DataView Objects
  • Grid Functionalities
    • Auto-Resize / Resizer Service
    • Resize by Cell Content
    • Column Picker
    • Composite Editor Modal
    • Custom Tooltip
    • Add, Update or Highlight a Datagrid Item
    • Dynamically Add CSS Classes to Item Rows
    • Column & Row Spanning
    • Context Menu
    • Custom Footer
    • Excel Copy Buffer Plugin
    • Export to Excel
    • Export to File (csv/txt)
    • Grid Menu
    • Grid State & Presets
    • Grouping & Aggregators
    • Header & Footer Slots
    • Header Menu & Header Buttons
    • Infinite Scroll
    • Pinning (frozen) of Columns/Rows
    • Providing data to the grid
    • Row Detail
    • Row Selection
    • Tree Data Grid
    • Row Based Editing Plugin
  • Developer Guides
    • CSP Compliance
  • Localization
    • with I18N
    • with Custom Locales
  • Backend Services
    • Custom Backend Service
    • OData
    • GraphQL
      • JSON Result Structure
      • Filtering Schema
      • Pagination Schema
      • Sorting Schema
  • Testing
    • Testing Patterns
  • Migrations
    • Migration Guide to 3.x (2023-05-29)
    • Migration Guide to 4.x (2023-12-15)
    • Migration Guide to 5.x (2024-05-10)
    • Versions 6 to 8 are skipped...
    • Migration Guide to 9.x (2025-05-10)
Powered by GitBook
On this page
  • Implementation
  • GraphQL Server Definitions
Edit on GitHub
  1. Backend Services

GraphQL

PreviousODataNextJSON Result Structure

Last updated 3 days ago

index

Description

GraphQL Backend Service (for Pagination purposes) to get data from a backend server with the help of GraphQL.

Demo

/

Note

You can use it when you need to support Pagination (though you could disable Pagination if you wish), that is when your dataset is rather large and has typically more than 5k rows, with a GraphQL endpoint. If your dataset is small (less than 5k rows), then you might be better off with with the "dataset.bind" property. SlickGrid can easily handle million of rows using a DataView object, but personally when the dataset is known to be large, I usually use a backend service (OData or GraphQL) and when it's small I go with a .

Implementation

To connect a backend service into Slickgrid-Universal, you simply need to modify your gridOptions and add a declaration of backendServiceApi. See below for the signature and an example further down below.

TypeScript Signature

backendServiceApi: {
  // On init (or on page load), what action to perform?
  onInit?: (query: string) => Promise<any>;

  // Before executing the query, what action to perform? For example, start a spinner
  preProcess?: () => void;

  // On Processing, we get the query back from the service, and we need to provide a Promise. For example: http.get(myGraphqlUrl)
  process: (query: string) => Promise<any>;

  // After executing the query, what action to perform? For example, stop the spinner
  postProcess: (response: any) => void;

  // Backend Service instance (could be OData or GraphQL Service)
  service: BackendService;

  // Throttle the amount of requests sent to the backend. Default to 500ms
  filterTypingDebounce?: number;
}

As you can see, you mainly need to define which service to use (GridODataService or GraphQLService) and finally add the process and postProcess callback, while all the rest are totally optional.

Typescript GraphQL Service Options

You can also pass certain options to the backendServiceApi through the options property. The list of options is the following

export interface GraphqlServiceOption extends BackendServiceOption {
  /**
   * When using Translation, we probably want to add locale in the query for the filterBy/orderBy to work
   * ex.: users(first: 10, offset: 0, locale: "en-CA", filterBy: [{field: name, operator: EQ, value:"John"}]) {
   */
  addLocaleIntoQuery?: boolean;

  /** Array of column ids that are included in the column definitions */
  columnIds?: string[];

  /** What is the dataset, this is required for the GraphQL query to be built */
  datasetName?: string;

  /** Used for defining the operation name when building the GraphQL query */
  operationName?: string;

  /** Use Pagination Cursor in the GraphQL Server. Note: previously named `isWithCursor */
  useCursor?: boolean;

  /** What are the pagination options? ex.: (first, last, offset) */
  paginationOptions?: GraphqlPaginationOption | GraphqlCursorPaginationOption;

  /** array of Filtering Options, ex.: { field: name, operator: EQ, value: "John" }  */
  filteringOptions?: GraphqlFilteringOption[];

  /** array of Filtering Options, ex.: { field: name, direction: DESC }  */
  sortingOptions?: GraphqlSortingOption[];

  /**
   * Do we want to keep double quotes on field arguments of filterBy/sortBy (field: "name" instead of field: name)
   * ex.: { field: "name", operator: EQ, value: "John" }
   */
  keepArgumentFieldDoubleQuotes?: boolean;

  /**
   * When false, searchTerms may be manipulated to be functional with certain filters eg: string only filters.
   * When true, JSON.stringify is used on the searchTerms and used in the query "as-is". It is then the responsibility of the developer to sanitise the `searchTerms` property if necessary.
   */
  useVerbatimSearchTerms?: boolean;
}

Grid Definition & call of backendServiceApi

Notes

  • onInit is optional and is there to initialize the grid with data on first page load (typically the same call as process)

    • you could load the grid yourself outside of the gridOptions which is why it's optional

  • filterTypingDebounce is a timer (in milliseconds) that waits for user input pause before querying the backend server

    • this is meant to throttle the amount of requests sent to the backend (we don't really want to query every keystroke)

    • 700ms is the default when not provided

Code

import { GraphqlService, GraphqlPaginatedResult, GraphqlServiceApi, } from '@slickgrid-universal/graphql';

const Example: React.FC = () => {
  const [dataset, setDataset] = useState<any[]>([]);
  const [columns, setColumns] = useState<Column[]>([]);
  const [options, setOptions] = useState<GridOption | undefined>(undefined);
  const graphqlService = new GraphqlService();

  useEffect(() => defineGrid(), []);

  function defineGrid() {
    setColumns([/*...*/]);
    setOptions({
      enableFiltering: true,
      enablePagination: true,
      pagination: {
        pageSizes: [10, 15, 20, 25, 30, 40, 50, 75, 100],
        pageSize: defaultPageSize,
        totalItems: 0
      },
      backendServiceApi: {
        service: graphqlService,

        // add some options to the backend service to work
        // shown below is the minimum setup for the service to work correctly
        options: {
          datasetName: 'users',
          paginationOptions: {
            first: 25,
            offset: 0
          }
        },

        // define all the on Event callbacks
        preProcess: () => displaySpinner(true),
        process: (query) => getAllCustomers(query),
        postProcess: (response) => {
          displaySpinner(false);
          getCustomerCallback(response);
        },
        filterTypingDebounce: 700,
        service: graphqlService
      }
    });
  }

  // Web API call
  function getAllCustomers(graphqlQuery) {
    // regular Http Client call
    return fetch(`/api/customers?${graphqlQuery}`).asGet().send().then(response => response.content);

    // or with Fetch Client
    // return fetch(`/api/customers?${graphqlQuery}`).then(response => response.json());
  }
}

export default Example;

Extra Query Arguments

You can pass extra query arguments to the GraphQL query via the extraQueryArguments property defined in the backendServiceApi.options. For example let say you have a list of users and your GraphQL query accepts an optional userId, you can write it in code this way:

setOptions({
  backendServiceApi: {
    service: new GraphqlService(),

    // add some options to the backend service to work
    options: {
      executeProcessCommandOnInit: false, // true by default, which load the data on page load
      datasetName: 'users',
      paginationOptions: {
        first: 25,
        offset: 0
      },
      extraQueryArguments: [{
        field: 'userId',
        value: 567
      }]
    },

    // define all the on Event callbacks
    preProcess: () => displaySpinner(true),
    process: (query) => getCustomerApiCall(query),
    postProcess: (response) => displaySpinner(false)
  }
});

The GraphQL query built with these options will be

// extraQueryArguments will change the userId with
{
  users(first: 20, offset: 0, userId: 567) {
    totalCount,
    nodes {
      id,
      name,
      company
    }
  }
}

Changing/Updating Options Dynamically

You might want to change certain options dynamically, for example passing new set of values to extraQueryArguments. For that you will have to first keep a reference to your GraphqlService instance and then you can call the updateOptions method.

Code Example

import { GraphqlService, GraphqlPaginatedResult, GraphqlServiceApi, } from '@slickgrid-universal/graphql';

const Example: React.FC = () => {
  const [dataset, setDataset] = useState<any[]>([]);
  const [columns, setColumns] = useState<Column[]>([]);
  const [options, setOptions] = useState<GridOption | undefined>(undefined);
  const reactGridRef = useRef<SlickgridReactInstance | null>(null);
  const graphqlService = new GraphqlService();

  useEffect(() => {
    i18next.changeLanguage(defaultLang);
    defineGrid();
  }, []);

  function reactGridReady(reactGrid: SlickgridReactInstance) {
    reactGridRef.current = reactGrid;
  }

  function defineGrid() {
    setColumns([
      // ...
    ]);

    setOptions({
      backendServiceApi: {
        service: graphqlService,
        // ...
      }
    });
  }

  function changeQueryArguments() {
    // update any Backend Service Options you want
    graphqlService.updateOptions({
      extraQueryArguments: [{
        field: 'userId',
        value: 567
      }]
    });

    // then make sure to refresh the dataset
    reactGrid.pluginService.refreshBackendDataset();
  }
}

GraphQL without Pagination

By default, the Pagination is enabled and will produce a GraphQL query which includes page related information but you could also use the GraphQL Service without Pagination if you wish by disabling the flag enablePagination: false in the Grid Options. However please note that the GraphQL Query will be totally different since it won't include any page related information.

Code Example

const gridOptions = {
  enablePagination: false,
  backendServiceApi: {
    service: graphqlService,
    // ...
  }
};

Query Change Example

If we take for example a GrahQL Query that includes Pagination versus without Pagination, you will see a much simpler query string. Also, note that the filtering and sorting won't be affected, they will remain as query input.

with Pagination

  1. query{ users(first:20, offset:40){ totalCount, nodes{ id, field1, field2 }}}

  2. query{ users(first:20, offset:40, filterBy: [{ field: field1, value: 'test', operator: StartsWith }]){ totalCount, nodes{ id, field1, field2 }}}

without Pagination

  1. query{ users{ id, field1, field2 }}

  2. query{ users(filterBy: [{ field: field1, value: 'test', operator: StartsWith }]){ id, field1, field2 }}

GraphQL Server Definitions

For the implementation of all 3 actions (filtering, sorting, pagination) with your GraphQL Server, please refer to the sections below to configure your GraphQL Schema accordingly.

Pagination is optional and if not defined, it will use what is set in the

Slickgrid-Universal - Global Options
Pagination
Sorting
Filtering
Pagination
Sorting
Filtering
Demo Page
Demo ViewModel
regular grid
regular grid
Extra Query Arguments
Changing/Updating Options Dynamically
GraphQL without Pagination
GraphQL Server Definitions
Infinite Scroll