Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generic arguments #8

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Sofa - CouchDB for Rust

[![Crates.io](https://img.shields.io/crates/v/sofa.svg)](https://crates.io/crates/sofa)
[![Crates.io](https://img.shields.io/crates/v/sofa.svg)](https://crates.io/crates/sofa)[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FYellowInnovation%2Fsofa.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2FYellowInnovation%2Fsofa?ref=badge_shield)

[![docs.rs](https://docs.rs/sofa/badge.svg)](https://docs.rs/sofa)

![sofa-logo](https://raw.githubusercontent.com/YellowInnovation/sofa/master/docs/logo-sofa.png "Logo Sofa")
Expand Down Expand Up @@ -54,10 +55,13 @@ Licensed under either of these:
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
[https://opensource.org/licenses/MIT](https://opensource.org/licenses/MIT))


[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FYellowInnovation%2Fsofa.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2FYellowInnovation%2Fsofa?ref=badge_large)

## Yellow Innovation

Yellow Innovation is the innovation laboratory of the French postal service: La Poste.

We create innovative user experiences and journeys through services with a focus on IoT lately.

[Yellow Innovation's website and works](http://yellowinnovation.fr/en/)
[Yellow Innovation's website and works](http://yellowinnovation.fr/en/)
Expand Down
52 changes: 26 additions & 26 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ pub struct Client {
}

impl Client {
pub fn new(uri: String) -> Result<Client, Error> {
pub fn new<S: Into<String>>(uri: S) -> Result<Client, Error> {
let client = reqwest::Client::builder()
.gzip(true)
.timeout(Duration::new(4, 0))
.build()?;

Ok(Client {
_client: client,
uri: uri,
uri: uri.into(),
_gzip: true,
_timeout: 4,
dbs: Vec::new(),
Expand All @@ -51,13 +51,13 @@ impl Client {
self
}

pub fn set_uri(&mut self, uri: String) -> &Self {
self.uri = uri;
pub fn set_uri<S: Into<String>>(&mut self, uri: S) -> &Self {
self.uri = uri.into();
self
}

pub fn set_prefix(&mut self, prefix: String) -> &Self {
self.db_prefix = prefix;
pub fn set_prefix<S: Into<String>>(&mut self, prefix: S) -> &Self {
self.db_prefix = prefix.into();
self
}

Expand All @@ -68,8 +68,8 @@ impl Client {
Ok(self)
}

pub fn timeout(&mut self, to: u8) -> Result<&Self, Error> {
self._timeout = to;
pub fn timeout<U: Into<u8>>(&mut self, to: U) -> Result<&Self, Error> {
self._timeout = to.into();
self._client = self.create_client()?;

Ok(self)
Expand All @@ -82,12 +82,12 @@ impl Client {
Ok(data)
}

fn build_dbname(&self, dbname: &'static str) -> String {
self.db_prefix.clone() + dbname
fn build_dbname<S: AsRef<str>>(&self, dbname: S) -> String {
format!("{}{}", self.db_prefix, dbname.as_ref())
}

pub fn db(&self, dbname: &'static str) -> Result<Database, Error> {
let name = self.build_dbname(dbname);
pub fn db<S: AsRef<str>>(&self, dbname: S) -> Result<Database, Error> {
let name = self.build_dbname(&dbname);

let db = Database::new(name.clone(), self.clone());

Expand All @@ -99,12 +99,12 @@ impl Client {

match head_response.status() {
StatusCode::Ok => Ok(db),
_ => self.make_db(dbname),
_ => self.make_db(&dbname),
}
}

pub fn make_db(&self, dbname: &'static str) -> Result<Database, Error> {
let name = self.build_dbname(dbname);
pub fn make_db<S: AsRef<str>>(&self, dbname: S) -> Result<Database, Error> {
let name = self.build_dbname(&dbname);

let db = Database::new(name.clone(), self.clone());

Expand All @@ -125,7 +125,7 @@ impl Client {
}
}

pub fn destroy_db(&self, dbname: &'static str) -> Result<bool, Error> {
pub fn destroy_db<S: AsRef<str>>(&self, dbname: S) -> Result<bool, Error> {
let path = self.create_path(self.build_dbname(dbname), None)?;
let response = self._client.delete(&path)
.header(reqwest::header::ContentType::json())
Expand All @@ -146,11 +146,11 @@ impl Client {
Ok(status)
}

fn create_path(&self,
path: String,
fn create_path<S: AsRef<str>>(&self,
path: S,
args: Option<HashMap<String, String>>
) -> Result<String, Error> {
let mut uri = Url::parse(&self.uri)?.join(&path)?;
let mut uri = Url::parse(&self.uri)?.join(path.as_ref())?;

if let Some(ref map) = args {
let mut qp = uri.query_pairs_mut();
Expand All @@ -162,9 +162,9 @@ impl Client {
Ok(uri.into_string())
}

pub fn req(&self,
pub fn req<S: AsRef<str>>(&self,
method: Method,
path: String,
path: S,
opts: Option<HashMap<String, String>>
) -> Result<RequestBuilder, Error> {
let uri = self.create_path(path, opts)?;
Expand All @@ -175,27 +175,27 @@ impl Client {
Ok(req)
}

pub fn get(&self, path: String, args: Option<HashMap<String, String>>) -> Result<RequestBuilder, Error> {
pub fn get<S: AsRef<str>>(&self, path: S, args: Option<HashMap<String, String>>) -> Result<RequestBuilder, Error> {
Ok(self.req(Method::Get, path, args)?)
}

pub fn post(&self, path: String, body: String) -> Result<RequestBuilder, Error> {
pub fn post<S: AsRef<str>>(&self, path: S, body: String) -> Result<RequestBuilder, Error> {
let mut req = self.req(Method::Post, path, None)?;
req.body(body);
Ok(req)
}

pub fn put(&self, path: String, body: String) -> Result<RequestBuilder, Error> {
pub fn put<S: AsRef<str>>(&self, path: S, body: String) -> Result<RequestBuilder, Error> {
let mut req = self.req(Method::Put, path, None)?;
req.body(body);
Ok(req)
}

pub fn head(&self, path: String, args: Option<HashMap<String, String>>) -> Result<RequestBuilder, Error> {
pub fn head<S: AsRef<str>>(&self, path: S, args: Option<HashMap<String, String>>) -> Result<RequestBuilder, Error> {
Ok(self.req(Method::Head, path, args)?)
}

pub fn delete(&self, path: String, args: Option<HashMap<String, String>>) -> Result<RequestBuilder, Error> {
pub fn delete<S: AsRef<str>>(&self, path: S, args: Option<HashMap<String, String>>) -> Result<RequestBuilder, Error> {
Ok(self.req(Method::Delete, path, args)?)
}
}
21 changes: 11 additions & 10 deletions src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ pub struct Database {
}

impl Database {
pub fn new(name: String, client: Client) -> Database {
pub fn new<S: Into<String>>(name: S, client: Client) -> Database {
Database {
_client: client,
name: name,
name: name.into(),
}
}

Expand All @@ -42,10 +42,10 @@ impl Database {
result
}

fn create_compact_path(&self, design_name: &'static str) -> String {
fn create_compact_path<S: AsRef<str>>(&self, design_name: S) -> String {
let mut result: String = self.name.clone();
result.push_str("/_compact/");
result.push_str(design_name);
result.push_str(design_name.as_ref());
result
}

Expand Down Expand Up @@ -82,7 +82,7 @@ impl Database {
}

/// Starts the compaction of a given index
pub fn compact_index(&self, index: &'static str) -> bool {
pub fn compact_index<S: AsRef<str>>(&self, index: S) -> bool {
let request = self._client.post(self.create_compact_path(index), "".into());

request
Expand Down Expand Up @@ -281,12 +281,12 @@ impl Database {

/// Inserts an index in a naive way, if it already exists, will throw an
/// `Err`
pub fn insert_index(&self, name: String, spec: IndexFields) -> Result<IndexCreated, Error> {
pub fn insert_index<S: Into<String>>(&self, name: S, spec: IndexFields) -> Result<IndexCreated, Error> {
let response = self._client
.post(
self.create_document_path("_index".into()),
js!(json!({
"name": name,
"name": name.into(),
"index": spec
})),
)?
Expand Down Expand Up @@ -314,19 +314,20 @@ impl Database {
/// Method to ensure an index is created on the database with the following
/// spec. Returns `true` when we created a new one, or `false` when the
/// index was already existing.
pub fn ensure_index(&self, name: String, spec: IndexFields) -> Result<bool, Error> {
pub fn ensure_index<S: Into<String>>(&self, name: S, spec: IndexFields) -> Result<bool, Error> {
let n = name.into();
let db_indexes = self.read_indexes()?;

// We look for our index
for i in db_indexes.indexes.into_iter() {
if i.name == name {
if &i.name == &n {
// Found? Ok let's return
return Ok(false);
}
}

// Let's create it then
let _ = self.insert_index(name, spec)?;
let _ = self.insert_index(n, spec)?;

// Created and alright
Ok(true)
Expand Down
6 changes: 3 additions & 3 deletions src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ impl Document {

/// Recursively populates field (must be an array of IDs from another
/// database) with provided database documents
pub fn populate(&mut self, field: &String, db: Database) -> &Self {
let ref val = self[field].clone();
pub fn populate<S: AsRef<str>>(&mut self, field: S, db: Database) -> &Self {
let ref val = self[field.as_ref()].clone();
if *val == Value::Null {
return self;
}
Expand All @@ -84,7 +84,7 @@ impl Document {

match data {
Ok(data) => {
self[field] = data.into_iter()
self[field.as_ref()] = data.into_iter()
.filter_map(|d: Value| {
let did = match d["_id"].as_str() {
Some(did) => did,
Expand Down
14 changes: 7 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,14 +156,14 @@ mod sofa_tests {

#[test]
fn a_should_check_couchdbs_status() {
let client = Client::new("http://localhost:5984".into()).unwrap();
let client = Client::new("http://localhost:5984").unwrap();
let status = client.check_status();
assert!(status.is_ok());
}

#[test]
fn b_should_create_sofa_test_db() {
let client = Client::new("http://localhost:5984".into()).unwrap();
let client = Client::new("http://localhost:5984").unwrap();
let dbw = client.db("b_should_create_sofa_test_db");
assert!(dbw.is_ok());

Expand All @@ -172,7 +172,7 @@ mod sofa_tests {

#[test]
fn c_should_create_a_document() {
let client = Client::new("http://localhost:5984".into()).unwrap();
let client = Client::new("http://localhost:5984").unwrap();
let dbw = client.db("c_should_create_a_document");
assert!(dbw.is_ok());
let db = dbw.unwrap();
Expand All @@ -191,7 +191,7 @@ mod sofa_tests {

#[test]
fn d_should_destroy_the_db() {
let client = Client::new("http://localhost:5984".into()).unwrap();
let client = Client::new("http://localhost:5984").unwrap();
let _ = client.db("d_should_destroy_the_db");

assert!(client.destroy_db("d_should_destroy_the_db").unwrap());
Expand All @@ -202,7 +202,7 @@ mod sofa_tests {
use *;

fn setup(dbname: &'static str) -> (Client, Database, Document) {
let client = Client::new("http://localhost:5984".into()).unwrap();
let client = Client::new("http://localhost:5984").unwrap();
let dbw = client.db(dbname);
assert!(dbw.is_ok());
let db = dbw.unwrap();
Expand Down Expand Up @@ -257,7 +257,7 @@ mod sofa_tests {

let spec = types::IndexFields::new(vec![types::SortSpec::Simple(s!("thing"))]);

let res = db.insert_index("thing-index".into(), spec);
let res = db.insert_index("thing-index", spec);

assert!(res.is_ok());

Expand Down Expand Up @@ -289,7 +289,7 @@ mod sofa_tests {

let spec = types::IndexFields::new(vec![types::SortSpec::Simple(s!("thing"))]);

let res = db.ensure_index("thing-index".into(), spec);
let res = db.ensure_index("thing-index", spec);
assert!(res.is_ok());

teardown(client, "f_should_ensure_index_in_db");
Expand Down