69 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			69 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
| import http from "./request"
 | |
| 
 | |
| /**
 | |
|  * 观察者工具对象,用于前端接口监测
 | |
|  */
 | |
| 
 | |
| class Observer {
 | |
|   constructor() {
 | |
|     this.initXHRObserver()
 | |
|   }
 | |
| 
 | |
|   static saveLog(item = {}) {
 | |
|     const api = {
 | |
|       method: item.method,
 | |
|       path: item.url,
 | |
|       url: location.href,
 | |
|       nodeProcess: process.env.NODE_ENV,
 | |
|       status: item.response?.code || item.status,
 | |
|       code: item.response?.code,
 | |
|       error: item.response?.code != 0 ? item.response?.data : null,
 | |
|       device: navigator.userAgent
 | |
|     }
 | |
|     if (!/(sockjs-node|hot-update|monitorApi|frontjs|apiForward)/.test(api.path)) {
 | |
|       if (!!this.timer) {
 | |
|         clearTimeout(this.timer)
 | |
|       }
 | |
|       this.pending = [this.pending, api].flat().filter(Boolean)
 | |
|       this.timer = setTimeout(() => {
 | |
|         http.post("/admin/apiForward", this.pending, {
 | |
|           withoutToken: true,
 | |
|           params: {url: "http://dvcp.cunwuyun.cn/ns/node/monitorApi/addOrUpdate"}
 | |
|         }).then(res => {
 | |
|           if (res?.code == 0) {
 | |
|             this.pending = []
 | |
|           }
 | |
|         })
 | |
|       }, 30000)
 | |
|     }
 | |
|   }
 | |
| 
 | |
|   initXHRObserver() {
 | |
|     const origin = XMLHttpRequest.prototype.open;
 | |
|     XMLHttpRequest.prototype.open = function (...args) {
 | |
|       let send = this.send;
 | |
|       let _this = this
 | |
|       let post_data = []
 | |
|       this.send = function (...data) {
 | |
|         post_data = data;
 | |
|         return send.apply(_this, data)
 | |
|       }
 | |
|       this.addEventListener("readystatechange", function () {
 | |
|         if (this.readyState === 4) {
 | |
|           // 请求后拦截
 | |
|           Observer.saveLog({
 | |
|             url: args[1],
 | |
|             status: this.status,
 | |
|             method: args[0],
 | |
|             data: post_data,
 | |
|             response: JSON.parse(this.response || null)
 | |
|           })
 | |
|         }
 | |
|       }, false)
 | |
|       return origin.apply(this, args)
 | |
|     }
 | |
|   }
 | |
| }
 | |
| 
 | |
| export default Observer
 |