Skip to content

Instantly share code, notes, and snippets.

@rxluz
Last active January 18, 2019 02:38
Show Gist options
  • Save rxluz/887dca96fbbec34e6d50308ccfd27ff4 to your computer and use it in GitHub Desktop.
Save rxluz/887dca96fbbec34e6d50308ccfd27ff4 to your computer and use it in GitHub Desktop.
JS Design Patterns: Proxy, see more at: https://medium.com/p/b8f962affe02
class Products {
constructor(User) {
if (typeof User !== "object") {
throw new Error("User object is required to initialize products class");
return false;
}
this.currentUser = User;
this.data = [];
}
checkPrivilege(permision) {
const userHasThisPermission = this.currentUser.permissions.some(
currentPermission => permision === currentPermission,
);
return userHasThisPermission;
}
add(product) {
if (this.checkPrivilege("product_add")) {
this.data.push(product);
return true;
}
return false;
}
remove(product) {
if (this.checkPrivilege("product_remove")) {
this.data = this.data.filter(
currentProduct => product !== currentProduct,
);
return true;
}
return false;
}
reports() {
if (this.checkPrivilege("product_reports")) {
return `Products reports`;
}
return false;
}
}
class User {
constructor(name, permissions) {
this.name = name;
this.permissions = permissions;
}
}
const run = () => {
const productInstanceWithUser1 = new Products(
new User("Ricardo", ["product_reports"]),
);
console.log(
`User without access to add method tries add new product `,
productInstanceWithUser1.add("New product"),
);
console.log(
`User without access to add method tries remove product `,
productInstanceWithUser1.remove("New product"),
);
console.log(
`User with access to report method tries generates a report `,
productInstanceWithUser1.reports(),
);
};
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment