fej/src/server/main.rs

74 lines
2.1 KiB
Rust
Raw Normal View History

#![feature(proc_macro_hygiene, decl_macro)]
2021-04-02 21:20:36 +02:00
#[macro_use]
extern crate rocket;
2021-04-17 10:52:55 +02:00
#[macro_use]
extern crate rocket_contrib;
2021-04-17 14:43:24 +02:00
#[macro_use]
extern crate diesel_migrations;
#[cfg(test)]
mod tests;
mod catchers;
mod routes;
2021-03-06 00:25:40 +01:00
2021-04-14 22:00:56 +02:00
// Very temporary solution for CORS
// https://stackoverflow.com/questions/62412361/how-to-set-up-cors-or-options-for-rocket-rs
2021-04-17 14:43:24 +02:00
use rocket::fairing::AdHoc;
2021-04-14 22:00:56 +02:00
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::Header;
2021-04-17 14:43:24 +02:00
use rocket::{Request, Response, Rocket};
2021-04-17 10:52:55 +02:00
use rocket_contrib::databases::diesel;
2021-04-14 22:00:56 +02:00
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"));
}
}
2021-04-17 14:43:24 +02:00
// Macro from diesel_migrations that sets up migrations
embed_migrations!();
2021-04-17 10:52:55 +02:00
// This defines a connection to the database
#[database("postgres_fej")]
pub struct FejDbConn(diesel::PgConnection);
2021-04-17 10:52:55 +02:00
2021-04-17 14:43:24 +02:00
// 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(e) => Err(rocket),
}
}
2021-03-06 00:25:40 +01:00
fn rocket() -> rocket::Rocket {
rocket::ignite()
2021-04-14 22:00:56 +02:00
.attach(CORS)
2021-04-17 10:52:55 +02:00
.attach(FejDbConn::fairing())
2021-04-17 14:43:24 +02:00
.attach(AdHoc::on_attach("Database Migrations", run_db_migrations))
.mount("/ivago", routes::ivago())
.register(catchers![catchers::not_found])
2021-03-06 00:25:40 +01:00
}
2021-03-05 18:55:18 +01:00
2021-03-05 18:39:49 +01:00
fn main() {
2021-03-06 00:25:40 +01:00
rocket().launch();
2021-03-05 18:39:49 +01:00
}