Use decorator mode to strengthen your fetch

Official account Front end Shura 2021-05-03 13:21:27
use decorator mode strengthen fetch


 Search box propagation style - White version .png

1. fetch() very good , But you may want to be better

fetch() API Allow you to be in web Executing network requests in an application .

fetch() It's very simple : call fetch ('/movies.json') To start the request . When the request is complete , You will get a Response object , Extract data from .

Here is a simple example , How to go from movies.json URL obtain JSON Format data :

async function executeRequest() {
const response = await fetch('/movies.json');
const moviesJson = await response.json();
console.log(moviesJson);
}
executeRequest();
// logs [{ name: 'Heat' }, { name: 'Alien' }]
 Copy code 

This is shown in the code snippet above , You have to manually extract... From the response JSON object :moviesJson = await response.JSON(). Only once , That's all right. . But if your application performs many requests , So use await response.json() extract JSON All the time of the object is very cumbersome .

therefore , Third party libraries are often used , such as axios, It can greatly simplify the processing of requests . Consider using axios Get the same movie :

async function executeRequest() {
const moviesJson = await axios('/movies.json');
console.log(moviesJson);
}
executeRequest();
// logs [{ name: 'Heat' }, { name: 'Alien' }]
 Copy code 

moviesJson = await axios('/movies.json') Return to the actual JSON Respond to . It doesn't have to be like fetch() As requested Manual extraction JSON.

however , Use something like axios This kind of auxiliary library also brings some problems

First , It increases the web Application's bundle size . secondly , Combine your application with third-party libraries : You get all the benefits of the library , But also got all of it bug.

My aim is to take a different approach , The best results have been obtained from both aspects —— Use decorator mode to add fetch() API Ease of use and flexibility .

The idea is to put a The base fetch class ( I'm going to show you how to define it ) Packaging for any other features you need : extract JSON、 Overtime 、 In the bad HTTP Throw an error in state 、 Handle auth head , wait . Let's see how to do that in the next section .

2. Get ready Fetcher Interface

Decorator mode is very useful , Because it supports adding functionality to basic logic in a flexible and loosely coupled way ( let me put it another way —— decorate ).

If you're not familiar with decorative patterns , I suggest you read about how it works .

Apply decorators to enhance fetch() It takes a few simple steps :

  • First step It's a statement called Fetcher The abstract interface of :
type ResponseWithData = Response & { data?: any };
interface Fetcher {
run(
input: RequestInfo,
init?: RequestInit
): Promise<ResponseWithData>;
}
 Copy code 

Fetcher The interface has only one method , It takes the same parameters and returns the same as normal fetch() Same data type .

  • The second step It's about achieving basic fetcher class :
class BasicFetcher implements Fetcher {
run(
input: RequestInfo,
init?: RequestInit
): Promise<ResponseWithData> {
return fetch(input, init);
}
}
 Copy code 

BasicFetcher Realized Fetcher Interface . One way of it run() Call regular fetch() function .

for example , Let's use the basic fetcher Class to get the movie list :

const fetcher = new BasicFetcher();
const decoratedFetch = fetcher.run.bind(fetcher);
async function executeRequest() {
const response = await decoratedFetch('/movies.json');
const moviesJson = await response.json();
console.log(moviesJson);
}
executeRequest();
// logs [{ name: 'Heat' }, { name: 'Alien' }]
 Copy code 

const fetcher = new BasicFetcher() Create a fetcher Class .decoratedFetch = fetcher.run.bind(fetcher) Create a binding method .

Then you can use decoratedFetch('/movies.JSON ') To get the movie JSON, It's like using regular fetch() equally .

In this step ,BasicFetcher Class doesn't benefit . Besides , Because of new interfaces and new classes , Things get more complicated ! Wait a moment , You'll find the huge benefits when decorator mode is introduced into action .

3. To extract JSON Data method, add decorator

Adorner pattern is mainly adorner class .

Decorator class must conform to Fetcher Interface , Examples of packaging being decorated , as well as stay run() Method .

Let's implement an extraction from the response object JSON The decorator of data :

class JsonFetcherDecorator implements Fetcher {
private decoratee: Fetcher;
constructor (decoratee: Fetcher) {
this.decoratee = decoratee;
}
async run(
input: RequestInfo,
init?: RequestInit
): Promise<ResponseWithData> {
const response = await this.decoratee.run(input, init);
const json = await response.json();
response.data = json;
return response;
}
}
 Copy code 

Let's take a closer look JsonFetcherDecorator How is it constructed .

JsonFetcherDecorator accord with Fetcher Interface .

JsonExtractorFetch There is a private field decoratee, It's also in line with the law Fetcher Interface . stay run() In the method this.decoratee.run(input, init) Perform the actual data acquisition .

then json = await response.json() Extract... From the response json data . Last , Respond to .data = json What will be extracted json Data is assigned to the response object .

Now let's use JsonFetcherDecorator Adorner to combine decoration BasicFetcher, And simplify fetch() Use :

const fetcher = new JsonFetcherDecorator(
new BasicFetcher()
);
const decoratedFetch = fetcher.run.bind(fetcher);
async function executeRequest() {
const { data } = await decoratedFetch('/movies.json');
console.log(data);
}
executeRequest();
// logs [{ name: 'Heat' }, { name: 'Alien' }]
 Copy code 

Now? , You can select from the response object's data Property to access the extracted data , Instead of manually extracting from the response JSON data .

adopt take JSON The extractor moves to the decorator , Now in any use const {data} = decoratedFetch(URL) The place of , You don't have to extract it manually JSON object .

4. Create request timeout decorator

By default ,fetch() API It will time out at the time specified by the browser . stay Chrome in , The network request timeout is 300 second , And in the Firefox The timeout in is 90 second .

Users can wait 8 Seconds to complete a simple request . That's why you need to set a timeout for network requests , And in 8 Inform the user of the cause of the network problem in seconds .

The great thing about the decorator model is , have access to Any number of ornaments Come on Decorate your basic realization ! that , Let's create a time-out decorator for the retrieval request :

const TIMEOUT = 8000; // 8 seconds
class TimeoutFetcherDecorator implements Fetcher {
private decoratee: Fetcher;
constructor(decoratee: Fetcher) {
this.decoratee = decoratee;
}
async run(
input: RequestInfo,
init?: RequestInit
): Promise<ResponseWithData> {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), TIMEOUT);
const response = await this.decoratee.run(input, {
...init,
signal: controller.signal
});
clearTimeout(id);
return response;
}
}
 Copy code 

TimeoutFetcherDecorator Is an implementation Fetcher Interface decorator.

stay TimeoutFetcherDecorator Of run() Methods the internal : If the request is in 8 Not finished in seconds , The abort controller is used to abort the request .

Now let's use this decorator :

const fetcher = new TimeoutFetcherDecorator(
new JsonFetcherDecorator(
new BasicFetcher()
)
);
const decoratedFetch = fetcher.run.bind(fetcher);
async function executeRequest() {
try {
const { data } = await decoratedFetch('/movies.json');
console.log(data);
} catch (error) {
// Timeouts if the request takes
// longer than 8 seconds
console.log(error.name);
}
}
executeRequest();
// if the request takes more than 8 seconds
// logs "AbortError"
 Copy code 

In this example , Yes /movies.json Your request needs to exceed 8 second .

decoratedFetch('/movies.json'), because TimeoutFetcherDecorator, Throw timeout error .

Now the basic getter is encapsulated in 2 In a decorator : An extraction JSON object , The other is 8 Seconds timeout request . This greatly simplifies decoratedFetch() Use : When calling decoratedFetch() when ,decorator Logic will work for you .

5. summary

fetch() API It provides the basic function of executing get request . But you need more than that . Use alone fetch() Force you to manually extract from the request JSON data , Configuration timeout , wait .

for fear of Model file , You can use a more friendly Library , Such as axios. However , Use something like axios Such a third-party library will increase the size of the application package , At the same time, you will be closely associated with it .

Another solution is to fetch() Above apply decorator mode . You can create and extract... From the request JSON、 Decorators for timeout requests and so on . You can combine at any time 、 Add or remove decorators , Without affecting the code that uses the decorator .

版权声明
本文为[Official account Front end Shura]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503131222027b.html

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless