Skip to content

Instantly share code, notes, and snippets.

@DavidTheProgrammer
Created November 22, 2018 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidTheProgrammer/1c8c7bfa86c9b9eb979f8c5d9ab186ee to your computer and use it in GitHub Desktop.
Save DavidTheProgrammer/1c8c7bfa86c9b9eb979f8c5d9ab186ee to your computer and use it in GitHub Desktop.
// Import Lodash library
const _ = require('lodash');
// Original perissions object
const _permissions = {
homeAppliances: {
read: true,
write: true,
delete: true
},
haberdashery: {
read: true,
write: true,
delete: false
},
// ... And so on
}
// The proxy
const permissions = new Proxy(_permissions, {
get: function (target, prop, receiver) {
// More ES2015 goodness. Destructuring assignment
const [can, perm, ...categoryArr] = prop.split('_');
const category = categoryArr.join('_');
// We'll get some help from the lodash library here
const categoryCamelCase = _.camelCase(category);
const permissionCategory = target[categoryCamelCase];
// Check if it exists. Throw error if it doesn't
if (permissionCategory) {
const permLowercase = perm.toLowerCase();
// If permission is allowed.
if (permissionCategory[permLowercase]) {
// e.g 'CAN READ HOME_APPLIANCES'
const permissionString = [can, perm, category].join(' ').toUpperCase();
return permissionString;
} else {
throw new Error(`Permission Error: '${perm}' is not allowed on category '${category}'`);
}
} else {
throw new Error(`Permission Error: '${category}' does not exist on permission object`);
}
}
});
console.log(permissions.CAN_READ_HOME_APPLIANCES);
// CAN READ HOME_APPLIANCES
console.log(permissions['CAN_WRITE_HABERDASHERY']);
// CAN WRITE HABERDASHERY
console.log(permissions['CAN_DELETE_HABERDASHERY']);
// Permission Error: 'DELETE' is not allowed on category 'HABERDASHERY'
console.log(permissions.CAN_READ_ELECTRONICS);
// Permission Error: 'ELECTRONICS' does not exist on permission object
console.log(permissions['CAN_ADD_HOME_APPLIANCES']);
// Permission Error: The permission 'ADD' is not allowed on 'HOME_APPLIANCES'
@OlivierJM
Copy link

Good stuff, line 4 I think you meant permission in the comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment