Skip to content

Commit

Permalink
react and tower middelware support
Browse files Browse the repository at this point in the history
  • Loading branch information
Sam Bonill committed Oct 29, 2022
1 parent ee870cb commit e33a160
Show file tree
Hide file tree
Showing 10 changed files with 134 additions and 24 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ serde_path_to_error = "0.1.8"
serde_json = "1.0.86"
serde = "1.0"
serde_urlencoded = "0.7"
tower-http = { version = "0.3.0", features = ["fs", "trace"] }
tower-http = { version = "0.3.0", features = ["full"] }
1 change: 1 addition & 0 deletions examples/static-react-spa-app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ publish = false
[dependencies]
graphul = { path = "../../." }
tokio = { version = "1.0", features = ["full"] }
serde_json = "1.0"
18 changes: 18 additions & 0 deletions examples/static-react-spa-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Getting Started with Graphul and React

## Available Scripts

### Requirements:

* Nodejs
* Npm
* Rust :)

In the project directory, you can run:

### `bash run.sh`


Runs the graphul server.\
Open [http://127.0.0.1:8000](http://127.0.0.1:8000) to view it in your browser.

1 change: 1 addition & 0 deletions examples/static-react-spa-app/app/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
/>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link href="https://unpkg.com/[email protected]/dist/tailwind.min.css" rel="stylesheet">
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
Expand Down
56 changes: 35 additions & 21 deletions examples/static-react-spa-app/app/src/App.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,43 @@
import {React, useEffect, useState} from "react";

function App() {

let [data, setData] = useState([])

let graphul_data = async () => {
const response = await fetch(`http://127.0.0.1:8000/api/samuel`);
const data = await response.json();
setData(data)
}

useEffect(() => {
graphul_data()
}, [])

return (
<div className="h-100 w-full flex items-center justify-center bg-teal-lightest font-sans">
<div className="bg-white rounded shadow p-6 m-4 w-full lg:w-3/4 lg:max-w-lg">
<div className="mb-4">
<h1 className="text-grey-darkest">Todo List</h1>
<div className="flex mt-4">
<input className="shadow appearance-none border rounded w-full py-2 px-3 mr-4 text-grey-darker" placeholder="Add Todo" />
<button className="flex-no-shrink p-2 border-2 rounded text-teal border-teal hover:text-white hover:bg-teal">Add</button>
</div>
</div>
<div>
<div className="flex mb-4 items-center">
<p className="w-full text-grey-darkest">Add another component to Tailwind Components</p>
<button className="flex-no-shrink p-2 ml-4 mr-2 border-2 rounded hover:text-white text-green border-green hover:bg-green">Done</button>
<button className="flex-no-shrink p-2 ml-2 border-2 rounded text-red border-red hover:text-white hover:bg-red">Remove</button>
</div>
<div className="flex mb-4 items-center">
<p className="w-full line-through text-green">Submit Todo App Component to Tailwind Components</p>
<button className="flex-no-shrink p-2 ml-4 mr-2 border-2 rounded hover:text-white text-grey border-grey hover:bg-grey">Not Done</button>
<button className="flex-no-shrink p-2 ml-2 border-2 rounded text-red border-red hover:text-white hover:bg-red">Remove</button>
<div className="h-10">
<section className="bg-white dark:bg-gray-900">
<div className="container px-6 py-10 mx-auto">
<h1 className="text-3xl font-semibold text-gray-800 capitalize lg:text-4xl dark:text-white">Graphul Blog</h1>

<div className="grid grid-cols-1 gap-8 mt-8 md:mt-16 md:grid-cols-2">
{data.map((item) =>
<div className="lg:flex" key={item.id}>
<img className="object-cover w-full h-56 rounded-lg lg:w-64" src={item.img} alt="" />

<div className="flex flex-col justify-between py-6 lg:mx-6">
<a href="#" className="text-xl font-semibold text-gray-800 hover:underline dark:text-white ">
{item.title}
</a>

<span className="text-sm text-gray-500 dark:text-gray-300">Author: {item.user_name}</span>
</div>
</div>
)}
</div>
</div>
</div>
</section>
</div>
</div>
);
}

Expand Down
2 changes: 2 additions & 0 deletions examples/static-react-spa-app/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
cd app && npm run build && cd ..
cargo run
56 changes: 56 additions & 0 deletions examples/static-react-spa-app/src/data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use serde_json::{json, Value};

pub fn get_data(name: String) -> Value {
json!(
[
{
"id": 1758,
"user_id": 3678,
"user_name": name,
"img": "https://images.unsplash.com/photo-1515378960530-7c0da6231fb1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80",
"title": "Bardus truculenter suspendo patruus beatus voluptatem vito alter arcesso demens supra deprecator ut aveho somnus.",
"body": "Laboriosam curriculum autem. Claudeo viduo tunc. Defendo arca conventus. Suscipio summa basium. Sed aer arguo. Acer volo quaerat. Bardus ulterius arguo. Creo suppono dolores. Depromo absorbeo et. Strenuus villa temperantia. Non xiphias iusto. Solitudo tenuis in. Cupiditas campana desipio. Aduro sollicito cervus. Molestias curia qui. Argumentum possimus unus. Inflammatio ut nemo. Stipes pecunia nihil. Autus facilis ancilla. Omnis aggero victus."
},
{
"id": 1757,
"user_id": 3676,
"user_name": name,
"img": "https://images.unsplash.com/photo-1497032628192-86f99bcd76bc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80",
"title": "Maxime vae cogito conspergo accedo arbustum ultra sed acsi cornu decet undique quia sint aggredior viduo tantillus assumenda.",
"body": "Solium valeo ante. Vicinus omnis tenetur. Utrimque tristis ex. Tui magni adnuo. Et delibero comis. Bis celebrer creo. Delectatio victoria apud. Stabilis vulgivagus triumphus. Ut cras trans. Denuo volva vivo. Nihil conventus conatus. Veritatis comedo terga. Stultus vito crux. Caute aedificium optio. Est desparatus asper. Tremo eligendi virtus. Acceptus tracto canonicus. Solium taceo molestias. Vomica deporto veritas. Patria conqueror cum."
},
{
"id": 1756,
"user_id": 3675,
"user_name": name,
"img": "https://images.unsplash.com/photo-1544654803-b69140b285a1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80",
"title": "Ut pecunia ver accommodo triginta aliquid repellat.",
"body": "Accommodo adimpleo cultellus. Magnam atrocitas et. Eligendi cur tres. Acceptus vinculum sto. Tergum appello umbra. Sumo timidus aeneus. Deprimo totidem verus. Cognomen subito concido. Ultio sit triginta. Altus amiculum cetera. Cimentarius laudantium assentator. Ullam nostrum degero. Nulla verbera amita. Ea aeger delego. Quia temporibus terreo. Vere aut cibo. Adinventitias utpote ager. Delectatio magnam candidus. Cuppedia valde anser. Pel cogito denuncio."
},
{
"id": 1755,
"user_id": 3674,
"user_name": name,
"img": "https://images.unsplash.com/photo-1530099486328-e021101a494a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1547&q=80",
"title": "Demo validus fugiat vallum crur causa beatus dedico canis aggero videlicet vulgus suscipio ait denique nemo.",
"body": "Aeger ut quidem. Iste aegre aggero. Adduco et sed. Teres id vulnus. Eius id surculus. Ut speciosus adhuc. Arcus vorax valeo. Vel demulceo eveniet. Sequi tenetur arto. Nemo xiphias eligendi. Et magni textus. Consequatur correptius tametsi. Clementia claustrum animi. Contabesco vesica aliquam. Crudelis curto volutabrum. Viscus id ter. Celo teneo cumque. Articulus pecto ter. Virtus cena tego. Trucido decens angulus. Avarus explicabo illum. Vel sortitus canonicus. Aestus delectatio theologus."
},
{
"id": 1754,
"user_id": 3674,
"user_name": name,
"img": "https://images.unsplash.com/photo-1521737604893-d14cc237f11d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1484&q=80",
"title": "Cupiditas sponte fugit careo vilitas strenuus culpo vomica est tenus.",
"body": "Capitulus possimus voluptas. Cerno magnam spiculum. Adiuvo auctus tremo. Cogo suscipio aliquam. Conculco autem cibus. Votum thesis careo. Ago benigne conspergo. Ars cras uberrime. Corona toties numquam. Aegrus alter vaco. Correptius dapifer aegrotatio. Accusantium nihil vinitor. Thymbra vinitor id. Statua adsuesco vito. Tametsi audio accipio. Video auris officia. Coruscus ulterius volo. Sodalitas cohors pariatur. Paulatim taceo nam. Et consequatur bellicus."
},
{
"id": 1753,
"user_id": 3668,
"user_name": name,
"img": "https://images.unsplash.com/photo-1624996379697-f01d168b1a52?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80",
"title": "Vorago coerceo tergiversatio conventus volup beneficium cruciamentum strues vulpes stipes atque ventus voluptatem defleo.",
"body": "Eligendi tabernus conor. Vita crepusculum votum. Voluptatibus saepe numquam. Damno consequatur facilis. Adsuesco adnuo aetas. Sublime conicio suadeo. Attonbitus nam verumtamen. Capillus vobis viridis. Delego casso delinquo. Valens solum beneficium. Texo suffragium custodia. Traho tabella color. Via clementia maxime. Peccatus causa conor. Demonstro ut cometes. Textilis voluptatem crux. Cena antepono sufficio. Aequitas trans atrocitas. Paens fuga et. Beatus accommodo solus."
}
]
)
}
19 changes: 17 additions & 2 deletions examples/static-react-spa-app/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
use graphul::{http::Methods, Context, FolderConfig, Graphul};
mod data;

use data::get_data;
use graphul::{
http::{utils::Method, Methods},
middleware::tower::cors,
Context, FolderConfig, Graphul,
};

#[tokio::main]
async fn main() {
Expand All @@ -7,8 +14,16 @@ async fn main() {
app.static_files("/", "app/build", FolderConfig::spa());

app.get("/api/:name", |c: Context| async move {
format!("Hello, {}", c.params("name"))
c.json(get_data(c.params("name")))
});

app.middleware(
cors::CorsLayer::new()
// allow `GET` and `POST` when accessing the resource
.allow_methods([Method::GET, Method::POST])
// allow requests from any origin
.allow_origin(cors::Any),
);

app.run("127.0.0.1:8000").await;
}
2 changes: 2 additions & 0 deletions src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ pub mod request;
pub mod resource;
pub mod response;

pub use axum::http as utils;

pub use methods::Methods;

pub type StatusCode = hyper::StatusCode;
1 change: 1 addition & 0 deletions src/middleware/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ use crate::Body;
pub use axum::middleware::{self, from_fn};

pub type Next = middleware::Next<Body>;
pub use tower_http as tower;

0 comments on commit e33a160

Please sign in to comment.