Created
November 15, 2017 19:08
-
-
Save rafaelcorreiapoli/4c85ecd4a216cd3f26cd5038326ee0d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { compose } from 'redux' | |
const ensureLoggedIn = (next) => (obj, args, ctx) => { | |
if (!ctx.user) { | |
throw new Error('Not authorized') | |
} | |
return next(obj, args, ctx) | |
} | |
const intersection = (array1, array2) => array1.filter((n) => array2.includes(n)) | |
const ensureScopes = scopes => next => (obj, args, ctx) => { | |
if (!intersection(scopes, ctx.user.scopes).length) { | |
throw new Error('Forbidden') | |
} | |
return next(obj, args, ctx) | |
} | |
const logArgs = (cb) => (obj, args, ctx) => { | |
console.log(args.arg1) | |
return cb(obj, args, ctx) | |
} | |
const resolver = (obj, args, ctx) => { | |
return obj.name | |
} | |
const enhancedResolver = compose( | |
ensureLoggedIn, | |
logArgs, | |
ensureScopes(['admin', 'subadmin']), | |
)(resolver) | |
const params1 = [{name: 'Rafael'},{arg1: 'Log me1'},{user:{scopes:['admin']}}] | |
const params2 = [{name: 'Rafael'}, {arg1: 'Log me2'}, {}] | |
const params3 = [{name: 'Rafael'}, {arg1: 'Log me3'}, {user: {scopes: ['noob']}}] | |
try { | |
console.log('Test 1 - should print Log me1 and Rafael') | |
console.log(enhancedResolver(...params1)) | |
} | |
catch (err) { | |
console.log(err.message) | |
} | |
console.log('------------------------') | |
try { | |
console.log('Test 2 - should throw Not authorized') | |
console.log(enhancedResolver(...params2)) | |
} | |
catch (err) { | |
console.log(err.message) | |
} | |
console.log('------------------------') | |
try { | |
console.log('Test 3 - should print Log me3 and throw Forbidden') | |
console.log(enhancedResolver(...params3)) | |
} | |
catch (err) { | |
console.log(err.message) | |
} | |
console.log('------------------------') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment