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

# Crop images to a widget’s aspect ratio

> An editor helper: crops each image of an image relationship to widgetOptions.aspectRatio (unless it is already close), and answers the relationship with each image’s crop in its _fields.

```ts AdonisJS wrap theme={"dark"}
import app from '@adonisjs/core/services/app'
import { SiteClient } from '@fetchski/attract-cms-sdk'

const site = await app.container.make(SiteClient)
const autocropImages = await site.media().autocropImages({ relationship: [{}] })
```

```json 200 wrap theme={"dark"}
{
  "relationship": [
    {}
  ]
}
```

## In your app

A controller answers a route on your app: it calls `autocropImages()` and returns the answer.

**1. Add the controller**

```ts app/controllers/autocrop_images_controller.ts theme={"dark"}
import { inject } from '@adonisjs/core'
import { SiteClient } from '@fetchski/attract-cms-sdk'

@inject()
export default class AutocropImagesController {
  constructor(protected site: SiteClient) {}

  async handle() {
    return this.site.media().autocropImages({ relationship: [{}] })
  }
}
```

The other values are the example’s: take yours from the request, a form or your database.

**2. Add the route**

```ts start/routes.ts theme={"dark"}
import router from '@adonisjs/core/services/router'

const AutocropImagesController = () => import('#controllers/autocrop_images_controller')

router.post('/image/autocrop', [AutocropImagesController])
```

Put it behind your auth middleware (`.use(middleware.auth())`): it acts with your key’s access.

**3. Call it**

Your own page’s form or script sends `POST /image/autocrop` and gets back its answer as JSON. Test it, below, calls it.

Without an aspect ratio it answers the relationship as sent.

> [accordion] Required parameters
>
> One object, e.g. `autocropImages({ relationship })`; leave out the optional fields.
>
> **relationship** `readonly Readonly\<Record\<string, unknown\>\>[]` *required*
>
> **Required.** Image documents as an image relationship holds them, each with its crop and focal point in `_fields`.

> [accordion] Optional parameters
>
> **widgetOptions** `AutocropImagesRequestWidgetOptions | null | undefined`
>
> **Optional.** Leave it out (or pass `null`) and it isn’t sent: the site’s default applies. The image widget’s options.
>
> **AutocropImagesRequestWidgetOptions**
>
> **aspectRatio** `readonly number[]`
>
> Width and height, e.g. `[16, 9]`. 2 to 2 items.
>
> **minSize** `readonly number[]`
>
> The smallest width and height a crop may have, in pixels. 2 to 2 items.

> [accordion] Returns
>
> An `AutocropImagesResponse`. The relationship, cropped. Read its properties (`autocropImages.relationship`): each says whether the site always sends it.
>
> **relationship** `readonly Readonly\<Record\<string, unknown\>\>[]`
>
> **Always sent.** Image documents as an image relationship holds them, each with its crop and focal point in `_fields`.

> [accordion] Errors
>
> Nothing to catch: the SDK retries what is safe, and throws the rest as the classes below. Your exception handler turns them into your app’s own answers, once for every call (see [Map SDK errors to responses](https://docs.fetchski-attract.com/adonisjs/calling-the-api.md#map-sdk-errors-to-responses)); catch only what you want to react to here.
>
> **ValidationFailed** `400`
>
> The site refused what was sent: `errors` lists each field’s problem, `siteMessage` the first.
>
> **Retried first:** No. **Read:** `errors` (field → messages), `siteMessage`.
>
> **AuthenticationFailed** `401`
>
> The API key is missing or refused (malformed, revoked, expired), or a signature its signing mode needs is missing or stale.
>
> **Retried first:** No. **Read:** `siteMessage`, `errorName`, `data`.
>
> **Forbidden** `403`
>
> The key may not do this: a scope it lacks, or an address outside its allowlist. `siteMessage` names it.
>
> **Retried first:** No. **Read:** `siteMessage`, `errorName`, `data`.
>
> **SiteError** `500`
>
> The site failed. Its logs say why.
>
> **Retried first:** No: a write may have landed. **Read:** `siteMessage`, `errorName`, `data`.
>
> **SiteUnreachable** `no answer`
>
> No answer: DNS, a refused connection, TLS, or the timeout (15 s per attempt by default).
>
> **Retried first:** Only when nothing reached the site (`neverConnected()`); never after a timeout, when it may have landed. **Read:** `reason`, `neverConnected`.
>
> **RequestNotSent** `not sent`
>
> The client refused to send it (e.g. a path segment of `..`); the site never saw it.
>
> **Retried first:** No. **Read:** `reason` (what to change).
>
> **SiteRequestFailed** `any other`
>
> Any other status, or a success whose JSON doesn’t match this SDK version’s types (update the SDK).
>
> **Retried first:** No. **Read:** `reason`, `status`.
>
> **UnknownSite** `setup`
>
> `sites.forSite('acme')` named a slug `config/attract.ts` doesn’t list (with the keys in the database: no row in `attract_api_keys`).
>
> **Retried first:** No: nothing was sent. **Read:** `message`, `slug`.
>
> **SiteConfigurationError** `setup`
>
> The site’s entry is wrong: a malformed `baseUrl` or key, a key filed under another slug, or no default site. `node ace attract:check` names the fix.
>
> **Retried first:** No: nothing was sent. **Read:** `message` (what to fix).

## Behavior

* **Access:** an API key with `content:images:write` (or a master above it: `content:images:all`, `content:all`, `admin:all`). A signed-in person may call it as far as their own permissions allow; anyone else gets 403.
* **Rate limit:** the key’s own writes-per-minute limit, set when the key is created (default 120); over it, 429 with `Retry-After`. The client waits and retries for you; you see `RateLimited` only if that runs out.
* **Retries:** a write is sent again only after a 429 (refused before it acted) or when it never reached the site. After a timeout or a 5xx it may have landed: check before you send it again.
* **Timeout:** 15 s per attempt by default; raise `timeout` (milliseconds) in `config/attract.ts` for longer.

## Test it

It calls the controller above with the SDK faked: `fakeAttract()` puts the fake in the container for this one test, and it answers every call with a valid example, so nothing leaves your machine and no key is read. Save it as `tests/unit/media_autocrop_images.spec.ts`, then run your tests:

```ts tests/unit/media_autocrop_images.spec.ts theme={"dark"}
import { test } from '@japa/runner'
import app from '@adonisjs/core/services/app'
import { fakeAttract } from '@fetchski/attract-cms-adonis/testing'
import AutocropImagesController from '#controllers/autocrop_images_controller'

test('media.autocropImages', async () => {
  const site = fakeAttract()

  const controller = await app.container.make(AutocropImagesController)
  await controller.handle()

  site.assertCalled('media.autocropImages')
})
```

```bash Terminal theme={"dark"}
node ace test
```

## Related

> [card] [List images](https://docs.fetchski-attract.com/adonisjs/reference/media/list-images.md)
>
> `site.media().listImages()`

> [card] [Create an image](https://docs.fetchski-attract.com/adonisjs/reference/media/create-image.md)
>
> `site.media().createImage()`

> [card] [Archive images](https://docs.fetchski-attract.com/adonisjs/reference/media/archive-images.md)
>
> `site.media().archiveImages()`

> [card] [Copy images to another locale](https://docs.fetchski-attract.com/adonisjs/reference/media/localize-images.md)
>
> `site.media().localizeImages()`

> [card] [Publish images](https://docs.fetchski-attract.com/adonisjs/reference/media/publish-images.md)
>
> `site.media().publishImages()`

> [card] [Restore images](https://docs.fetchski-attract.com/adonisjs/reference/media/restore-images.md)
>
> `site.media().restoreImages()`

> [card] [POST /@apostrophecms/image/autocrop](https://docs.fetchski-attract.com/api-reference/media/crop-images-to-a-widget’s-aspect-ratio.md)
>
> The endpoint this calls, in the API reference: the HTTP request and answer, and every rule the site checks.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.