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