如何使用 grpc-web 构建 react-redux 应用程序?

emi*_*l14 7 design-patterns reactjs grpc redux grpc-web

我有一个react-redux应用程序,我的团队使用grpc-web。我想知道 - 设计这种系统的最佳方法是什么?

目前的计划是创建 3 个抽象级别:

  1. API模块 -grpc-web客户端周围的promisified包装器
  2. Redux thunks level - 处理 API 的异步动作创建者
  3. React components props - 只会询问组件需要什么

所以components一无所知grpc,他们与动作创建者混在一起,动作创建者一无所知grpc,他们处理一个api模块,并且只有api模块与grpc-web存根一起使用。

我想走这条路的原因:

  • 动作创建器和组件中没有特定于 grpc 的代码
  • 我的基于 Promise 的 API 而不是 grpc-web 的基于回调的 API

我的问题是:

  1. 在 Redux 和 grpc-web 之间有一个抽象级别是个好主意吗?或者最好将这些东西保留在动作创建者的逻辑中?
  2. 有没有我应该想到的通用设计模式?(我在考虑“适配器”)
  3. 承诺grpc-webAPI是个好主意吗?如果是,编写一个函数并即时执行是否是个好主意?
  4. 我可以说我目前的计划是适配器模式吗?
  5. 如果我想使用适配器模式,我是否必须将数据集合的每个元素都映射到我自己的界面?我知道我的组件(可能还有 action-creators)不应该依赖grpc-webAPI,因为这个 API 将来可能会改变

小智 0

我在 redux thunk 上使用 grpc-web,下面的示例代码来自操作创建者:

export const getStudentInfo = (id) => async dispatch => {

const request = new StudentRequest();
request.setId("555");
var metadata = { 'token': 'value1' };
var URL = "https://localhost:5001";
var client = new StudentClient(URL);
var call = client.getStudentInformation(request, metadata, function (err, response) {

    if (err) {
        console.log(err.code);
        console.log(err.message);
    } else {
        dispatch({ type: STUDENT_INFO, payload: response.getMessage() })
    }
});
call.on('status', function (status) {
    //console.log(status.details);
});

};
Run Code Online (Sandbox Code Playgroud)