# Collection override

{% hint style="success" %}
This is the official documentation of the `@forestadmin/agent` Node.js agent.
{% endhint %}

Forest Admin allows customizing at a very low level the behavior of any given Collection via the usage of Collection Overrides.

{% hint style="info" %}
Collection Overrides provide a powerful means to completely replace the default behavior of CUD operations (`create`, `update`, `delete`) for your Collections. This feature should be used with caution, as it directly affects the core operations on your data.
{% endhint %}

### How it Works

In addition to the standard Collection functions:

* `create`
* `update`
* `delete`

Collection Overrides allow you to define custom behavior that will entirely replace the default implementation of the `create`, `update`, and `delete` operations.

To define an Override for a Collection, you must specify:

* The handler function that will be executed instead of the default operation.

The custom handler function will receive a context object containing relevant information for the operation, allowing for comprehensive control over the behavior of these CUD operations.

### Context object reference

All override contexts provide access to:

* `collection` - the current collection
* `dataSource` - the composite data source containing all collections
* `caller` - information about the user performing the operation (see [Collection Hooks](https://docs.forestadmin.com/developer-guide-agents-nodejs/agent-customization/collection-hook#the-caller-object) for details)

#### Override-specific context properties

| Override   | Properties                                                             |
| ---------- | ---------------------------------------------------------------------- |
| **Create** | `data` - Array of records to create                                    |
| **Update** | `filter` - Filter for records to update, `patch` - Partial update data |
| **Delete** | `filter` - Filter for records to delete                                |

### Setting Up Overrides

Overrides are declared similarly to hooks but are aimed at replacing an entire operation rather than augmenting its execution. However this can also be used to enrich the default behavior. Here's how to set up overrides in your Collection:

#### Custom Create Operation

To replace the default create operation, use `overrideCreate` with your custom handler:

{% hint style="warning" %}
Unknown properties in returned records will be removed.
{% endhint %}

```javascript
collection.overrideCreate(async context => {
  // Custom logic to handle creation
  // context.data contains the data intended for creation
  // Return an array of created records
});
```

#### Custom Update Operation

To replace the default update operation, use `overrideUpdate` with your custom handler:

```javascript
collection.overrideUpdate(async context => {
  // Custom logic to handle update
  // context.filter to determine which records are targeted
  // context.patch contains the data for update
  // Perform update operation
});
```

#### Custom Delete Operation

To replace the default delete operation, use `overrideDelete` with your custom handler:

```javascript
collection.overrideDelete(async context => {
  // Custom logic to handle deletion
  // context.filter to determine which records are targeted
  // Perform deletion operation
});
```

{% hint style="warning" %}
Overrides take precedence over the default operation. Ensure your custom handlers properly manage all necessary logic for the operation, as the default behavior will not be executed.
{% endhint %}

### Basic Use Cases

#### Create over API

You might want to create the record with your custom API:

```javascript
const { MissingFieldError } = require('@forestadmin/datasource-toolkit');

product.overrideCreate(async context => {
  const { data } = context;

  if (data.some(product => !product.name)) {
    throw new MissingFieldError('name', 'products');
  }

  const response = await fetch('https://my-product-api.com/products', {
    method: 'POST',
    body: data,
  });
  const products = await response.json();

  // structure is an array of Partial<Product>
  // [ { name: 'CoffeeMaker3000, price: "$300" } ]
  return products;
});
```

#### Modify data before update

You might want to modify payload data before update your record:

```javascript
product.overrideUpdate(async context => {
  const { patch } = context;

  // Execute data modification and validation only if one of name or slug was edited
  if (patch.name || patch.slug) {
    const name = patch.name || patch.slug.split('-')[0];
    const uuid = await fetch('https://my-product-api.com/slug', {
      method: 'GET',
      body: { name, slug },
    });

    patch.name = name;
    patch.slug = `${name}-${uuid}`;
  }

  await context.collection.update(context.filter, context.patch);
});
```

#### Implementing soft delete

Instead of actually deleting records, mark them as deleted:

```javascript
collection.overrideDelete(async context => {
  // Get all records that would be deleted
  const records = await context.collection.list(context.filter, ['id']);

  // Mark them as deleted instead of actually deleting
  for (const record of records) {
    await context.collection.update(
      { conditionTree: { field: 'id', operator: 'Equal', value: record.id } },
      { deletedAt: new Date(), deletedBy: context.caller.id },
    );
  }
});
```
