Update a variant

Updating a variant purges the cache for all images associated with the variant.

Script cloudflare Verified

by hugo697 ยท 11/16/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 383 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Update a variant
8
 * Updating a variant purges the cache for all images associated with the variant.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  identifier: string,
13
  account_identifier: string,
14
  body: {
15
    neverRequireSignedURLs?: boolean;
16
    options: {
17
      fit: "scale-down" | "contain" | "cover" | "crop" | "pad";
18
      height: number;
19
      metadata: "keep" | "copyright" | "none";
20
      width: number;
21
      [k: string]: unknown;
22
    };
23
    [k: string]: unknown;
24
  }
25
) {
26
  const url = new URL(
27
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/images/v1/variants/${identifier}`
28
  );
29

30
  const response = await fetch(url, {
31
    method: "PATCH",
32
    headers: {
33
      "X-AUTH-EMAIL": auth.email,
34
      "X-AUTH-KEY": auth.key,
35
      "Content-Type": "application/json",
36
      Authorization: "Bearer " + auth.token,
37
    },
38
    body: JSON.stringify(body),
39
  });
40
  if (!response.ok) {
41
    const text = await response.text();
42
    throw new Error(`${response.status} ${text}`);
43
  }
44
  return await response.json();
45
}
46