1
0
mirror of https://github.com/actix/examples synced 2025-06-27 01:27:43 +02:00

update juniper and middleware examples

This commit is contained in:
Nikolay Kim
2019-03-10 19:19:50 -07:00
parent 0b46125f5d
commit 14eed91fcd
7 changed files with 170 additions and 152 deletions

View File

@ -1,25 +1,63 @@
extern crate actix_web;
use actix_service::{Service, Transform};
use actix_web::dev::{ServiceRequest, ServiceResponse};
use futures::future::{ok, FutureResult};
use futures::{Future, Poll};
use actix_web::middleware::{Finished, Middleware, Response, Started};
use actix_web::{HttpRequest, HttpResponse, Result};
// Middleware can get called at three stages during the request/response handling. Below is a
// struct that implements all three of them.
// There are two step in middleware processing.
// 1. Middleware initialization, middleware factory get called with
// next service in chain as parameter.
// 2. Middleware's call method get called with normal request.
pub struct SayHi;
impl<S> Middleware<S> for SayHi {
fn start(&self, req: &HttpRequest<S>) -> Result<Started> {
println!("Hi from start. You requested: {}", req.path());
Ok(Started::Done)
}
// Middleware factory is `Transform` trait from actix-service crate
// `S` - type of the next service
// `P` - type of request's payload
// `B` - type of response's body
impl<S, P, B> Transform<S> for SayHi
where
S: Service<Request = ServiceRequest<P>, Response = ServiceResponse<B>>,
S::Future: 'static,
S::Error: 'static,
B: 'static,
{
type Request = ServiceRequest<P>;
type Response = ServiceResponse<B>;
type Error = S::Error;
type InitError = ();
type Transform = SayHiMiddleware<S>;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn response(&self, _req: &HttpRequest<S>, resp: HttpResponse) -> Result<Response> {
println!("Hi from response");
Ok(Response::Done(resp))
}
fn finish(&self, _req: &HttpRequest<S>, _resp: &HttpResponse) -> Finished {
println!("Hi from finish");
Finished::Done
fn new_transform(&self, service: S) -> Self::Future {
ok(SayHiMiddleware { service })
}
}
pub struct SayHiMiddleware<S> {
service: S,
}
impl<S, P, B> Service for SayHiMiddleware<S>
where
S: Service<Request = ServiceRequest<P>, Response = ServiceResponse<B>>,
S::Future: 'static,
S::Error: 'static,
B: 'static,
{
type Request = ServiceRequest<P>;
type Response = ServiceResponse<B>;
type Error = S::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready()
}
fn call(&mut self, req: ServiceRequest<P>) -> Self::Future {
println!("Hi from start. You requested: {}", req.path());
Box::new(self.service.call(req).and_then(|res| {
println!("Hi from response");
Ok(res)
}))
}
}