Skip to content

Instantly share code, notes, and snippets.

@florianherrengt
Created April 4, 2016 09:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save florianherrengt/95ec3ddda052a3b4a2775dfba97263ec to your computer and use it in GitHub Desktop.
Save florianherrengt/95ec3ddda052a3b4a2775dfba97263ec to your computer and use it in GitHub Desktop.
Lambda Reproduce middleware with decorators
{
"presets": ["es2015", "stage-0"],
"plugins": ["transform-decorators-legacy"]
}
import { decorate } from 'core-decorators';
function checkJwt(target) {
return (event, context) => {
const { body: { jwt } } = event;
if (!jwt) { return context.done('400: missing jwt'); } // if can't find the jwt return an error and don't call the next function
// ... add logic to verify the token here ...
// add the userId from the token to the data
Object.assign(event.body, {
authentificatedUser: 'the authentificated user entity'
});
return target(event, context); // call the next function
};
}
function validateUsername(target) {
return (event, context) => {
setTimeout(() => {
const { body: { username } } = event;
// do some kind of validation
if (typeof username !== 'string') { return context.done('400 username must be a string'); }
target(event, context);
}, 1000);
};
}
class GetUser {
constructor() {
this.handler = this.handler.bind(this);
}
@decorate(checkJwt) // same as a middleware to check the jwt on the body
@decorate(validateUsername)
handler(event, context) {
context.done(null, event);
}
}
class LambdaContext {
done(error, success) {
if (error) { return console.log('Error:', error); }
console.log(success);
}
}
const getUser = new GetUser();
[ { jwt: 'abc123', username: 'abc' }, { jwt: 'abc123', username: 123 }, { random: 'hello' } ].forEach(body => {
getUser.handler({ body }, new LambdaContext() );
});
// Returns
// 1: { body: { jwt: 'abc123', username: 'abc', authentificatedUser: 'the authentificated user entity' } }
// 2: Error: 400 username must be a string
// 3: Error: 400: missing jwt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment