Skip to content

Commit ba65d03

Browse files
authored
Prepend bolt scheme to URI if no scheme is present (#94)
1 parent 29129fd commit ba65d03

File tree

1 file changed

+53
-12
lines changed

1 file changed

+53
-12
lines changed

lib/src/connection.rs

Lines changed: 53 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,9 @@ pub struct Connection {
2222

2323
impl Connection {
2424
pub async fn new(uri: &str, user: &str, password: &str) -> Result<Connection> {
25-
let url = match Url::parse(uri) {
26-
Ok(url) => url,
27-
Err(url::ParseError::RelativeUrlWithoutBase) => Url::parse(&format!("bolt://{}", uri))?,
28-
Err(err) => return Err(Error::UrlParseError(err)),
29-
};
30-
31-
let port = url.port().unwrap_or(7687);
32-
33-
let host = match url.host() {
34-
Some(host) => host,
35-
None => return Err(Error::UrlParseError(url::ParseError::EmptyHost)),
36-
};
25+
let url = NeoUrl::parse(uri)?;
26+
let port = url.port();
27+
let host = url.host();
3728

3829
let stream = match host {
3930
Host::Domain(domain) => TcpStream::connect((domain, port)).await?,
@@ -180,6 +171,33 @@ impl Connection {
180171
}
181172
}
182173

174+
struct NeoUrl(Url);
175+
176+
impl NeoUrl {
177+
fn parse(uri: &str) -> Result<Self> {
178+
let url = match Url::parse(uri) {
179+
Ok(url) if url.has_host() => url,
180+
// missing scheme
181+
Ok(_) => Url::parse(&format!("bolt://{}", uri))?,
182+
Err(err) => return Err(Error::UrlParseError(err)),
183+
};
184+
185+
Ok(Self(url))
186+
}
187+
188+
fn scheme(&self) -> &str {
189+
self.0.scheme()
190+
}
191+
192+
fn host(&self) -> Host<&str> {
193+
self.0.host().unwrap()
194+
}
195+
196+
fn port(&self) -> u16 {
197+
self.0.port().unwrap_or(7687)
198+
}
199+
}
200+
183201
mod stream {
184202
use pin_project_lite::pin_project;
185203
use tokio::{
@@ -255,3 +273,26 @@ mod stream {
255273
}
256274
}
257275
}
276+
277+
#[cfg(test)]
278+
mod tests {
279+
use url::Host;
280+
281+
use super::NeoUrl;
282+
283+
#[test]
284+
fn should_parse_uri() {
285+
let url = NeoUrl::parse("bolt://localhost:4242").unwrap();
286+
assert_eq!(url.port(), 4242);
287+
assert_eq!(url.host(), Host::Domain("localhost"));
288+
assert_eq!(url.scheme(), "bolt");
289+
}
290+
291+
#[test]
292+
fn should_parse_uri_without_scheme() {
293+
let url = NeoUrl::parse("localhost:4242").unwrap();
294+
assert_eq!(url.port(), 4242);
295+
assert_eq!(url.host(), Host::Domain("localhost"));
296+
assert_eq!(url.scheme(), "bolt");
297+
}
298+
}

0 commit comments

Comments
 (0)