Guest User

Untitled

a guest
Jan 16th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. class Products {
  2. constructor() {
  3. this.data = [];
  4. }
  5.  
  6. add(product) {
  7. this.data.push(product);
  8. return true;
  9. }
  10.  
  11. remove(product) {
  12. this.data = this.data.filter(currentProduct => product !== currentProduct);
  13.  
  14. return true;
  15. }
  16.  
  17. reports() {
  18. return `Products reports`;
  19. }
  20. }
  21.  
  22. class ProductsProxyHandler {
  23. constructor(User) {
  24. if (typeof User !== "object") {
  25. throw new Error("User object is required to initialize products class");
  26. return false;
  27. }
  28.  
  29. this.user = User;
  30. }
  31.  
  32. get(target, propKey, receiver) {
  33. const ProductsProxyScope = this;
  34.  
  35. const targetValue = Reflect.get(target, propKey, receiver);
  36.  
  37. if (typeof targetValue === "function") {
  38. return function(...args) {
  39. return ProductsProxyScope.checkPermissions(
  40. propKey,
  41. targetValue.bind(this, args),
  42. );
  43. };
  44. } else {
  45. return targetValue;
  46. }
  47. }
  48.  
  49. checkPermissions(methodName, func) {
  50. const userHasPermission = this.user.permissions.some(
  51. permission => permission === methodName,
  52. );
  53.  
  54. return userHasPermission ? func() : "Not allowed";
  55. }
  56. }
  57.  
  58. class ProductsFacade {
  59. constructor(User) {
  60. return new Proxy(new Products(), new ProductsProxyHandler(User));
  61. }
  62. }
  63.  
  64. class User {
  65. constructor(name, permissions) {
  66. this.name = name;
  67. this.permissions = permissions;
  68. }
  69. }
  70.  
  71. const run = () => {
  72. const userRicardo = new User("Ricardo", ["add"]);
  73.  
  74. const ProductInstance = new ProductsFacade(userRicardo);
  75.  
  76. console.log(ProductInstance.remove("something"));
  77. };
  78.  
  79. run();
Add Comment
Please, Sign In to add comment