nu_command/network/url/
build_query.rs

1use nu_engine::command_prelude::*;
2
3use super::query::{record_to_query_string, table_to_query_string};
4
5#[derive(Clone)]
6pub struct UrlBuildQuery;
7
8impl Command for UrlBuildQuery {
9    fn name(&self) -> &str {
10        "url build-query"
11    }
12
13    fn signature(&self) -> Signature {
14        Signature::build("url build-query")
15            .input_output_types(vec![
16                (Type::record(), Type::String),
17                (
18                    Type::Table([("key".into(), Type::Any), ("value".into(), Type::Any)].into()),
19                    Type::String,
20                ),
21            ])
22            .category(Category::Network)
23    }
24
25    fn description(&self) -> &str {
26        "Converts record or table into query string applying percent-encoding."
27    }
28
29    fn search_terms(&self) -> Vec<&str> {
30        vec!["convert", "record", "table"]
31    }
32
33    fn examples(&self) -> Vec<Example<'_>> {
34        vec![
35            Example {
36                description: "Outputs a query string representing the contents of this record",
37                example: r#"{ mode:normal userid:31415 } | url build-query"#,
38                result: Some(Value::test_string("mode=normal&userid=31415")),
39            },
40            Example {
41                description: "Outputs a query string representing the contents of this record, with a value that needs to be url-encoded",
42                example: r#"{a:"AT&T", b: "AT T"} | url build-query"#,
43                result: Some(Value::test_string("a=AT%26T&b=AT+T")),
44            },
45            Example {
46                description: "Outputs a query string representing the contents of this record, \"exploding\" the list into multiple parameters",
47                example: r#"{a: ["one", "two"], b: "three"} | url build-query"#,
48                result: Some(Value::test_string("a=one&a=two&b=three")),
49            },
50            Example {
51                description: "Outputs a query string representing the contents of this table containing key-value pairs",
52                example: r#"[[key, value]; [a, one], [a, two], [b, three], [a, four]] | url build-query"#,
53                result: Some(Value::test_string("a=one&a=two&b=three&a=four")),
54            },
55        ]
56    }
57
58    fn run(
59        &self,
60        _engine_state: &EngineState,
61        _stack: &mut Stack,
62        call: &Call,
63        input: PipelineData,
64    ) -> Result<PipelineData, ShellError> {
65        let head = call.head;
66        let input_span = input.span().unwrap_or(head);
67        let value = input.into_value(input_span)?;
68        let span = value.span();
69        let output = match value {
70            Value::Record { ref val, .. } => record_to_query_string(val, span, head),
71            Value::List { ref vals, .. } => table_to_query_string(vals, span, head),
72            // Propagate existing errors
73            Value::Error { error, .. } => Err(*error),
74            other => Err(ShellError::UnsupportedInput {
75                msg: "Expected a record or table from pipeline".to_string(),
76                input: "value originates from here".into(),
77                msg_span: head,
78                input_span: other.span(),
79            }),
80        };
81        Ok(Value::string(output?, head).into_pipeline_data())
82    }
83}
84
85#[cfg(test)]
86mod test {
87    use super::*;
88
89    #[test]
90    fn test_examples() {
91        use crate::test_examples;
92
93        test_examples(UrlBuildQuery {})
94    }
95}