Fluent Fetcher: 重构基于 Fetch 的 JavaScript 网络请求库

开发 开发工具
V2 版本中的 Fluent Fetcher 中,最核心的设计变化在于将请求构建与请求执行剥离了开来。RequestBuilder 提供了构造器模式的接口,使用者首先通过 RequestBuilder 构建请求地址与配置,该配置也就是 fetch 支持的标准配置项;使用者也可以复用 RequestBuilder 中定义的非请求体相关的公共配置信息。

 [[195852]]

源代码地址:这里

第一版本的 Fluent Fetcher 中,笔者希望将所有的功能包含在单一的 FluentFetcher 类内,结果发现整个文件冗长而丑陋;在团队内部尝试推广时也无人愿用,包括自己过了一段时间再拾起这个库也觉得很棘手。在编写 declarative-crawler 的时候,笔者又用到了 fluent-fetcher,看着如乱麻般的代码,我不由沉思,为什么当时会去封装这个库?为什么不直接使用 fetch,而是自找麻烦多造一层轮子。框架本身是对于复用代码的提取或者功能的扩展,其会具有一定的内建复杂度。如果内建复杂度超过了业务应用本身的复杂度,那么引入框架就不免多此一举了。而网络请求则是绝大部分客户端应用不可或缺的一部分,纵观多个项目,我们也可以提炼出很多的公共代码;譬如公共的域名、请求头、认证等配置代码,有时候需要添加扩展功能:譬如重试、超时返回、缓存、Mock 等等。笔者构建 Fluent Fetcher 的初衷即是希望能够简化网络请求的步骤,将原生 fetch 中偏声明式的构造流程以流式方法调用的方式提供出来,并且为原有的执行函数添加部分功能扩展。

那么之前框架的问题在于:

  • 模糊的文档,很多参数的含义、用法包括可用的接口类型都未讲清楚;
  • 接口的不一致与不直观,默认参数,是使用对象解构(opt = {})还是函数的默认参数(arg1, arg2 = 2);
  • 过多的潜在抽象漏洞,将 Error 对象封装了起来,导致使用者很难直观地发现错误,并且也不便于使用者进行个性化定制;
  • 模块独立性的缺乏,很多的项目都希望能提供尽可能多的功能,但是这本身也会带来一定的风险,同时会导致最终打包生成的包体大小的增长。

好的代码,好的 API 设计确实应该如白居易的诗,浅显易懂而又韵味悠长,没有人有义务透过你邋遢的外表去发现你美丽的心灵。开源项目本身也意味着一种责任,如果是单纯地为了炫技而提升了代码的复杂度却是得不偿失。笔者认为最理想的情况是使用任何第三方框架之前都能对其源代码有所了解,像 React、Spring Boot、TensorFlow 这样比较复杂的库,我们可以慢慢地拨开它的面纱。而对于一些相对小巧的工具库,出于对自己负责、对团队负责的态度,在引入之前还是要了解下它们的源码组成,了解有哪些文档中没有提及的功能或者潜在风险。笔者在编写 Fluent Fetcher 的过程中也参考了 OkHttp、super-agent、request 等流行的网络请求库。

基本使用

V2 版本中的 Fluent Fetcher 中,最核心的设计变化在于将请求构建与请求执行剥离了开来。RequestBuilder 提供了构造器模式的接口,使用者首先通过 RequestBuilder 构建请求地址与配置,该配置也就是 fetch 支持的标准配置项;使用者也可以复用 RequestBuilder 中定义的非请求体相关的公共配置信息。而 execute 函数则负责执行请求,并且返回经过扩展的 Promise 对象。直接使用 npm / yarn 安装即可:

  1. npm install fluent-fetcher 
  2.  
  3. or 
  4.  
  5. yarn add fluent-fetcher 

创建请求

基础的 GET 请求构造方式如下:

  1. import { RequestBuilder } from "../src/index.js"
  2.  
  3. test("构建完整跨域缓存请求", () => { 
  4.   let { url, option }: RequestType = new RequestBuilder({  
  5.       scheme: "https"
  6.       host: "api.com"
  7.       encoding: "utf-8" 
  8.   }) 
  9.     .get("/user"
  10.     .cors() 
  11.     .cookie("*"
  12.     .cache("no-cache"
  13.     .build({ 
  14.       queryParam: 1, 
  15.       b: "c" 
  16.     }); 
  17.  
  18.   chaiExpect(url).to.equal("https://api.com/user?queryParam=1&b=c"); 
  19.  
  20.   expect(option).toHaveProperty("cache""no-cache"); 
  21.  
  22.   expect(option).toHaveProperty("credentials""include"); 
  23. }); 

RequestBuilder 的构造函数支持传入三个参数:

  1. * @param scheme http 或者 https 
  2. * @param host 请求的域名 
  3. * @param encoding 编码方式,常用的为 utf8 或者 gbk 

然后我们可以使用 header 函数设置请求头,使用 get / post / put / delete / del 等方法进行不同的请求方式与请求体设置;对于请求体的设置是放置在请求方法函数的第二与第三个参数中:

  1. // 第二个参数传入请求体 
  2. // 第三个参数传入编码方式,默认为 raw json 
  3. post("/user", { a: 1 }, "x-www-form-urlencoded"

最后我们调用 build 函数进行请求构建,build 函数会返回请求地址与请求配置;此外 build 函数还会重置内部的请求路径与请求体。鉴于 Fluent Fetch 底层使用了 node-fetch,因此 build 返回的 option 对象在 Node 环境下仅支持以下属性与扩展属性:

  1.     // Fetch 标准定义的支持属性 
  2.     method: 'GET'
  3.     headers: {},        // request headers. format is the identical to that accepted by the Headers constructor (see below) 
  4.     body: null,         // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream 
  5.     redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect 
  6.  
  7.     // node-fetch 扩展支持属性 
  8.     follow: 20,         // maximum redirect count. 0 to not follow redirect 
  9.     timeout: 0,         // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies) 
  10.     compress: true,     // support gzip/deflate content encoding. false to disable 
  11.     size: 0,            // maximum response body size in bytes. 0 to disable 
  12.     agent: null         // http(s).Agent instance, allows custom proxy, certificate etc. 

此外,node-fetch 默认请求头设置:

HeaderValueAccept-Encodinggzip,deflate (when options.compress === true)Accept*/*Connectionclose (when no options.agent is present)Content-Length(automatically calculated, if possible)User-Agentnode-fetch/1.0 (+https://github.com/bitinn/node-fetch)

请求执行

execute 函数的说明为:

  1. /** 
  2.  * Description 根据传入的请求配置发起请求并进行预处理 
  3.  * @param url 
  4.  * @param option 
  5.  * @param {*} acceptType json | text | blob 
  6.  * @param strategy 
  7.  */ 
  8.  export default function execute
  9.   url: string, 
  10.   optionany = {}, 
  11.   acceptType: "json" | "text" | "blob" = "json"
  12.   strategy: strategyType = {} 
  13. ): Promise<any>{} 
  14.  
  15. type strategyType = { 
  16.   // 是否需要添加进度监听回调,常用于下载 
  17.   onProgress: (progress: number) => {}, 
  18.  
  19.   // 用于 await 情况下的 timeout 参数 
  20.   timeout: number 
  21. }; 

引入合适的请求体

默认的浏览器与 Node 环境下我们直接从项目的根入口引入文件即可:

  1. import {execute, RequestBuilder} from "../../src/index.js"

默认情况下,其会执行 require("isomorphic-fetch"); ,而在 React Native 情况下,鉴于其自有 fetch 对象,因此就不需要动态注入。譬如笔者在CoderReader 中 获取 HackerNews 数据时,就需要引入对应的入口文件

  1. import { RequestBuilder, execute } from "fluent-fetcher/dist/index.rn"

而在部分情况下我们需要以 Jsonp 方式发起请求(仅支持 GET 请求),就需要引入对应的请求体:

  1. import { RequestBuilder, execute } from "fluent-fetcher/dist/index.jsonp"

引入之后我们即可以正常发起请求,对于不同的请求类型与请求体,请求执行的方式是一致的:

  1. test("测试基本 GET 请求", async () => { 
  2.   const { url: getUrl, option: getOption } = requestBuilder 
  3.     .get("/posts"
  4.     .build(); 
  5.  
  6.   let posts = await execute(getUrl, getOption); 
  7.  
  8.   expectChai(posts).to.have.length(100); 
  9. }); 

需要注意的是,部分情况下在 Node 中进行 HTTPS 请求时会报如下异常:

  1. (node:33875) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): FetchError: request to https://test.api.truelore.cn/users?token=144d3e0a-7abb-4b21-9dcb-57d477a710bd failed, reason: unable to verify the first certificate 
  2. (node:33875) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

我们需要动态设置如下的环境变量:

  1. process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"

自动脚本插入

有时候我们需要自动地获取到脚本然后插入到界面中,此时就可以使用 executeAndInject 函数,其往往用于异步加载脚本或者样式类的情况:

  1. import { executeAndInject } from "../../src/index"
  2.  
  3. let texts = await executeAndInject([ 
  4.   "https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css" 
  5. ]); 

笔者在 create-react-boilerplate 项目提供的性能优化模式中也应用了该函数,在 React 组件中我们可以在 componentDidMount 回调中使用该函数来动态加载外部脚本:

  1. // @flow 
  2. import React, { Component } from "react"
  3. import { message, Spin } from "antd"
  4. import { executeAndInject } from "fluent-fetcher"
  5.  
  6. /** 
  7.  * @function 执行外部脚本加载工作 
  8.  */ 
  9. export default class ExternalDependedComponent extends Component { 
  10.   state = { 
  11.     loaded: false 
  12.   }; 
  13.  
  14.   async componentDidMount() { 
  15.     await executeAndInject([ 
  16.       "https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.3.1/css/swiper.min.css"
  17.       "https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.3.1/js/swiper.min.js" 
  18.     ]); 
  19.  
  20.     message.success("异步 Swiper 脚本加载完毕!"); 
  21.  
  22.     this.setState({ 
  23.       loaded: true 
  24.     }); 
  25.   } 
  26.  
  27.   render() { 
  28.     return ( 
  29.       <section className="ExternalDependedComponent__container"
  30.         {this.state.loaded 
  31.           ? <div style={{ color: "white" }}> 
  32.               <h1 style={{ position: "absolute" }}>Swiper</h1> 
  33.               <p style={{ position: "absolute"top"50px" }}> 
  34.                 Swiper 加载完毕,现在你可以在全局对象中使用 Swiper! 
  35.               </p> 
  36.               <img 
  37.                 height="504px" 
  38.                 width="320px" 
  39.                 src="http://img5.cache.netease.com/photo/0031/2014-09-20/A6K9J0G94UUJ0031.jpg" 
  40.                 alt="" 
  41.               /> 
  42.             </div> 
  43.           : <div> 
  44.               <Spin size="large" /> 
  45.             </div>} 
  46.       </section
  47.     ); 
  48.   } 

代理

有时候我们需要动态设置以代理方式执行请求,这里即动态地为 RequestBuilder 生成的请求配置添加 agent 属性即可:

  1. const HttpsProxyAgent = require("https-proxy-agent"); 
  2.  
  3. const requestBuilder = new RequestBuilder({ 
  4. scheme: "http"
  5. host: "jsonplaceholder.typicode.com" 
  6. }); 
  7.  
  8. const { url: getUrl, option: getOption } = requestBuilder 
  9. .get("/posts"
  10. .pathSegment("1"
  11. .build(); 
  12.  
  13. getOption.agent = new HttpsProxyAgent("http://114.232.81.95:35293"); 
  14.  
  15. let post = await execute(getUrl, getOption,"text"); 

扩展策略

中断与超时

execute 函数在执行基础的请求之外还回为 fetch 返回的 Promise 添加中断与超时地功能,需要注意的是如果以 Async/Await 方式编写异步代码则需要将 timeout 超时参数以函数参数方式传入;否则可以以属性方式设置:

  1. describe("策略测试", () => { 
  2.   test("测试中断", done => { 
  3.     let fnResolve = jest.fn(); 
  4.     let fnReject = jest.fn(); 
  5.  
  6.     let promise = execute("https://jsonplaceholder.typicode.com"); 
  7.  
  8.     promise.then(fnResolve, fnReject); 
  9.  
  10.     // 撤销该请求 
  11.     promise.abort(); 
  12.  
  13.     // 异步验证 
  14.     setTimeout(() => { 
  15.       // fn 不应该被调用 
  16.       expect(fnResolve).not.toHaveBeenCalled(); 
  17.       expect(fnReject).toHaveBeenCalled(); 
  18.       done(); 
  19.     }, 500); 
  20.   }); 
  21.  
  22.   test("测试超时", done => { 
  23.     let fnResolve = jest.fn(); 
  24.     let fnReject = jest.fn(); 
  25.  
  26.     let promise = execute("https://jsonplaceholder.typicode.com"); 
  27.  
  28.     promise.then(fnResolve, fnReject); 
  29.  
  30.     // 设置超时 
  31.     promise.timeout = 10; 
  32.  
  33.     // 异步验证 
  34.     setTimeout(() => { 
  35.       // fn 不应该被调用 
  36.       expect(fnResolve).not.toHaveBeenCalled(); 
  37.       expect(fnReject).toHaveBeenCalled(); 
  38.       done(); 
  39.     }, 500); 
  40.   }); 
  41.  
  42.   test("使用 await 下测试超时", async done => { 
  43.     try { 
  44.       await execute("https://jsonplaceholder.typicode.com", {}, "json", { 
  45.         timeout: 10 
  46.       }); 
  47.     } catch (e) { 
  48.       expectChai(e.message).to.equal("Abort or Timeout"); 
  49.     } finally { 
  50.       done(); 
  51.     } 
  52.   }); 
  53. }); 

进度反馈

  1. function consume(reader) { 
  2.   let total = 0; 
  3.   return new Promise((resolve, reject) => { 
  4.     function pump() { 
  5.       reader.read().then(({done, value}) => { 
  6.         if (done) { 
  7.           resolve(); 
  8.           return 
  9.         } 
  10.         total += value.byteLength; 
  11.         log(`received ${value.byteLength} bytes (${total} bytes in total)`); 
  12.         pump() 
  13.       }).catch(reject) 
  14.     } 
  15.     pump() 
  16.   }) 
  17.  
  18. // 执行数据抓取操作 
  19. fetch("/music/pk/altes-kamuffel.flac"
  20.   .then(res => consume(res.body.getReader())) 
  21.   .then(() => log("consumed the entire body without keeping the whole thing in memory!")) 
  22.   .catch(e => log("something went wrong: " + e)) 

Pipe

execute 还支持动态地将抓取到的数据传入到其他处理管道中,譬如在 Node.js 中完成图片抓取之后可以将其保存到文件系统中;如果是浏览器环境下则需要动态传入某个 img 标签的 ID,execute 会在图片抓取完毕后动态地设置图片内容:

  1. describe("Pipe 测试", () => { 
  2.   test("测试图片下载", async () => { 
  3.     let promise = execute
  4.       "https://assets-cdn.github.com/images/modules/logos_page/Octocat.png"
  5.       {}, 
  6.       "blob" 
  7.     ).pipe("/tmp/Octocat.png", require("fs")); 
  8.   }); 
  9. }); 

 【本文是51CTO专栏作者“张梓雄 ”的原创文章,如需转载请通过51CTO与作者联系】

戳这里,看该作者更多好文

责任编辑:武晓燕 来源: 51CTO专栏
相关推荐

2022-05-18 08:00:00

JavaScriptFetch数据

2022-12-09 15:02:44

2022-02-15 08:51:21

AjaxFetchAxios

2020-06-10 08:37:21

JavaScript重构技巧

2011-06-03 13:48:18

JavaScript重构

2020-06-17 16:38:22

Rust业务架构

2023-08-10 10:58:24

2020-06-09 09:13:12

JavaScript重构对象

2020-11-26 06:50:40

APII请求Fetch API

2024-03-19 08:36:19

2020-06-30 08:23:00

JavaScript开发技术

2018-08-28 07:02:26

网络重构SDNNFV

2021-05-26 08:50:37

JavaScript代码重构函数

2011-06-09 15:27:01

JavaScript

2022-04-21 07:20:39

Javascript重构逻辑

2020-06-08 08:46:59

JavaScript条件类名

2020-05-27 09:30:52

JavaScript重构函数

2020-06-01 08:42:11

JavaScript重构函数

2021-06-08 10:10:25

SQLMyBatisFluent MyBa

2010-06-04 14:10:09

MySQL_fetch
点赞
收藏

51CTO技术栈公众号