Write multiple key-value pairs

Write multiple keys and values at once. Body should be an array of up to 10,000 key-value pairs to be stored, along with optional expiration information. Existing values and expirations will be overwritten. If neither `expiration` nor `expiration_ttl` is specified, the key-value pair will never expire. If both are set, `expiration_ttl` is used and `expiration` is ignored. The entire request size must be 100 megabytes or less.

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
 * Write multiple key-value pairs
8
 * Write multiple keys and values at once. Body should be an array of up to 10,000 key-value pairs to be stored, along with optional expiration information. Existing values and expirations will be overwritten. If neither `expiration` nor `expiration_ttl` is specified, the key-value pair will never expire. If both are set, `expiration_ttl` is used and `expiration` is ignored. The entire request size must be 100 megabytes or less.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  namespace_identifier: string,
13
  account_identifier: string,
14
  body: {
15
    base64?: boolean;
16
    expiration?: number;
17
    expiration_ttl?: number;
18
    key?: string;
19
    metadata?: { [k: string]: unknown };
20
    value?: string;
21
    [k: string]: unknown;
22
  }[]
23
) {
24
  const url = new URL(
25
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/storage/kv/namespaces/${namespace_identifier}/bulk`
26
  );
27

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