wrangler/commands/kv/key/
get.rs

1// TODO:(gabbi) This file should use cloudflare-rs instead of our http::legacy_auth_client
2// when https://github.com/cloudflare/cloudflare-rs/issues/26 is handled (this is
3// because the GET key operation doesn't return json on success--just the raw
4// value).
5
6use cloudflare::framework::response::ApiFailure;
7
8use anyhow::Result;
9
10use crate::commands::kv;
11use crate::http;
12use crate::settings::global_user::GlobalUser;
13use crate::settings::toml::Target;
14use std::io::{self, Write};
15
16pub fn get(target: &Target, user: &GlobalUser, id: &str, key: &str) -> Result<()> {
17    let api_endpoint = format!(
18        "https://api.cloudflare.com/client/v4/accounts/{}/storage/kv/namespaces/{}/values/{}",
19        target.account_id.load()?,
20        id,
21        kv::url_encode_key(key)
22    );
23
24    let client = http::legacy_auth_client(user);
25
26    let res = client.get(&api_endpoint).send()?;
27
28    let response_status = res.status();
29    if response_status.is_success() {
30        let body = res.bytes()?;
31        // We don't use message::success because we don't want to include the emoji/formatting
32        // in case someone is piping this to stdin.
33        // This will probably fail for non-UTF8 on Windows, but should at least work for people
34        // getting binary data from KV on Unix-y systems.
35        io::stdout().write_all(&*body)?;
36    } else {
37        // This is logic pulled from cloudflare-rs for pretty error formatting right now;
38        // it will be redundant when we switch to using cloudflare-rs for all API requests.
39        let parsed = res.json();
40        let errors = parsed.unwrap_or_default();
41        print!(
42            "{}",
43            kv::format_error(ApiFailure::Error(response_status, errors))
44        );
45    }
46
47    Ok(())
48}