notegraf_web/
startup.rs

1use crate::routes::*;
2use crate::NoteType;
3use actix_files::{Files, NamedFile};
4use actix_web::dev::Server;
5use actix_web::middleware::{NormalizePath, TrailingSlash};
6use actix_web::web::Data;
7use actix_web::{web, App, HttpServer};
8use notegraf::notestore::BoxedNoteStore;
9use std::net::TcpListener;
10use tracing_actix_web::TracingLogger;
11
12async fn index_file() -> actix_web::Result<NamedFile> {
13    Ok(NamedFile::open("./dist/index.html")?)
14}
15
16pub fn run(
17    listener: TcpListener,
18    note_store: BoxedNoteStore<NoteType>,
19    debug: bool,
20) -> Result<Server, std::io::Error> {
21    let ns: Data<BoxedNoteStore<NoteType>> = Data::new(note_store);
22    let server = HttpServer::new(move || {
23        App::new()
24            .wrap(NormalizePath::new(TrailingSlash::Trim))
25            .wrap(TracingLogger::default())
26            .service(web::scope("/api/v1").configure(api_v1_config))
27            .configure(index_config)
28            .configure(|cfg| {
29                if !debug {
30                    cfg.service(Files::new("/static", "./dist/"));
31                }
32            })
33            // Service the static page for client-side routing
34            // https://create-react-app.dev/docs/deployment/#serving-apps-with-client-side-routing
35            .service(web::resource("/{tail}*").route(web::get().to(index_file)))
36            .app_data(ns.clone())
37    })
38    .listen(listener)?
39    .run();
40    Ok(server)
41}