Skip to content

Instantly share code, notes, and snippets.

@rxluz
Last active January 18, 2019 02:37
Show Gist options
  • Save rxluz/f2cd5f35db91cc2ad3bd84b42e1bbf38 to your computer and use it in GitHub Desktop.
Save rxluz/f2cd5f35db91cc2ad3bd84b42e1bbf38 to your computer and use it in GitHub Desktop.
JS Design Patterns: Proxy, see more at: https://medium.com/p/b8f962affe02
class Products {
constructor() {
this.data = [];
}
add(product) {
this.data.push(product);
return true;
}
remove(product) {
this.data = this.data.filter(currentProduct => product !== currentProduct);
return true;
}
reports() {
return `Products reports`;
}
}
class ProductsProxyHandler {
constructor(User) {
if (typeof User !== "object") {
throw new Error("User object is required to initialize products class");
return false;
}
this.user = User;
}
get(target, propKey, receiver) {
const ProductsProxyScope = this;
const targetValue = Reflect.get(target, propKey, receiver);
if (typeof targetValue === "function") {
return function(...args) {
return ProductsProxyScope.checkPermissions(
propKey,
targetValue.bind(this, args),
);
};
} else {
return targetValue;
}
}
checkPermissions(methodName, func) {
const userHasPermission = this.user.permissions.some(
permission => permission === methodName,
);
return userHasPermission ? func() : "Not allowed";
}
}
class ProductsFacade {
constructor(User) {
return new Proxy(new Products(), new ProductsProxyHandler(User));
}
}
class User {
constructor(name, permissions) {
this.name = name;
this.permissions = permissions;
}
}
const run = () => {
const userRicardo = new User("Ricardo", ["add"]);
const ProductInstance = new ProductsFacade(userRicardo);
console.log(ProductInstance.remove("something"));
};
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment