Skip to main content

06_router_fetch/
06_router_fetch.rs

1use keket::{
2    database::AssetDatabase,
3    fetch::{file::FileAssetFetch, router::RouterAssetFetch},
4    protocol::{bytes::BytesAssetProtocol, text::TextAssetProtocol},
5};
6use std::error::Error;
7
8fn main() -> Result<(), Box<dyn Error>> {
9    /* ANCHOR: main */
10    let mut database = AssetDatabase::default()
11        .with_protocol(TextAssetProtocol)
12        .with_protocol(BytesAssetProtocol)
13        .with_fetch(
14            // Router allows to combine multiple asset sources, so that proper one to use
15            // for given asset is selected by pattern in asset path.
16            RouterAssetFetch::default()
17                // Every asset that has `router=file` meta, will load asset from file.
18                .route(
19                    |path| path.has_meta_key_value("router", "file"),
20                    FileAssetFetch::default().with_root("resources"),
21                    0,
22                )
23                // Every asset that has `memory/` path prefix, will load from in-memory collection.
24                .route(
25                    |path| path.path().starts_with("memory/"),
26                    vec![(
27                        "memory/trash.bin".to_owned(),
28                        std::fs::read("./resources/trash.bin")?,
29                    )],
30                    1,
31                ),
32        );
33
34    // This asset will select file router.
35    let lorem = database.ensure("text://lorem.txt?router=file")?;
36    println!("Lorem Ipsum: {}", lorem.access::<&String>(&database));
37
38    // This asset will select memory router.
39    let trash = database.ensure("bytes://memory/trash.bin")?;
40    println!("Bytes: {:?}", trash.access::<&Vec<u8>>(&database));
41    /* ANCHOR_END: main */
42
43    Ok(())
44}