Edits history of script submission #23119 for ' Read KV Value (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 }))
    }
    
    /**
     * Read KV Value
     * Read the value stored under a key in a KV namespace (returned as text).
     */
    export async function main(
      auth: RT.Cloudflare,
      namespace_id: DynSelect_namespace_id,
      key: string
    ) {
      const response = await fetch(
        `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/storage/kv/namespaces/${namespace_id}/values/${encodeURIComponent(key)}`,
        { headers: { Authorization: `Bearer ${auth.token}` } }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.text()
    }
    

    Submitted by hugo989 4 hours ago