Created
December 11, 2016 17:57
-
-
Save brianhyder/f011cdea8a6cce1128ba6ff86e9a10a1 to your computer and use it in GitHub Desktop.
PencilBlue Router Framework & Request Pipeline
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
/** | |
* An example of adding middleware. | |
* It injects code into the request pipeline that adds a header to allows resources from the server to be accessed by other domains. | |
*/ | |
class CorsPlugin { | |
static onStartupWithContext (context, cb) { | |
var middlewareName = 'addCorsHeader'; | |
var middleware = { | |
name: middlewareName, | |
action: MinifyPlugin.addCorsHeader | |
}; | |
var result = pb.Router.addMiddlewareBefore('checkPublicRoute', middleware); | |
cb(!result ? new Error('Failed to add middleware') : null); | |
} | |
static addCorsHeader (req, res, next) { | |
res.setHeader('Access-Control-Allow-Origin', '*'); | |
} | |
} |
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
/** | |
* An example of replacing middleware. | |
* It injects code into the request pipeline that will minify JS before being written to the response stream | |
*/ | |
class MinifyPlugin { | |
static onStartupWithContext (context, cb) { | |
var middlewareName = 'writeResponse'; | |
var middleware = { | |
name: middlewareName, | |
action: MinifyPlugin.writeResponseWithMinification | |
}; | |
var result = pb.Router.replaceMiddleware(middlewareName, middleware); | |
cb(!result ? new Error('Failed to override middleware') : null); | |
} | |
static writeResponseWithMinification (req, res, next) { | |
var data = req.controllerResult; | |
if (data.content_type === 'text/javascript' && !!data.content) { | |
data.content = UglifyJS.minify(data.content, {fromString: true}); | |
} | |
pb.Middleware.writeResponse(req, res, next); | |
} | |
} |
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
/** | |
* An example of removing middleware. | |
* It removes the middleware that writes the request result to the console | |
*/ | |
class PerformancePlugin { | |
static onStartupWithContext (context, cb) { | |
var middlewareName = 'responseTime'; | |
var result = pb.Router.removeMiddleware(middlewareName); | |
cb(!result ? new Error('Failed to remove middleware') : null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment