Write key-value pair with metadata

Write a value identified by a key. Use URL-encoding to use special characters (for example, `:`, `!`, `%`) in the key name. Body should be the value to be stored along with JSON metadata to be associated with the key/value pair. Existing values, expirations, and metadata 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.

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 key-value pair with metadata
8
 * Write a value identified by a key. Use URL-encoding to use special characters (for example, `:`, `!`, `%`) in the key name. Body should be the value to be stored along with JSON metadata to be associated with the key/value pair. Existing values, expirations, and metadata 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.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  key_name: string,
13
  namespace_identifier: string,
14
  account_identifier: string,
15
  body: { metadata: string; value: string; [k: string]: unknown }
16
) {
17
  const url = new URL(
18
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/storage/kv/namespaces/${namespace_identifier}/values/${key_name}`
19
  );
20

21
  const formData = new FormData();
22
  for (const [k, v] of Object.entries(body)) {
23
    if (v !== undefined && v !== "") {
24
      formData.append(k, String(v));
25
    }
26
  }
27
  const response = await fetch(url, {
28
    method: "PUT",
29
    headers: {
30
      "X-AUTH-EMAIL": auth.email,
31
      "X-AUTH-KEY": auth.key,
32
      Authorization: "Bearer " + auth.token,
33
    },
34
    body: formData,
35
  });
36
  if (!response.ok) {
37
    const text = await response.text();
38
    throw new Error(`${response.status} ${text}`);
39
  }
40
  return await response.json();
41
}
42