added database and json post

This commit is contained in:
Arlo Filley 2022-09-29 12:12:55 +01:00
parent 6797e6a952
commit 94904481a6
5 changed files with 67 additions and 7 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
/target
Cargo.lock
/database/database.sqlite

View File

@ -7,3 +7,4 @@ edition = "2021"
[dependencies.rocket]
version = "0.5.0-rc.2"
features = ["json"]

View File

@ -1,14 +1,46 @@
// relevant macros and imports for rocket.rs
#[macro_use] extern crate rocket;
use rocket::{Rocket, Build, fs::{FileServer, relative}};
use rocket::{Rocket, Build, fs::{FileServer, relative}, serde::{Deserialize, json::Json}};
#[get("/")]
fn index() -> String {
fn test() -> String {
format!("Hello world")
}
#[derive(Deserialize)]
#[serde(crate = "rocket::serde")]
struct PostTest<'r> {
test_type: &'r str,
test_length: i64,
test_time: i32,
test_seed: i64,
quote_id: i32,
wpm: i16,
accuracy: i8,
user_id: i32
}
#[post("/post_test", data = "<test>")]
fn post_test(test: Json<PostTest<'_>>) {
println!(
"{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
test.test_type,
test.test_length,
test.test_time,
test.test_seed,
test.quote_id,
test.wpm,
test.accuracy,
test.user_id
)
}
#[launch]
fn rocket() -> Rocket<Build> {
rocket::build()
// .mount("/", routes![index])
.mount("/", FileServer::from(relative!("website")))
.mount("/test", routes![test]) // testing only, should return "Hello world"
.mount("/api", routes![post_test])
.mount("/", FileServer::from(relative!("website"))) // hosts the fileserver
}

View File

@ -5,8 +5,13 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- Main Script Files -->
<script src="./index.js" type="text/javascript" defer="true"></script>
<!-- API Script Files -->
</head>
<body>
Hello Fileserver
<button id="button">Submit JSON</button>
</body>
</html>

21
website/index.js Normal file
View File

@ -0,0 +1,21 @@
const url = "http://localhost:8000/api/post_test/"
const data = {
test_type: "words",
test_length: 500,
test_time: 100,
test_seed: 123040004,
quote_id: 0,
wpm: 60,
accuracy: 100,
}
const xhr = new XMLHttpRequest();
const button = document.getElementById("button");
button.addEventListener("click", (e) => {
send();
});
function send() {
xhr.open("POST", url);
xhr.send(JSON.stringify(data));
}