fej/src/server/main.rs

87 lines
2.4 KiB
Rust

#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
#[macro_use]
extern crate diesel_migrations;
#[cfg(test)]
mod tests;
mod catchers;
mod routes;
// Very temporary solution for CORS
// https://stackoverflow.com/questions/62412361/how-to-set-up-cors-or-options-for-rocket-rs
use rocket::{
fairing::{AdHoc, Fairing, Info, Kind},
http::Header,
Request, Response, Rocket,
};
use rocket_contrib::databases::diesel;
#[cfg(feature = "frontend")]
use rocket_contrib::serve::StaticFiles;
pub struct Cors;
impl Fairing for Cors {
fn info(&self) -> Info {
Info {
name: "Add CORS headers to responses",
kind: Kind::Response,
}
}
fn on_response(&self, _: &Request, response: &mut Response) {
response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
response.set_header(Header::new(
"Access-Control-Allow-Methods",
"POST, GET, PATCH, OPTIONS",
));
response.set_header(Header::new("Access-Control-Allow-Headers", "*"));
response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
}
}
// Macro from diesel_migrations that sets up migrations
embed_migrations!();
// This defines a connection to the database
#[database("postgres_fej")]
pub struct FejDbConn(diesel::PgConnection);
// I'd like to thank Stackoverflow for helping me with this
// https://stackoverflow.com/questions/61047355/how-to-run-diesel-migration-with-rocket-in-production
fn run_db_migrations(rocket: Rocket) -> Result<Rocket, Rocket> {
let conn = FejDbConn::get_one(&rocket).expect("database connection");
match embedded_migrations::run(&*conn) {
Ok(()) => Ok(rocket),
Err(_) => Err(rocket),
}
}
fn rocket() -> rocket::Rocket {
// This needs to be muted for the frontend feature
#[allow(unused_mut)]
let mut rocket = rocket::ignite()
.attach(Cors)
.attach(FejDbConn::fairing())
.attach(AdHoc::on_attach("Database Migrations", run_db_migrations))
.mount("/api/ivago", routes::ivago()) // /api being hardcoded is temporary
.register(catchers![catchers::not_found]);
// TODO make all of this not hard-coded
#[cfg(feature = "frontend")]
{
rocket = rocket.mount("/", StaticFiles::from("/app/dist"));
}
rocket
}
fn main() {
rocket().launch();
}