21 分钟学 apollo-client 系列:扩展 ApolloClient 的 api

21 分钟学 apollo-client 是一个系列,简单暴力,包学包会。javascript

搭建 Apollo client 端,集成 redux
使用 apollo-client 来获取数据
修改本地的 apollo store 数据
提供定制方案java

apollo store 存储细节
写入 store 的失败缘由分析和解决方案redux

apollo 的不少 api 都丑得惨绝人寰,好比 readQuerywriteQuery,绝对会让你写不少垃圾代码。
但你又不能去改源码,给官方提了 pr 产品经理又等不起你。那怎么办呢?segmentfault

本章就教你很是简单地实现扩展 client 的 api。api

咱们能够借鉴 Redux 的 enhancer 的写法,为 apollo 的 client 实例添加一些本身的方法。app

enhancers.js函数

const enhancers = [
    log,
];

export default function applyEnhancers(client) {
    // 更函数式的写法是把 enhancers 也做为参数传进来,可是我须要的 enhancer 比较少,作此精简
    return enhancers.reduce(
        (result, enhancer) => enhancer(result),
        client
    );
}

// --- enhancers ---
function log(client) {
    client.log = (...args) => {
        console.log(...args);
    };

    return client;
}

enhancer 的本质就是接收一个 client,对其进行一些修改,再返回一个 client。因此对 client applyEnhancers 的结果仍是一个 client。
这看起来和直接修改 client 没区别,不过是把每个修改,都单独写成一个 enhancer ,比起写在一个巨型函数来讲,这样更便于维护。
更重要的是,applyEnhancers 也会有 pipe 的效果,上一个 enhancer 的输出会成为下一个 enhancer 的输入,便于组合。code

而后咱们只须要在前面的基础上ip

createApolloCLient.jsget

import applyEnhancers from './enhancers';

export default function createApolloCLient() {
    const client = ....; // 能够参看之前的章节查看详细的代码
    return applyEnhancers(client);
}

很是简单吧!

在后面的章节里,你会看到我是如何使用 enhancer 封装 readQuery + writeQuery 为一个 api 的。

相关文章
相关标签/搜索