头图

typescript 实现grpc-web 的拦截器

Chiu
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);
...
阅读 493
284 声望
5 粉丝
0 条评论
你知道吗?

284 声望
5 粉丝
宣传栏