Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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();
Add Comment
Please, Sign In to add comment