storage

Struct FileStore

Source
pub struct FileStore { /* private fields */ }
Expand description

A file store that implements the Store trait

Maze objects are stored on disk as files named <name>.json (in the working directory), with the id of the object assumed to be the file name

Implementations§

Source§

impl FileStore

Source

pub fn new(config: &FileStoreConfig) -> Self

Creates a new file store instance

§Returns

A new file store instance if successful

§Examples

Try to create a new maze within a file store


use data_model::{Maze, User};
use storage::{FileStore, FileStoreConfig, MazeStore, Store, Error, UserStore};

let grid: Vec<Vec<char>> = vec![
   vec!['S', ' ', 'W'],
   vec![' ', 'F', 'W']
];
let mut maze_to_create = Maze::from_vec(grid);
maze_to_create.name = "maze_1".to_string();

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Locate the owner by username
let find_user_result: Result<User, Error> = store.find_user_by_name("a_username");
let owner = match find_user_result {
   Ok(user) => user,
   Err(error) => {
       println!("Error fetching user: {:?}", error);
       return ;
   }
};

// Create a maze within the file store
match store.create_maze(&owner, &mut maze_to_create) {
    Ok(_) => {
        println!(
            "Successfully created maze in the file store with id = {}",
            maze_to_create.id
        );
    }
    Err(error) => {
        println!(
            "Failed to create maze => {}",
            error
        );
    }
}
Source

pub fn get_mazes_dir(&self, owner: &User) -> String

Trait Implementations§

Source§

impl Default for FileStore

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Manage for FileStore

Source§

fn empty(&mut self) -> Result<(), Error>

Resets the store to empty
Source§

impl MazeStore for FileStore

Source§

fn create_maze(&mut self, owner: &User, maze: &mut Maze) -> Result<(), Error>

Creates a new maze within the file store instance

§Examples

Try to create a new maze within a file store


use data_model::{Maze, User};
use storage::{FileStore, FileStoreConfig, MazeStore, Store, Error, UserStore};
use uuid::Uuid;

let grid: Vec<Vec<char>> = vec![
   vec!['S', ' ', 'W'],
   vec![' ', 'F', 'W']
];
let mut maze_to_create = Maze::from_vec(grid);
maze_to_create.name = "maze_1".to_string();

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Locate the owner by username
let find_user_result: Result<User, Error> = store.find_user_by_name("a_username");
let owner = match find_user_result {
   Ok(user) => user,
   Err(error) => {
       println!("Error fetching user: {:?}", error);
       return ;
   }
};

// Create maze within the file store
match store.create_maze(&owner, &mut maze_to_create) {
    Ok(_) => {
        println!(
            "Successfully created maze in the file store with id = {}",
            maze_to_create.id
        );
    }
    Err(error) => {
        println!(
            "Failed to create maze => {}",
            error
        );
    }
}
Source§

fn delete_maze(&mut self, owner: &User, id: &str) -> Result<(), Error>

Deletes an existing maze from within the file store instance

§Examples

Try to delete an existing maze from within a file store


use data_model::{Maze, User};
use storage::{FileStore, FileStoreConfig, MazeStore, Store, Error, UserStore};
use uuid::Uuid;

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Locate the owner by username
let find_user_result: Result<User, Error> = store.find_user_by_name("a_username");
let owner = match find_user_result {
   Ok(user) => user,
   Err(error) => {
       println!("Error fetching user: {:?}", error);
       return ;
   }
};

// Delete maze from within the file store
let id = "maze_1.json".to_string();

match store.delete_maze(&owner, &id) {
    Ok(_) => {
        println!(
            "Successfully delete maze from the file store",
        );
    }
    Err(error) => {
        println!(
            "Failed to delete maze with id {} => {}",
            id,
            error
        );
    }
}
Source§

fn update_maze(&mut self, owner: &User, maze: &mut Maze) -> Result<(), Error>

Updates an existing maze within the file store instance

§Examples

Try to update an existing maze within a file store with new content


use data_model::{Maze, User};
use storage::{FileStore, FileStoreConfig, MazeStore, Store, Error, UserStore};
use uuid::Uuid;

let grid: Vec<Vec<char>> = vec![
   vec!['S', ' ', 'W'],
   vec![' ', 'F', 'W']
];
let mut maze_to_update = Maze::from_vec(grid);
maze_to_update.name = "maze_1".to_string();
maze_to_update.id = "maze_1".to_string();

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Locate the owner by username
let find_user_result: Result<User, Error> = store.find_user_by_name("a_username");
let owner = match find_user_result {
   Ok(user) => user,
   Err(error) => {
       println!("Error fetching user: {:?}", error);
       return ;
   }
};

// Update maze within the file store
match store.update_maze(&owner, &mut maze_to_update) {
    Ok(_) => {
        println!(
            "Successfully updated maze in the file store with id = {}",
            maze_to_update.id
        );
    }
    Err(error) => {
        println!(
            "Failed to update maze => {}",
            error
        );
    }
}
Source§

fn get_maze(&self, owner: &User, id: &str) -> Result<Maze, Error>

Loads a maze from within the file store instance

§Returns

The maze instance if successful

§Examples

Try to create and then reload a maze from within a file store and, if successful, print it


use data_model::{Maze, User};
use maze::{MazePath, MazePrinter};
use storage::{FileStore, FileStoreConfig, MazeStore, Store, Error,  UserStore};
use utils::StdoutLinePrinter;
use uuid::Uuid;

let grid: Vec<Vec<char>> = vec![
   vec!['S', ' ', 'W'],
   vec![' ', 'F', 'W']
];
let mut maze_to_create = Maze::from_vec(grid);
maze_to_create.name = "maze_1".to_string();

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Locate the owner by username
let find_user_result: Result<User, Error> = store.find_user_by_name("a_username");
let owner = match find_user_result {
   Ok(user) => user,
   Err(error) => {
       println!("Error fetching user: {:?}", error);
       return ;
   }
};

// Create the maze within the store
if let Err(error) = store.create_maze(&owner, &mut maze_to_create) {
    println!(
        "Failed to create maze => {}",
        error
    );
    return;
}

// Now reload the maze from the store
match store.get_maze(&owner, &maze_to_create.id) {
    Ok(loaded_maze) => {
        println!("Successfully loaded maze:");
        let mut print_target = StdoutLinePrinter::new();
        let empty_path = MazePath { points: vec![] };
        loaded_maze.print(&mut print_target, empty_path);
    }
    Err(error) => {
        println!(
            "Failed to load maze with id '{}' => {}",
            maze_to_create.id,
            error
        );
    }
}
Source§

fn find_maze_by_name(&self, owner: &User, name: &str) -> Result<MazeItem, Error>

Locates a maze item by name from within the file store instance

§Returns

The maze item if successful

§Examples

Try to find the maze item with name my_maze from within a file store and, if successful, print its details


use data_model::User;
use storage::{FileStore, FileStoreConfig, MazeStore, Store, Error, UserStore};
use uuid::Uuid;

// Create the file store
let store = FileStore::new(&FileStoreConfig::default());

// Locate the owner by username
let find_user_result: Result<User, Error> = store.find_user_by_name("a_username");
let owner = match find_user_result {
   Ok(user) => user,
   Err(error) => {
       println!("Error fetching user: {:?}", error);
       return ;
   }
};

let id = "my_maze".to_string();

// Attempt to find the maze item
match store.find_maze_by_name(&owner, &id) {
    Ok(maze_item) => {
        println!("Successfully found maze item => id = {}, name = {}",
            maze_item.id,
            maze_item.name
        );
    }
    Err(error) => {
        println!(
            "Failed to find maze item with id '{}' => {}",
            id,
            error
        );
    }
}
Source§

fn get_maze_items( &self, owner: &User, include_definitions: bool, ) -> Result<Vec<MazeItem>, Error>

Returns the list of maze items within the file store instance, sorted alphabetically in ascending order, optionally including the maze definitions as a JSON string

§Returns

The maze items if successful

§Examples

Try to load the maze items within a file store and, if successful, print the number of items found


use data_model::User;
use storage::{FileStore, FileStoreConfig, MazeStore, Store, Error, UserStore};
use uuid::Uuid;

// Create the file store
let store = FileStore::new(&FileStoreConfig::default());

// Locate the owner by username
let find_user_result: Result<User, Error> = store.find_user_by_name("a_username");
let owner = match find_user_result {
   Ok(user) => user,
   Err(error) => {
       println!("Error fetching user: {:?}", error);
       return ;
   }
};

// Attempt to load the maze items along with their definitions
match store.get_maze_items(&owner, true) {
    Ok(maze_items) => {
        println!("Successfully loaded {} maze items",
            maze_items.len()
        );
    }
    Err(error) => {
        println!(
            "Failed to load maze items=> {}",
            error
        );
    }
}
Source§

impl UserStore for FileStore

Source§

fn init_default_admin_user( &mut self, username: &str, password_hash: &str, ) -> Result<User, Error>

Adds the default admin user to the store if it doesn’t already exist, else returns it

§Examples

Try to create a new user within a file store


use data_model::User;
use storage::{FileStore, FileStoreConfig, Store, UserStore};
use uuid::Uuid;

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Create the default admin user within the file store if needed
match store.init_default_admin_user("admin", "my_password_hash") {
    Ok(user) => {
        println!(
            "Successfully intiialized default admin user with id {} in the file store",
            user.id
        );
    }
    Err(error) => {
        println!(
            "Failed to initialized default admin user => {}",
            error
        );
    }
}
Source§

fn create_user(&mut self, user: &mut User) -> Result<(), Error>

Adds a new user to the store and sets the allocated id within the user object

§Examples

Try to create a new user within a file store


use data_model::User;
use storage::{FileStore, FileStoreConfig, Store, UserStore};
use uuid::Uuid;

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Create the user definition
let mut user = User {
    id: Uuid::nil(),
    is_admin: false,
    username: "jsmith".to_string(),
    full_name: "John Smith".to_string(),
    email: "jsmith@company.com".to_string(),
    password_hash: "Hashed password".to_string(),
    api_key: Uuid::nil(),
};

// Create the user within the file store
match store.create_user(&mut user) {
    Ok(_) => {
        println!(
            "Successfully created user with id {} in the file store",
            user.id
        );
    }
    Err(error) => {
        println!(
            "Failed to create user => {}",
            error
        );
    }
}
Source§

fn delete_user(&mut self, id: Uuid) -> Result<(), Error>

Deletes a user from the store

§Examples

Try to create and then delete a user within a file store


use data_model::User;
use storage::{FileStore, FileStoreConfig, Store, UserStore};
use uuid::Uuid;

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Create the user definition
let mut user = User {
    id: Uuid::nil(),
    is_admin: false,
    username: "jsmith".to_string(),
    full_name: "John Smith".to_string(),
    email: "jsmith@company.com".to_string(),
    password_hash: "Hashed password".to_string(),
    api_key: Uuid::nil(),
};

// Create the user within the file store
match store.create_user(&mut user) {
    Ok(_) => {
        println!(
            "Successfully created user with id {} in the file store",
            user.id
        );
        match store.delete_user(user.id) {
            Ok(_) => {
                println!("Successfully deleted user from the file store");
            }
            Err(error) => {
                println!(
                    "Failed to delete user => {}",
                     error
                );
            }
        }
    }
    Err(error) => {
        println!(
            "Failed to create user => {}",
            error
        );
    }
}
Source§

fn update_user(&mut self, user: &mut User) -> Result<(), Error>

Updates a user within the store

§Examples

Try to create and then update a user within a file store


use data_model::User;
use storage::{FileStore, FileStoreConfig, Store, UserStore};
use uuid::Uuid;

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Create the user definition
let mut user = User {
    id: Uuid::nil(),
    is_admin: false,
    username: "jsmith".to_string(),
    full_name: "John Smith".to_string(),
    email: "jsmith@company.com".to_string(),
    password_hash: "Hashed password".to_string(),
    api_key: Uuid::nil(),
};

// Create the user within the file store
match store.create_user(&mut user) {
    Ok(_) => {
        println!(
            "Successfully created user with id {} in the file store",
            user.id
        );
        // Change the user full name
        user.full_name = "John Henry Smith".to_string();
        match store.update_user(&mut user) {
            Ok(_) => {
                println!("Successfully update user within the file store");
            }
            Err(error) => {
                println!(
                    "Failed to update user => {}",
                     error
                );
            }
        }
    }
    Err(error) => {
        println!(
            "Failed to create user => {}",
            error
        );
    }
}
Source§

fn get_user(&self, id: Uuid) -> Result<User, Error>

Loads a user from the store

§Examples

Try to create and then load a user from within a file store


use data_model::User;
use storage::{FileStore, FileStoreConfig, Store, UserStore};
use uuid::Uuid;

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Create the user definition
let mut user = User {
    id: Uuid::nil(),
    is_admin: false,
    username: "jsmith".to_string(),
    full_name: "John Smith".to_string(),
    email: "jsmith@company.com".to_string(),
    password_hash: "Hashed password".to_string(),
    api_key: Uuid::nil(),
};

// Create the user within the file store
match store.create_user(&mut user) {
    Ok(_) => {
        println!(
            "Successfully created user with id {} in the file store",
            user.id
        );
        // Now attempt to load it again and display the results
        match store.get_user(user.id) {
            Ok(user_loaded) => {
                println!("Successfully loaded user from within the file store => {:?}", user_loaded);
            }
            Err(error) => {
                println!(
                    "Failed to load user => {}",
                     error
                );
            }
        }
    }
    Err(error) => {
        println!(
            "Failed to create user => {}",
            error
        );
    }
}
Source§

fn find_user_by_name(&self, name: &str) -> Result<User, Error>

Locates a user by their username within the store

§Examples

Try to create and then locate a user from within a file store


use data_model::User;
use storage::{FileStore, FileStoreConfig, Store, UserStore};
use uuid::Uuid;

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Create the user definition
let mut user = User {
    id: Uuid::nil(),
    is_admin: false,
    username: "jsmith".to_string(),
    full_name: "John Smith".to_string(),
    email: "jsmith@company.com".to_string(),
    password_hash: "Hashed password".to_string(),
    api_key: Uuid::nil(),
};

// Create the user within the file store
match store.create_user(&mut user) {
    Ok(_) => {
        println!(
            "Successfully created user with id {} in the file store",
            user.id
        );
        // Now attempt to find it again by username and display the results
        match store.find_user_by_name(&user.username) {
            Ok(user_found) => {
                println!("Successfully found user within the file store => {:?}", user_found);
            }
            Err(error) => {
                println!(
                    "Failed to find user => {}",
                     error
                );
            }
        }
    }
    Err(error) => {
        println!(
            "Failed to create user => {}",
            error
        );
    }
}
Source§

fn find_user_by_api_key(&self, api_key: Uuid) -> Result<User, Error>

Locates a user by their api key within the store

§Examples

Try to create and then locate a user by its api key from within a file store


use data_model::User;
use storage::{FileStore, FileStoreConfig, Store, UserStore};
use uuid::Uuid;

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Create the user definition
let mut user = User {
    id: Uuid::nil(),
    is_admin: false,
    username: "jsmith".to_string(),
    full_name: "John Smith".to_string(),
    email: "jsmith@company.com".to_string(),
    password_hash: "Hashed password".to_string(),
    api_key: Uuid::nil(),
};

// Create the user within the file store
match store.create_user(&mut user) {
    Ok(_) => {
        println!(
            "Successfully created user with id {} in the file store",
            user.id
        );
        // Now attempt to find it again by username and display the results
        match store.find_user_by_api_key(user.api_key) {
            Ok(user_found) => {
                println!("Successfully found user within the file store => {:?}", user_found);
            }
            Err(error) => {
                println!(
                    "Failed to find user => {}",
                     error
                );
            }
        }
    }
    Err(error) => {
        println!(
            "Failed to create user => {}",
            error
        );
    }
}
Source§

fn get_users(&self) -> Result<Vec<User>, Error>

Returns the list of users within the store, sorted alphabetically by username in ascending order

§Examples

Try to create a user within a file store and then load the list of registered users and display their count


use data_model::User;
use storage::{FileStore, FileStoreConfig, Store, UserStore};
use uuid::Uuid;

// Create the file store
let mut store = FileStore::new(&FileStoreConfig::default());

// Create the user definition
let mut user = User {
    id: Uuid::nil(),
    is_admin: false,
    username: "jsmith".to_string(),
    full_name: "John Smith".to_string(),
    email: "jsmith@company.com".to_string(),
    password_hash: "Hashed password".to_string(),
    api_key: Uuid::nil(),
};

// Create the user within the file store
match store.create_user(&mut user) {
    Ok(_) => {
        println!(
            "Successfully created user with id {} in the file store",
            user.id
        );
        // Now attempt to load the user list and display the results
        match store.get_users() {
            Ok(users_found) => {
                println!("Successfully loaded {} users from within the file store", users_found.len());
            }
            Err(error) => {
                println!(
                    "Failed to load users => {}",
                     error
                );
            }
        }
    }
    Err(error) => {
        println!(
            "Failed to create user => {}",
            error
        );
    }
}
Source§

impl Store for FileStore

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.