Edits history of script submission #23124 for ' Write KV Pairs (cloudflare)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_namespace_id = string
    
    // Dropdown of the account's KV namespaces, by title.
    export async function namespace_id(auth: RT.Cloudflare) {
      const response = await fetch(
        `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/storage/kv/namespaces?per_page=100`,
        {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { result } = (await response.json()) as {
        result: { id: string; title: string }[]
      }
      return result.map((n) => ({ value: n.id, label: n.title }))
    }
    
    /**
     * Write KV Pairs
     * Write one or more key-value pairs to a KV namespace in a single bulk request (up to 10,000 pairs).
     */
    export async function main(
      auth: RT.Cloudflare,
      namespace_id: DynSelect_namespace_id,
      pairs: { key: string; value: string; expiration_ttl?: number }[]
    ) {
      const response = await fetch(
        `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/storage/kv/namespaces/${namespace_id}/bulk`,
        {
          method: "PUT",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify(pairs),
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 4 hours ago