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);
...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。