Skip to content

Instantly share code, notes, and snippets.

@d-levin
Last active May 20, 2017 12:55
Show Gist options
  • Save d-levin/18a75809ddd9b33366a3d28f6439c4ef to your computer and use it in GitHub Desktop.
Save d-levin/18a75809ddd9b33366a3d28f6439c4ef to your computer and use it in GitHub Desktop.
Simple permissions directive for Vue.js
const args = {
SOME: 'some',
EVERY: 'every'
}
const permissions = [
'create',
'view',
'update',
'delete'
]
function hasPermission (permission) {
return permissions.includes(permission)
}
function hasSomePermissions (permissions = []) {
return permissions.some(hasPermission)
}
function hasEveryPermission (permissions = []) {
return permissions.every(hasPermission)
}
function replaceElementWithComment (el, vnode) {
const comment = document.createComment(' ')
vnode.elm = comment
vnode.text = ' '
vnode.isComment = true
vnode.context = undefined
vnode.tag = undefined
if (el.parentNode) {
el.parentNode.replaceChild(comment, el)
}
}
function getPermissionsFunction (arg) {
switch (arg) {
case args.SOME:
return hasSomePermissions
case args.EVERY:
return hasEveryPermission
default:
return hasPermission
}
}
function validValue (arg, value) {
switch (arg) {
case args.SOME:
return Array.isArray(value)
case args.EVERY:
return Array.isArray(value)
case undefined:
return typeof value === 'string'
default:
return false
}
}
function validArg (arg) {
return arg === undefined || Object.keys(args).some(key => args[key] === arg)
}
function validate ({ arg, value }) {
if (!validArg(arg)) {
throw new TypeError(`[ ${arg} ] is not a valid argument`)
}
if (!validValue(arg, value)) {
throw new TypeError(`Value type [ ${typeof value} ] is not supported or does not match type expected by arg [ ${arg} ]`)
}
}
export default (el, binding, vnode) => {
validate(binding)
let { arg, value } = binding
let permission = getPermissionsFunction(arg)
if (!permission(value)) {
replaceElementWithComment(el, vnode)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment