Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///<reference path='./../lib/def/defLoader.d.ts'/>
- export module Controllers {
- /**
- *
- * First, the super method is called.
- * It calls a magic method such as __beforeIndex if the request was coming from an index method.
- * If it doesn't found the origin, it calls directly __beforeEach method.
- * If it does then the __beforeIndex will automatically call the __beforeEach in first place.
- * Once all the __before magic methods are called, the custom method from the child is executed.
- * The options object contains specific stuff that belongs to the controllers logic, I could have use the req but I prefer not.
- *
- * The public methods such as index/show/etc. are defined but send by default a 404 response if they are not override in the child class.
- * They exists just to bind by default all these methods without take care if they exists or not.
- */
- export class Controller {
- /**
- * Default theme to use by default.
- */
- private static _defaultTheme = 'ayolan';
- /**
- * Relative path to a layout from a view.
- */
- private static _layoutRelativePath = '../_layouts/';
- /**
- * Default layout to use by default.
- */
- private static _defaultLayout = 'default';
- /**
- * Exported methods. Must be override by the childs to add custom methods.
- */
- public static exportedMethods: any = [];
- /**
- * Theme used by the controller by default.
- * Could be override by the user theme.
- */
- public static theme: string = Controller._defaultTheme;
- /**
- * Theme used by the controller by default.
- * Could be override by the user theme.
- */
- public static layout: string = Controller._defaultLayout;
- /**
- * Exported methods by default.
- * These methods will be accessible from internet.
- */
- private static _defaultExportedMethods: any = [
- // Sails controller custom config.
- '_config',
- // Default predefined controller methods.
- 'index',
- 'show',
- 'new',
- 'create',
- 'edit',
- 'update',
- 'destroy'
- ];
- /**
- * Overrides for the settings in `config/controllers.js`
- * (specific to the controller where it's defined)
- */
- private static _config = {};
- /**
- * Name of the folder located in /views/ that will contains the back office views.
- */
- private static _backofficeFolderName = 'dasboard';
- /**
- **************************************************************************************************
- **************************************** Static methods ******************************************
- **************************************************************************************************
- */
- /**
- * Acts as a super workflow controller to automatically call events when it's possible.
- * Used to call magic methods before the targeted methods is called.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- * controller Controller Child controller class. (static)
- *
- */
- public static super(req, res, callback, options: any = {}){
- // Extract information from the child.
- options.controllerName = req.target.controller;
- options.methodName = req.target.action;
- // Check that the dedicated method has a __before magic method in the current controller.
- if((Controller._getCurrentController(options))['__before' + Controller._cleanMethodName(options.methodName)]){
- // Custom before method is available. Call it. Remove underscores by security. (Protected/private methods)
- (Controller._getCurrentController(options))['__before' + Controller._cleanMethodName(options.methodName)](req, res, callback, options);
- }else{
- // By default, always call the global magic method.
- (Controller._getCurrentController(options))['__beforeEach'](req, res, callback, options);
- }
- }
- /**
- * Methods which MUST BE OVERRIDE in ALL childs.
- * Returns an object that contains all exported methods for the targeted child.
- * @param child The child controller class. (not an instance)
- * @returns {*}
- */
- public static exports(child?: any): any{
- if(!child){
- throw 'The exports method must be override in all Controller childs: ' + __filename;
- }
- // Merge default array and custom array from child.
- var methods: any = Controller._defaultExportedMethods.concat(child['exportedMethods']);
- var exportedMethods: any = {};
- for(var i = 0; i < methods.length; i++){
- exportedMethods[methods[i]] = child[methods[i]];
- }
- return exportedMethods;
- }
- /**
- * Default view renderer, manages basic data and stuff to always bind into the views.
- * @param req Request.
- * @param res Response.
- * @param options Specific options to render the view.
- * @param view View to load. Use the path controller/method by default.
- */
- public static renderView(req, res, options: any = {}, view: any = false){
- // Bind default data.
- options.date = new Date().getTime();
- options.currentUser = options.currentUser || req.session.user;
- options.translations = options.translations || require('./../data/translations.json').translations;
- options.users = options.users || require('./../data/users.json').users;
- options.theme = options.theme || Controller._getCurrentController(options).theme;
- options._layoutFile = options.layout ? Controller._getLayout(options.layout) : Controller._getLayout();
- options.controller = req.target.controller;
- options.action = req.target.action;
- if(view === false){
- return res.view(options);
- }else{
- return res.view(view, options);
- }
- }
- /**
- * View renderer adapted for the back office part of the website.
- * @param req Request.
- * @param res Response.
- * @param options Specific options to render the view.
- * @param view View to load. Use the path controller/method by default.
- */
- public static renderViewBackoffice(req, res, options: any = {}, view: any = false){
- if(view){
- // Custom path, just add the backoffice folder.
- view = Controller._backofficeFolderName + '/' + view;
- }else{
- // No path, use the targets to know which view to call.
- view = req.target.controller.replace(Controller._backofficeFolderName, '') + '/' + req.target.action
- }
- return Controller.renderView(req, res, options, view);
- }
- /**
- **************************************************************************************************
- **************************************** Controller basic methods ********************************
- **************************************************************************************************
- */
- /**
- * Displays the global content, displays several resources.
- * This method is just to return a 404 error and explain the role.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- */
- public static index(req, res, callback, options: any = {}){
- Controller.__beforeIndex(req, res, function(req, res, callback, options){
- res.notFound();
- }, options)
- }
- /**
- * Show only one resource. (Focuses on one, not many)
- * This method is just to return a 404 error and explain the role.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- */
- public static show(req, res, callback, options: any = {}){
- Controller.__beforeShow(req, res, function(req, res, callback, options){
- res.notFound();
- }, options)
- }
- /**
- * Display the content to create a new resource.
- * This method is just to return a 404 error and explain the role.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- */
- public static new(req, res, callback, options: any = {}){
- Controller.__beforeNew(req, res, function(req, res, callback, options){
- res.notFound();
- }, options)
- }
- /**
- * Manage the request to create a new resource.
- * Basically called from a "new" view.
- * This method is just to return a 404 error and explain the role.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- */
- public static create(req, res, callback, options: any = {}){
- Controller.__beforeCreate(req, res, function(req, res, callback, options){
- res.notFound();
- }, options)
- }
- /**
- * Display the content to edit an existing resource.
- * This method is just to return a 404 error and explain the role.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- */
- public static edit(req, res, callback, options: any = {}){
- Controller.__beforeEdit(req, res, function(req, res, callback, options){
- res.notFound();
- }, options)
- }
- /**
- * Manage the request to update an existing resource.
- * Basically called from an "edit" view.
- * This method is just to return a 404 error and explain the role.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- */
- public static update(req, res, callback, options: any = {}){
- Controller.__beforeUpdate(req, res, function(req, res, callback, options){
- res.notFound();
- }, options)
- }
- /**
- * Destroy a resource.
- * This method is just to return a 404 error and explain the role.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- */
- public static destroy(req, res, callback, options: any = {}){
- Controller.__beforeDestroy(req, res, function(req, res, callback, options){
- res.notFound();
- }, options)
- }
- /**
- **************************************************************************************************
- **************************************** Magic methods *******************************************
- **************************************************************************************************
- */
- /**
- * Automatically triggered before each called method.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- * @private
- */
- public static __beforeEach(req, res, callback, options: any = {}){
- // Bind fake data.
- if(!req.session.user){
- req.session.user = require('./../data/users.json').users[0];
- }
- callback(req, res, options);
- // Add debug information.
- dev(function(){
- // TODO Add file upload debug using req.files
- // TODO Add ip
- consoleDev('Url: ' + req.method + ' ' + req.baseUrl + req._parsedUrl.href, 'debug');
- consoleDev('Options: ' + JSON.stringify(options), 'debug');
- consoleDev('Route: ' + req.route.method + ' ' + req.path + ' (' + req.route.regexp + ')', 'debug');
- consoleDev('Cookies: ' + req.headers.cookie, 'debug');
- consoleDev('User agent: ' + req.headers['user-agent'], 'debug');
- consoleDev('Session: ' + JSON.stringify(req.session), 'debug');
- consoleDev('---------------------------------------', 'debug');
- });
- }
- /**
- * Automatically triggered before all index methods are called.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- * @private
- */
- public static __beforeIndex(req, res, callback, options: any = {}){
- (Controller._getCurrentController(options)).__beforeEach(req, res, function(req, res, options){
- callback(req, res, options);
- }, options);
- }
- /**
- * Automatically triggered before all show methods are called.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- * @private
- */
- public static __beforeShow(req, res, callback, options: any = {}){
- (Controller._getCurrentController(options)).__beforeEach(req, res, function(req, res, options){
- callback(req, res, options);
- }, options);
- }
- /**
- * Automatically triggered before all new methods are called.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- * @private
- */
- public static __beforeNew(req, res, callback, options: any = {}){
- (Controller._getCurrentController(options)).__beforeEach(req, res, function(req, res, options){
- callback(req, res, options);
- }, options);
- }
- /**
- * Automatically triggered before all create methods are called.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- * @private
- */
- public static __beforeCreate(req, res, callback, options: any = {}){
- (Controller._getCurrentController(options)).__beforeEach(req, res, function(req, res, options){
- callback(req, res, options);
- }, options);
- }
- /**
- * Automatically triggered before all edit methods are called.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- * @private
- */
- public static __beforeEdit(req, res, callback, options: any = {}){
- (Controller._getCurrentController(options)).__beforeEach(req, res, function(req, res, options){
- callback(req, res, options);
- }, options);
- }
- /**
- * Automatically triggered before all update methods are called.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- * @private
- */
- public static __beforeUpdate(req, res, callback, options: any = {}){
- (Controller._getCurrentController(options)).__beforeEach(req, res, function(req, res, options){
- callback(req, res, options);
- }, options);
- }
- /**
- * Automatically triggered before all destroy methods are called.
- * @param req Request.
- * @param res Response.
- * @param callback Function to execute.
- * @param options Object that contains options.
- * @private
- */
- public static __beforeDestroy(req, res, callback, options: any = {}){
- (Controller._getCurrentController(options)).__beforeEach(req, res, function(req, res, options){
- callback(req, res, options);
- }, options);
- }
- /**
- **************************************************************************************************
- **************************************** Private methods *****************************************
- **************************************************************************************************
- */
- /**
- * Based on the option, used to determinate which controller class use, a child if exists or the parent.
- * @param options See args explained at Controller.super
- * @returns {*}
- * @private
- */
- private static _getCurrentController(options): any{
- if(options.controller){
- return options.controller;
- }else{
- return Controller;
- }
- }
- /**
- * Clean the name of a method to avoid anything bad.
- * @param method
- * @returns {*}
- * @private
- */
- private static _cleanMethodName(method): string {
- return ucfirst(method.replace('_', ''));
- }
- /**
- * Should return the layout to use without have to take care of the relative path, it should be managed by the controller.
- * @param layout
- * @returns {string}
- * @private
- */
- private static _getLayout(layout = Controller._defaultLayout){
- return Controller._layoutRelativePath + layout;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement