> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codenullapp.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Custom Query Endpoint

> Enables retrieval of tailored data

Enables retrieval of tailored data

This is useful in the following scenarios

* You need to retrieve data from a different source than the application database
* You want to customize the data returned by the query
* You have complex queries that Codenull cannot process using the normal entity endpoints.

## How to create a Custom Query Endpoint

1. **Create your hook to customize your data**

You need to create a Custom Query Endpoint hook, for instance

```javascript theme={null}

const getPersonas = async () => {
  const data = await options.model.findAndCountAll();
  return {
    items: data.rows,
    total: data.count,
  };
}
getPersonas();
```

Here you can also import your database model or call external APIs, the important thing here is that you must return the data using the same structure `{ items, total }`&#x20;

If you want you can use your default model defined in the next step via `options.model` which in this example is `Persona`, but this is optional.&#x20;

2. **Define your Query**

Define the data source where you'll use the data retrieved by the hook. Use the Hook's ID to attach it to

```graphql theme={null}

query getPersonas{
  customEntityQuery(modelName: Persona, 
  queryOptions: {
    customHookId: "67981f0014d7df001d4aef1b"
  }) 
  {
    items
    total
  }
}

```

## How to use filters and params in a Custom Query Endpoint

Let's define a hook that needs to fetch data from an external source

```javascript theme={null}
const dbApp = require("../modelsapp/db").default;
const { QueryTypes } = require("sequelize");

const getInventarios = async () => {
  try {
    const connection = await DBConnection();

    /*
    you can access the where variable via the params object
    for instance:
    params.where
    params.limit
    params.offset 
    
    You can also have access to the user variable data:
    options.session
    */

    const response = await connection.query(
      `
      SELECT CANT, LOTE, FVTO
      FROM ZZL_VIEW_NIVIEL_INVENTARIO_LOTE
      WHERE REF = '${params.where.REF}'
      ORDER BY FVTO ASC;
      `,
      {
        type: QueryTypes.SELECT
      }
    );

    return {
      items: response, 
      total: response.length,
    };
  } catch (error) {
    console.error("Error en getInventarios:", error);
    throw new Error(JSON.stringify(error.message));
  }
};

getInventarios();
```

Let's configure the data source for the component (Datagrid for instance)

```graphql theme={null}
query getDetallesOrdenes($where: JSON) {
  customEntityQuery(
    where: $where # define the $where variable to be able to use it in the hook
    modelName: DetalleOrden
    queryOptions: {customHookId: "67e2a43a70f7bb0019d9e9e4"} # hook id
  ) {
    items
    total
  }
}
```
