关于grpcwebproxy:typescript-实现grpcweb-的拦截器

42次阅读

共计 1041 个字符,预计需要花费 3 分钟才能阅读完成。

npm install grpc-web

编写拦截器

interceptor.ts

import * as grpcWeb from "grpc-web";

// 拦截器必须要实现 intercept 这个接口函数
interface Interceptor {intercept:(request: grpcWeb.Request<any, any>, invoker: (request: grpcWeb.Request<any, any>, metadata?: grpcWeb.Metadata) => grpcWeb.ClientReadableStream<any>)=>void
}

function AuthInterceptor(token:string):Interceptor {
    return {intercept:(request: grpcWeb.Request<any, any>, invoker: (request: grpcWeb.Request<any, any>, metadata?: grpcWeb.Metadata) => grpcWeb.ClientReadableStream<any>)=>{
            // 解决一些 metadata 或者 message 等等
            const metadata = request.getMetadata();
            metadata.token=token;
            
            // 这个 stream 是 ClientReadableStream 类型,能够应用 on、cancel、removeListener 接口函数
            const stream=invoker(request);
            stream.on("status",status => {console.log(status)
            });
            return stream
        }
    }
}
export {AuthInterceptor}

实现办法参考自 grpc.io/blog

应用拦截器

import {AuthInterceptor} from "./interceptor";

const token = "123"
const authInterceptor = AuthInterceptor(token);

const options = {unaryInterceptors: [authInterceptor],
                    streamInterceptors: [authInterceptor],
                }

const proxyAddr = "127.0.0.1:1234"
const demo = new DemoClient(proxyAddr, null, options);
...

正文完
 0