How do you split up large controllers into multiple files in Express? - javascript

I'm building an express application which up until now has used a singular controller file named users. This contains various user related functions such as signUp/signIn/getPersonalInfo, which are exported using module.exports, and required in the router.
The problem is this file is now getting rather large and I would ideally like a folder structure such as the following:
controllers/users/registration.js
controllers/users/personalInfo.js
How can I do this such that I can still just require a single file in my router:
var users = require('../controllers/users/?');
and still have access to all the functions within each controller.
Also if there is a more efficient way of doing so please let me know.

Not sure if this is what you are looking for but in my project make use of multiple functions with only one reference to my 'bootcamps' controller.
const {
getBootcamps,
getBootcamp,
createBootcamp,
updateBootcamp,
deleteBootcamp,
getBootcampsInRadius,
bootcampPhotoUpload
} = require('../controllers/bootcamps');
Feel free to take a look at my project for inspiration:
https://github.com/KristoferMar/NodeJs-Guide/blob/master/routes/bootcamps.js

Related

How to structure app with Angular JS

I am trying to learn Angular JS and use it in my web app project and am looking for some guidance as well as answers to specific angular js questions. Tech stack I am using is MySQL db, Java w/ Spring Framework, HTML/CSS/Bootstrap/JS, etc..
The purpose of the app is basically a "social media craigslist" where it will have:
1. User accounts
2. Ability to create a "newsfeed-esque" post (one "view")
3. Ability to create a sale post (separate "view")
4. A view for an "inventory"
5. A view for a "wishlist"
etc..
(note: Items 2-5 are accessed via a nav bar of sorts that sits on the left side of my page and the idea was to have the main section of the page switch the content based on what nav item you clicked.. more later..)
What I was doing was writing a bunch of Javscript code to make calls to my web services (grabbing static content to populate drop downs, sending user login info for logging in, etc..) and the < script > tags were growing and all of this was living in my index.html page and I thought it might make more sense to use something like Angular JS and structure it a bit differently and "modularize" the code so it wasn't a giant mess in index page. I was also doing some manual .hide() and .show() JS stuff so I thought that it also might make more sense to switch out the content using something like AngularJS instead of having maximum ONE .show() active at once and then having to do as many .hide()'s as I would need to, to manually switch out the content. This is sounding like a SPA (single page app) right?
I have researched AngularJS StackOverflow posts and looked at w3schools and other helpful websites but am having trouble with how to structure this and use best practices not only with code efforts but organizational as well.
1) Am I correct in thinking Angular would make the hide and show of content easier?
2) I would like to make each "feature" of my website have its own controller and have Controller1.js, Controller2.js, etc.. but do I need to have a
var app = angular.module('myApp', []); ...
line at the top of each controller or do I need something like a main controller with that in there only once and then a call to each controller from a main controller? Or is this not even how I should go about it? Thought process was again to modularize and avoid having one giant beastly file with all my JS logic in it.
3) I assume that I need to use the ng-route stuff (is this correct?) in order to do that hide and show of html content? (items 2-5 listed above) But in what file should that live? a javascript controller file? index.html? other?
4) I read you can only have one ng-view per application. Does that mean that you can only switch/change the content for ONE < div > / section of your web app, OR can you have multiple different divs being changed?
5) fyi - my current file structure is pretty much this.. is this how it should be?
-Java Resources (java code)
...
-WebContent
-img
-META-INF
-resources
-css (folder)
-js (folder with js files - controllers)
-WEB-INF
-lib (folder)
-views (folder)
-xx-servlet.xml
-web.xml
-index.html
-pom.xml
A lot of my questions are just because I am new to AngularJS and not seasoned in JS itself so am trying to better understand. Thanks for any and all help in advance.
First of all, if you want to use multiple views per app then you should use angular-ui-router module instead of angular-route module.
Now, we come to the file handling. So, for that you can make as much file as you can to define controllers, config, services and factories for the app. There are three ways of doing this.
The first one is putting var app = angular.module("MyApp",[]); in first file and defining controllers and services like app.controller('ctrl', ControllerFunction) in each of the other files below the first one. But, personally i don't prefer to use this way as you are exposing your app as a global variable here.
The second way is to create a main module in first file using angular.module('MyApp',[]) and in other files you can get it and define controllers using angular.module('MyApp').controller('ctrl', ControllerFunction). This is the safer way than the previous one.
The third way is to create a different module in each of the files and using all the modules in a single main module as dependencies. Like below
in one file
angular.module('Module1',[]).controller('ctrl1',CtrlFun1);
in another file
angular.module('Module2',[]).controller('ctrl2',CtrlFun2);
and in the main file, the main module, which is to be bootstraped
angular.module('MyApp',['Module1','Module2'])
This is the safest way to define services in different files. I personally advise this way of using multiple js files in single app. Because here you care not exposing a global variable or a single module, so anyone cannot inject some code using console easily.

One inject from multiple constants - Angular

I am using Angular constant as an configuration file for my services, my problem is that this file can become huge and i am would like to separate the configuration into multiple files. But i donĀ“t want to create a new Angular constant that i need to inject in the services that uses constants.
Is there a way to have only one main constant file that requires all the other files so that there is only one inject into the services? Or is it possibly to create one constant from all js files in a specific folder?
Other solutions to this problem would also be very helpful.
You can use $provide.decorator for that:
$provide.decorator('yourSettings', ['$delegate', function ($delegate) {
$delegate.newProp = 'new value';
return delegate;
}]);
See docs.

Code seperation in AngularJS

I'm quite new to AngularJS so please bear that in mind when reading this question...
I have some functions that I would like to make globally available to different modules within my website, plan is to have pages performing their own functions in a single page app style (so a user list / create / modify would be one page, and a product list / create / modify would be another). I would like to have some shared logic, say utility functions, and also user authorisation that can be shared between the different page modules.
This leads to my question.
Assuming I have all the account functions encapsulated within a service (app.factory('account, etc etc...') for example) and separated into it's own JS file, is it better to place it within it's own module and using dependency injection like so:
var accountMod = angular.module('accountModule', ['dependencies']);
accountMod.factory('account', ['dependencies', function (...) { }]);
Or just assume the name of the app variable will always be app and express it like so:
app.factory('account', ['dependencies', function (...) { }]);
Functionally both of these work, but I am trying to use best practices. The second option seems limited, I have never been keen on assuming variable are the same name throughout, for me the dependency injection method seems better but I have seen many examples of both styles out there!
Any help is much appreciated!
Really nice question. There are subtle things in this.
I think it would helpful to use following code, which is using module.
var accountMod = angular.module('accountModule', ['dependencies']);
accountMod.factory('account', ['dependencies', function (...) { }]);
However with help of angular provider and adding module level config we can mock object or service. Eventually this will increase the test ability of code.
If there are multiple services under accounting, then I would prefer to group them inside module.
These are my aspect of to look at it. Please add more if you found.
Thanks.
Just my 2 cents on your code examples.
The following approach is not recommended:
var accountMod = angular.module('accountModule', ['dependencies']);
accountMod.factory('account', ['dependencies', function (...) { }]);
A best practice is to only have 1 component per file, therefore no need to define a variable. Take a look at this: https://github.com/johnpapa/angular-styleguide#definitions-aka-setters
If you are just starting out with Angular, I recommend that you go through the rest of John Papa's Style Guide.
I love the structure that angular fullstack generator for yeoman has.
https://github.com/DaftMonk/generator-angular-fullstack
You can see how each module and component is separated and inside, de factory, services, directives, etc. and their associate test are split in one file per functionality.
This probably is overkilling for your propose, you can take only the angular idea.

Creating a "controller" script for Node.js

I'm creating a program in Node.js. I'm pretty new to programming anything other than small javascript functions for websites so please bear with me if my terminology/ideas are totally wrong.
I originally had the entire program in one giant (~500 line) script file. Several people suggested I split it up into separate classes, where each class only has one 'job' to complete. I like this idea as it has helped me really streamline my code and make it more modular and manageable.
My issue is: How do I access these classes from a central file?
For instance, pretend I have 3 classes, in 3 separate javascript files, all containing 3 functions each. I want to access and pass data to/from all of these from one central "controller" script. What's the best way to do this? Can I just require it into a variable, then access the script's functions like so?
var class1 = require('./class1.js');
class1.function1(); // call the first function contained in class1.js
Is such a thing even possible? Again, totally new to this.
NodeJS supports CommonJS modules. A CommonJS module provides three global variables: module, exports and require.
You can export your API by adding to the exports object and require these files just like other node modules (add ./ to indicate that it is relative to the current file), assign it to a variable and access the values you added to that files exports object:
// first-module.js
exports.hello = 'world';
exports.num = 23;
// main.js
var first = require('./first-module');
console.log(first.hello);
console.log(first.num);
You need to add functions to the exports object in class1.js.
require("./class1") will return this object.

Exposing application scripts to certain scripts only

uhh it's hard to come with a right title for this problem excuse me.
In a backbone.js application i am building. Models, Views, Templates are all in separate javascript, html files. I want to export the Models, Views and Templates to the application bootstapper file (app.js) without polluting the global variable i.e doing window.App.Model = myModel; that. By export i mean make the code inside the files available to app.js for initialization and running
How do i go about doing this?
Are there any patterns that will solve the problem? Could you provide me a example
Description
In cases where models,views and templates are split to many disparate files the application bootstrapper file app.js should have some means to access these M,V,C components. Hence common approach is to do below inside the model.js file
window.App.Model.PersonModel = Backbone.Model.extend({});
App.js
var instance = new window.App.Model.PersonModel();
var personView = new window.App.Views.PersonView({model:instance});
Finally you see that everything derives from the Global object App which i think is not safe, improper and weak way to build application dependencies
Suggestions
Just to the above question, could someone suggest a template loading library(javascript templates regardless of engine used) that can be used to load the templates
Take a look on RequireJS, which support asynchronous module definitions/loading. You would have to rewrite your modules to and app.js to satisfy AMD api, but it would take only few strings of code.

Categories

Resources