1
0
mirror of https://github.com/actix/examples synced 2025-06-26 17:17:42 +02:00

Restructure folders (#411)

This commit is contained in:
Daniel T. Rodrigues
2021-02-25 21:57:58 -03:00
committed by GitHub
parent 9db98162b2
commit c3407627d0
334 changed files with 127 additions and 120 deletions

View File

@ -0,0 +1,14 @@
[package]
name = "juniper-example"
version = "0.2.0"
authors = ["pyros2097 <pyros2097@gmail.com>"]
edition = "2018"
[dependencies]
actix-web = "3"
actix-cors = "0.4.0"
env_logger = "0.8"
serde = "1.0.103"
serde_json = "1.0.44"
serde_derive = "1.0.103"
juniper = "0.14.2"

74
graphql/juniper/README.md Normal file
View File

@ -0,0 +1,74 @@
# Juniper
[Juniper](https://github.com/graphql-rust/juniper) integration for Actix web.
If you want more advanced example, see also the [juniper-advanced example].
[juniper-advanced example]: https://github.com/actix/examples/tree/master/juniper-advanced
## Usage
### server
```bash
cd examples/juniper
cargo run (or ``cargo watch -x run``)
# Started http server: 127.0.0.1:8080
```
### web client
[http://127.0.0.1:8080/graphiql](http://127.0.0.1:8080/graphiql)
_Query example:_
```graphql
{
human(id: "1234") {
name
appearsIn
homePlanet
}
}
```
_Result:_
```json
{
"data": {
"human": {
"name": "Luke",
"appearsIn": [
"NEW_HOPE"
],
"homePlanet": "Mars"
}
}
}
```
_Mutation example:_
```graphql
mutation {
createHuman(newHuman: {name: "Fresh Kid Ice", appearsIn: EMPIRE, homePlanet: "earth"}) {
id
name
appearsIn
homePlanet
}
}
```
_Result:_
```json
{
"data": {
"createHuman": {
"id": "1234",
"name": "Fresh Kid Ice",
"appearsIn": [
"EMPIRE"
],
"homePlanet": "earth"
}
}
}
```

View File

@ -0,0 +1,63 @@
//! Actix web juniper example
//!
//! A simple example integrating juniper in actix-web
use std::io;
use std::sync::Arc;
use actix_cors::Cors;
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
use juniper::http::graphiql::graphiql_source;
use juniper::http::GraphQLRequest;
mod schema;
use crate::schema::{create_schema, Schema};
async fn graphiql() -> HttpResponse {
let html = graphiql_source("http://127.0.0.1:8080/graphql");
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(html)
}
async fn graphql(
st: web::Data<Arc<Schema>>,
data: web::Json<GraphQLRequest>,
) -> Result<HttpResponse, Error> {
let user = web::block(move || {
let res = data.execute(&st, &());
Ok::<_, serde_json::error::Error>(serde_json::to_string(&res)?)
})
.await?;
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(user))
}
#[actix_web::main]
async fn main() -> io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
// Create Juniper schema
let schema = std::sync::Arc::new(create_schema());
// Start http server
HttpServer::new(move || {
App::new()
.data(schema.clone())
.wrap(middleware::Logger::default())
.wrap(
Cors::new()
.allowed_methods(vec!["POST", "GET"])
.supports_credentials()
.max_age(3600)
.finish(),
)
.service(web::resource("/graphql").route(web::post().to(graphql)))
.service(web::resource("/graphiql").route(web::get().to(graphiql)))
})
.bind("127.0.0.1:8080")?
.run()
.await
}

View File

@ -0,0 +1,62 @@
use juniper::FieldResult;
use juniper::RootNode;
#[derive(GraphQLEnum)]
enum Episode {
NewHope,
Empire,
Jedi,
}
use juniper::{GraphQLEnum, GraphQLInputObject, GraphQLObject};
#[derive(GraphQLObject)]
#[graphql(description = "A humanoid creature in the Star Wars universe")]
struct Human {
id: String,
name: String,
appears_in: Vec<Episode>,
home_planet: String,
}
#[derive(GraphQLInputObject)]
#[graphql(description = "A humanoid creature in the Star Wars universe")]
struct NewHuman {
name: String,
appears_in: Vec<Episode>,
home_planet: String,
}
pub struct QueryRoot;
#[juniper::object]
impl QueryRoot {
fn human(id: String) -> FieldResult<Human> {
Ok(Human {
id: "1234".to_owned(),
name: "Luke".to_owned(),
appears_in: vec![Episode::NewHope],
home_planet: "Mars".to_owned(),
})
}
}
pub struct MutationRoot;
#[juniper::object]
impl MutationRoot {
fn create_human(new_human: NewHuman) -> FieldResult<Human> {
Ok(Human {
id: "1234".to_owned(),
name: new_human.name,
appears_in: new_human.appears_in,
home_planet: new_human.home_planet,
})
}
}
pub type Schema = RootNode<'static, QueryRoot, MutationRoot>;
pub fn create_schema() -> Schema {
Schema::new(QueryRoot {}, MutationRoot {})
}