thirtyfour/session/
scriptret.rs

1use crate::error::WebDriverResult;
2use crate::session::handle::SessionHandle;
3use crate::WebElement;
4use serde::de::DeserializeOwned;
5use serde_json::Value;
6use std::sync::Arc;
7
8/// Helper struct for getting return values from scripts.
9///
10/// See the examples for [`WebDriver::execute`] and [`WebDriver::execute_async`].
11///
12/// [`WebDriver::execute`]: crate::session::handle::SessionHandle::execute_async
13/// [`WebDriver::execute_async`]: crate::session::handle::SessionHandle::execute_async
14#[derive(Debug)]
15pub struct ScriptRet {
16    handle: Arc<SessionHandle>,
17    value: Value,
18}
19
20impl ScriptRet {
21    /// Create a new ScriptRet.
22    ///
23    /// This is typically done automatically via [`WebDriver::execute`]
24    /// or [`WebDriver::execute_async`].
25    ///
26    /// [`WebDriver::execute`]: crate::session::handle::SessionHandle::execute_async
27    /// [`WebDriver::execute_async`]: crate::session::handle::SessionHandle::execute_async
28    pub fn new(handle: Arc<SessionHandle>, value: Value) -> Self {
29        Self {
30            handle,
31            value,
32        }
33    }
34
35    /// Get the raw JSON value.
36    pub fn json(&self) -> &Value {
37        &self.value
38    }
39
40    /// Get the raw JSON value.
41    #[deprecated(since = "0.30.0", note = "This method has been renamed to json()")]
42    pub fn value(&self) -> &Value {
43        self.json()
44    }
45
46    /// Convert the JSON value into the a deserializeable type.
47    pub fn convert<T>(&self) -> WebDriverResult<T>
48    where
49        T: DeserializeOwned,
50    {
51        let v: T = serde_json::from_value(self.value.clone())?;
52        Ok(v)
53    }
54
55    /// Get a single WebElement return value.
56    ///
57    /// Your script must return only a single element for this to work.
58    pub fn element(self) -> WebDriverResult<WebElement> {
59        WebElement::from_json(self.value, self.handle)
60    }
61
62    /// Get a single WebElement return value.
63    #[deprecated(since = "0.30.0", note = "This method has been renamed to element()")]
64    pub fn get_element(self) -> WebDriverResult<WebElement> {
65        self.element()
66    }
67
68    /// Get a vec of WebElements from the return value.
69    ///
70    /// Your script must return an array of elements for this to work.
71    pub fn elements(self) -> WebDriverResult<Vec<WebElement>> {
72        let values: Vec<Value> = serde_json::from_value(self.value)?;
73        let handle = self.handle;
74        values.into_iter().map(|x| WebElement::from_json(x, handle.clone())).collect()
75    }
76
77    /// Get a vec of WebElements from the return value.
78    #[deprecated(since = "0.30.0", note = "This method has been renamed to elements()")]
79    pub fn get_elements(self) -> WebDriverResult<Vec<WebElement>> {
80        self.elements()
81    }
82}