Skip to main content

07_fallback/
07_fallback.rs

1use keket::{
2    database::AssetDatabase,
3    fetch::{fallback::FallbackAssetFetch, file::FileAssetFetch},
4    protocol::text::TextAssetProtocol,
5    third_party::anput::bundle::DynamicBundle,
6};
7use std::error::Error;
8
9fn main() -> Result<(), Box<dyn Error>> {
10    /* ANCHOR: main */
11    let mut database = AssetDatabase::default()
12        .with_protocol(TextAssetProtocol)
13        .with_fetch(
14            // Fallback asset fetch in case of error on requested asset bytes load
15            // will try to load asset with matching protocol from fallback paths.
16            FallbackAssetFetch::new(FileAssetFetch::default().with_root("resources"))
17                // This fallback asset does not exists so it will be ignored.
18                .path("text://this-fails-to-load.txt")
19                // This asset exists so it will be loaded as fallback.
20                .path("text://lorem.txt")
21                .factory(|path| {
22                    if path.path() == "default.txt" {
23                        Some(DynamicBundle::new("default content".to_owned()).unwrap())
24                    } else {
25                        None
26                    }
27                }),
28        );
29
30    // This asset exists so it loads normally.
31    let lorem = database.ensure("text://lorem.txt")?;
32
33    // This asset does not exists so it loads fallback asset.
34    let non_existent = database.ensure("text://non-existent.txt")?;
35
36    if lorem.access::<&String>(&database) == non_existent.access::<&String>(&database) {
37        println!("Non existent asset loaded from fallback!");
38    }
39
40    let def = database.ensure("text://default.txt")?;
41    if def.access::<&String>(&database) == "default content" {
42        println!("Default asset loaded from factory!");
43    }
44    /* ANCHOR_END: main */
45
46    Ok(())
47}