bref/
store.rs

1use std::path::Path;
2
3use anyhow::Result;
4use sled::Db;
5
6use crate::key::Key;
7
8/// Stores key-url pairs to persistent storage.
9///
10/// We are using `sled` as an embedded database because it's simple and fast.
11/// If we needed more space or we wanted to scale our shortener horizontally, we
12/// could use a remote database instead, such as Redis.
13#[derive(Clone)]
14pub struct Store {
15  db: Db,
16}
17
18impl Store {
19  /// Create a new store.
20  pub fn new(path: impl AsRef<Path>) -> Result<Self> {
21    Ok(Self {
22      db: sled::open(path)?,
23    })
24  }
25
26  /// Insert a new key-url pair.
27  pub fn insert(&self, key: &Key, url: &str) -> Result<()> {
28    self.db.insert(key, url)?;
29    Ok(())
30  }
31
32  /// Get the url for a key.
33  pub fn get(&self, key: &Key) -> Result<Option<String>> {
34    Ok(
35      self
36        .db
37        .get(key)?
38        .map(|v| String::from_utf8_lossy(&v).into_owned()),
39    )
40  }
41}