github_workflow_lib/
workflow.rs

1use crate::database::DbContext;
2use crate::errors::Error;
3use crate::github::GitHubAPI;
4use alfred::Item;
5
6pub struct Workflow<'a> {
7    api_key: &'a str,
8    db: DbContext,
9}
10
11impl<'a> Workflow<'a> {
12    /// # Errors
13    ///
14    /// Will return `Err` if `database` could not be connected to.
15    ///
16    #[inline]
17    pub fn new(api_key: &'a str, database_url: &str) -> Result<Self, Error> {
18        let db = DbContext::new(database_url)?;
19        Ok(Workflow { api_key, db })
20    }
21
22    /// # Errors
23    ///
24    /// Will return `Err` if Contacting GitHub returns an error.
25    ///
26    #[inline]
27    pub fn refresh_cache(&mut self) -> Result<(), Error> {
28        self.db.run_migrations()?;
29        let api = GitHubAPI::new(self.api_key);
30
31        self.db.delete_repositories()?;
32
33        for v in api.accessible_repositories() {
34            self.db.insert_repositories(&v)?;
35        }
36        // and DB cleanup work
37        self.db.optimize()?;
38        Ok(())
39    }
40
41    /// # Errors
42    ///
43    /// Will return `Err` if querying the database fails.
44    ///
45    #[inline]
46    pub fn query<'items>(&self, repo_name: &str) -> Result<Vec<Item<'items>>, Error> {
47        self.db
48            .find_repositories(repo_name, 10)?
49            .into_iter()
50            .map(|repo| {
51                Ok(alfred::ItemBuilder::new(repo.name_with_owner)
52                    .subtitle(repo.name.clone())
53                    .autocomplete(repo.name)
54                    .arg(format!("open {}", repo.url))
55                    .into_item())
56            })
57            .collect::<Result<Vec<_>, _>>()
58    }
59}