preface
Delivery Address:
Front end design pattern factory pattern
Proxy patterns for front-end design patterns
The strategy pattern of the front-end design pattern
The design mode has been serialized to phase 3. Since the observer mode of the next phase will be postponed for a period of time together with the team’s buried point performance blog, this chapter is an Easter egg and an out-of-the-box FETCH project practice is launched.
Encapsulating fetch step
Package Base FETCH
Unencapsulated fecth is used as follows
fetch('https://www.baidu.com/search/error.html') // Return a Promise object.then((res) => {
returnRes.text () // res.text() is a Promise object})
.then((res) => {
Console. log(res) // res is the final result}) Copy the code
The fecth method is used directly, but there are a lot of inconvenience in referencing it directly in a project, so let’s encapsulate it briefly, such as cross-domain configuration, timeouts, various requests, etc.
import qs from 'qs'
class Fetch {
constructor(config = {}) {
this.config = {
cache: 'no-cache', // * default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, same-origin, *omit headers: {}, mode: 'cors', // no-cors, cors, *same-origin redirect: 'follow', // manual, *follow, error referrer: 'no-referrer', // *client, no-referrer timeOut: 3000, BASE_URL: ' '.. config } } send({ url, params, method = "GET", headers }) { // Send an Ajax request const { BASE_URL } = this.config const ajax = new Promise((resolve) => { fetch(BASE_URL ? `${BASE_URL}/${url}` : url, { . this.config, body: params, headers, method, }).then((response) => { return response.json() }).then((data) => { resolve(data) }) }) // Set the timeout period const time = new Promise((reject) => { console.log(this.config.timeOut) setTimeout(() => { reject('time out') }, this.config.timeOut); }) return Promise.race([ajax, time]) } // Encapsulate the request get({ url, query, headers }) { return this.send({ url: `${url}?${qs.stringify(query)}`, headers, method: 'GET' }) } post({ url, params, headers }) { return this.send({ url, params, headers, method: 'POST' }) } } const newFetch = new Fetch(); newFetch.get({ url: 'https://api.github.com/users/octocat'. params: { test: 1. } }).then(data => { console.log(data) }).catch(err => { console.log(err) }) Copy the code
As mentioned above, we simply encapsulated a fetch class that can send GET and POST requests, and added timeout and gateway. Simple projects can be used at will. However, since we want to do it out of the box, we will further customize according to the actual situation of the project.
Encapsulate the request parameter type
this.dataOperation = {
JSON: {
headers: {
'Content-Type': 'application/json'// Tell the server that the submitted data type is JSON },
formatting(params) { return JSON.stringify(params) } }, FormData: { headers: { 'Content-Type': 'application/x-www-form-urlencoded'// Tell the server that we are submitting data in FormData format }, formatting(params) { let _formData = new FormData(); Object.keys(params).forEach(key => { _formData.append(key, params[key]); }) return _formData } } } preSend({ url, params, headers, method }) { const { requestType } = this.config const FetchConfig = { . this.FetchConfig, method, headers: { . this.dataOperation[requestType].headers,. headers }, }; if(!!!!! params) FetchConfig.body = this.dataOperation[requestType].formatting(params); return this.send({ url, FetchConfig }) } post({ url, query, params = {}, headers }) { return this.preSend({ url: query ? `${url}?${qs.stringify(query)}` : url, params, headers, method: 'POST' }) } Copy the code
As above, we according to the strategy mode + agent will send a request to pack a layer, so that we can at the time of initialization, select the project request parameter type, generally a project does not use a variety of request type, so we temporarily does not provide request parameter type of method and configuration, simplify the number of parameters in our request method.
Add Get request cache configuration
Generally speaking, normal GET requests can be configured with 304 cache, etc. However, in terms of network communication request quality and reduction of request quantity, when the data data is too large or the number of requests is too large, the performance improvement of reading data directly from the local will be more effective. So we can wrap the caching examples from the proxy pattern with get requests and use them together
Get ({url, query, headers}) {// Optimize the GET request and add cache processing const key = query ? `${url}?${qs.stringify(query)}` : url
if (this.cacheStorage) {
if (this.cacheStorage.getItem(key)) {
return Promise.resolve(this.cacheStorage.getItem(key))
} else { return this.preSend({ url: key, headers, method: 'GET' }).then(data => { this.cacheStorage.setItem(key, data) return data }) } } else { return this.preSend({ url: key, headers, method: 'GET' }) } } Copy the code
As for the cache encapsulation, the cache type and cache time have been initialized together with the initialization of the tool class, which is more convenient for the subsequent business side to use. If all the parameters are included, the flexibility will be improved, but the cost of using the method will be increased.
Service request usage
Summarize the use of business side according to previous project experience:
- The request method is directly packaged with a layer method according to the service type, and then directly invoked on the required service side. In this way, the returned data of a certain type of request is processed in a unified manner, and the data is separated from the view, which facilitates expansion
- Write the request method in vuex, Redux state management, and then call the actual business side, you can achieve data sharing across components, page sharing
- Overall, if the request business does not involve cross-component or cross-page invocation, the business request can be directly written in the current code, which is more comfortable to maintain
The end of the
Complete demo address: project actual combat demo, like friends can star, the follow-up will be based on the launch of the design mode blog, and gradually expand the project.
Manual doghead town building
This article is formatted using MDNICE