Skip to content

Instantly share code, notes, and snippets.

@brianhyder
Created December 11, 2016 17:57
Show Gist options
  • Save brianhyder/f011cdea8a6cce1128ba6ff86e9a10a1 to your computer and use it in GitHub Desktop.
Save brianhyder/f011cdea8a6cce1128ba6ff86e9a10a1 to your computer and use it in GitHub Desktop.
PencilBlue Router Framework & Request Pipeline
/**
* 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', '*');
}
}
/**
* 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);
}
}
/**
* 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