weikee94 / design-patterns

Design Patterns
0 stars 0 forks source link

Proxy Pattern #4

Open weikee94 opened 11 months ago

weikee94 commented 11 months ago
class RealImg {
  constructor(fileName) {
    this.fileName = fileName;
    this.loadFromDisk();
  }
  loadFromDisk() {
    console.log("...loading " + this.fileName);
  }
  display() {
    console.log("...finished " + this.fileName);
  }
}

class ProxyImg {
  constructor(fileName) {
    this.realImg = new RealImg(fileName);
  }
  display() {
    this.realImg.display();
  }
}

let proxImg = new ProxyImg("1.png");
console.log(proxImg.display());

// 例子演示
$("#div1").click(function () {
  // this 符合期望
  $(this).addClass("red");
});

$("#div1").click(function () {
  // this 不符合期望
  setTimeout(function () {
    $(this).addClass("red");
  }, 1000);
});

// 可以用以下方式解决
$("#div1").click(function () {
  var _this = this;
  setTimeout(function () {
    $(_this).addClass("red");
  }, 1000);
});

// proxy 解决方法
$("#div1").click(function () {
  var fn = function () {
    $(this).css("background-color", "yellow");
  };
  fn = $.proxy(fn, this);
  setTimeout(fn, 1000);
});

// ES6 Proxy Example

let star = {
  name: "xxx",
  age: 20,
  phone: "1234",
};

// agent
let agent = new Proxy(star, {
  get: function (target, key) {
    if (key === "phone") {
      // this should be agent phone
      // cuz we cannot give star phone
      // by using proxy we provide agent phone instead star phone
      return "5678";
    }
    if (key === "price") {
      // agent call out price
      return 1200;
    }
    return target[key];
  },
});

console.log(agent.name);
console.log(agent.phone);
weikee94 commented 11 months ago

场景

代理模式在前端很常用

DOM 事件代理

<div id="div1">
    <a href="#">a1</a>
    <a href="#">a2</a>
    <a href="#">a3</a>
    <a href="#">a4</a>
</div>
<button>点击增加一个 a 标签</button>

<script>
    var div1 = document.getElementById('div1')
    div1.addEventListener('click', function (e) {
        var target = e.target
        if (e.nodeName === 'A') {
            alert(target.innerHTML)
        }
    })
</script>

webpack devServer

第一,配置 webpack ,参考 https://webpack.docschina.org/configuration/dev-server/#devserverproxy

// webpack.config.js
module.exports = {
  // 其他配置...
  devServer: {
    proxy: {
      '/api': 'http://localhost:8081',
    },
  },
};

第二,启动 nodejs 服务,监听 8081 端口

第三,借用 axios 发送请求

import axios from 'axios'

document.getElementById('btn1')?.addEventListener('click', () => {
    axios.get('/api/info')
        .then(res => {
            console.log(res)
        })
})

nginx 反向代理

nginx 配置文件可参考 https://www.runoob.com/w3cnote/nginx-setup-intro.html

server {
    listen   8000;
    location / {
        proxy_pass http://localhost:8001;
    }
    location /api/ {
        proxy_pass http://localhost:8002;
        proxy_set_header Host $host;
    }
}

反向代理 vs 正向代理

(视频里画图解释)

Proxy

Vue3 就使用 Proxy 做 data 响应式

// 明星
const star = {
    name: '张三',
    age: 25,
    phone: '18611112222',
    price: 0 // 艺术物价,明星不谈钱
}

// 经纪人
const agent = new Proxy(star, {
    get(target, key) {
        if (key === 'phone') {
            return '13900001111' // 返回经纪人的的电话
        }
        if (key === 'price') {
            return 100 * 1000  // 报价
        }
        return Reflect.get(target, key) // 返回原来的属性值
    },
    set(target, key, val): boolean {
        if (key === 'price') {
            if (val < 100 * 1000) {
                throw new Error('价格太低了...')
            } else {
                console.log('报价成功,合作愉快!', val)
                return Reflect.set(target, key, val)
            }
        }
        // 其他属性不可设置
        return false
    }
})

// 主办方
console.log(agent.name)
console.log(agent.age)
console.log(agent.phone)
console.log(agent.price)
// agent.price = 90000 // 价格低了会报错

总结

weikee94 commented 11 months ago
import { isValidEmail, isAllLetters } from './validator.js';

const user = {
  firstName: 'John',
  lastName: 'Doe',
  username: 'johndoe',
  age: 42,
  email: 'john@doe.com',
};

const userProxy = new Proxy(user, {
  get: (obj, prop) => {
    return `${new Date()} | The value of ${prop} is ${Reflect.get(obj, prop)}`;
  },
  set: (obj, prop, value) => {
    if (prop === 'email') {
      if (!isValidEmail(value)) {
        console.log('Please provide a valid email.');
        return false;
      }
    }

    if (prop === 'username') {
      if (value.length < 3) {
        throw new Error('Please use a longer username.');
      } else if (!isAllLetters(value)) {
        throw new Error('You can only use letters');
      }
    }

    if (prop === 'age') {
      if (typeof value !== 'number') {
        throw new Error('Please provide a valid age.');
      }

      if (value < 18) {
        throw 'User cannot be younger than 18.';
      }
    }

    return Reflect.set(obj, prop, value);
  },
});

stackblitz