I'm still wrapping my head around Node, but I have a very simple question. I see a lot of node examples where people are declaring their routes and all their logic in a single app.js file (or sometimes splitting them off into subfiles).
My question is basically: is it better to keep all your route declarations in the app or bootstrap a generic route that maps to your file structure. This may seem like a primitive question but my goal is to grasp what's most efficient within node.
I'm currently building an API handler with Restify but I have another app that uses Express (so this question will likely answer both questions).
In my route I can either declare a single route bootstrap like so:
app.all('/api/:package/:controller', function(request, response) {
var controller = require(
'../' + request.params.package + '/api/' + request.params.controller
);
controller.index(request, response);
response.end();
});
This basically accepts all calls from the API and targets the proper api controller. Alternatively I can declare each route individually or perhaps even write an loop that goes through each of my controllers and declares them on init. So:
for (var i in packages.controllers) {
app.all('api/' + package + '/' + controllers[i].name, function(request, response) {
var controller = require(
'../' + request.params.package + '/api/' + request.params.controller
);
controller.index(request, response);
}
}
packages.controllers being an array of all possible controllers. Note the above code is not accurate, I have an HMVC folder structure so the code is a bit more complicated than the above. But you get the point.
I'm wondering what the consequences of either are and if it really matters at all?
Thanks!
I would not recommend a single app.js at all. You will end up with a 5,000+ line file which is a nightmare to maintain.
The largest issue I see with your snippet is that even though require() gets cached, it has to perform a synchronous IO request. It's just a bad habit to get into.
Similar to what Don recommends, I have had the best luck splitting out routes into modules which export a single function which accept an instance of the app. You can think of it as "decorating" the app instance:
// app.js
var app = express.createServer();
app.configure(function(){ //... });
require('./foo')(app);
// foo.js
exports = module.exports = function(app){
app.get('/whatever', function(req, res){});
};
The exploding app.js file prompted a couple of us to create a small reference app to codify a standard Express app structure. It's not rocket science, but rather a set of conventions that makes things more organized.
You can find it here: https://github.com/EAAppFoundry/tableau
We'd love suggestions/pull requests if there something we got wrong or is missing.
I don't think there should be any real problem with looping through the directory tree and generating the routes. However, it'll be hard to define route based middleware and other routing features (such as variables in the routes) in a nice way.
I wrote a library that I use to define my routes declaratively and with minimal repetition which you might be interested in. It's inspired by Rails resourceful routing and is pretty flexible - the idea is to build a hash of routes and subroutes; there are also facilities to define groups of routes, middleware and variables.
https://github.com/cheesun/express-declarative-routing
Although it doesn't automatically generate the routes based on your directory structure, I think that'd be a cool feature and welcome you add it to the library.
Related
I have to make a webapplication with many different modules (like a todo-module, document-modules, and a big usermanagement-module for admin users). The total number of pages is > 100. And the module access is different for each user.
I am working with Laravel and Vue-router.
But what is the best practice to do it?
Create a SPA-application, with 1 large vue-router for everything?
For every module a own single "SPA" (with and own vue-router)?
Or another suggestion...?
Little late but I will try to answer the question. This is more an architectural question than just routing level question.
TLDR: You will need a mix of approaches. One approach won't fit.
1. Routing Mode
First, you should determine if you are going with HTML 5 history mode or hash mode
It is 2018, and I definitely recommend that you use HTML5 history mode.
If you use history mode, then it means your client-side router will need to work in sync with your server-side router.
2. Micro-frontends
I am not sure if you know this, but micro-frontends is the term you are looking for. Basically, it is your first line of segregation. You should split your app into multiple smaller apps. Each app will have its root component, router, models, services, etc. You will share many of the components (Of course, word very large application is important. And I literally mean it.)
3. Mono-repo considerations
If you have chosen to go ahead with Micro-frontends, then you might consider mono-repo setup
using Lerna or Builder.
4. Routing Module - Initialization
Irrespective of micro-apps, your app should have one starting point - main.js or index.js. In this file, you should initialize all your singleton things. Main singleton entities in a typical Vue.js app are Root Component, Data Store, Router, etc.
Your routing module will be separate from any component. Import routing module in this entry file and initialize it here.
5. Routing Module - Implementation
Routing module should be further split into smaller modules. Use simple functions and ES modules to do that. Each function will be responsible for returning a RouteConfig object. This is how it will look:
const route: RouteConfig = {
path: '/some-path',
component: AppComponent,
children: [
getWelcomeRoute(),
getDashboardRoute()
]
};
function getWelcomeRoute(): RouteConfig {
return {
name: ROUTE_WELCOME,
path: '',
component: WelcomeComponent
};
}
At route level, you should consider doing lazy loading of the modules. This will save many bytes from loading upfront:
function getLazyWelcomeRoute(): RouteConfig {
// IMPORTANT for lazy loading
const LazyWelcomeComponent = () => import('views/WelcomeComponent.vue');
return {
name: ROUTE_WELCOME,
path: '',
component: LazyWelcomeComponent
};
}
You cannot do this unless you use bundler like Webpack or Rollup.
5. Routing Module - Guard
This is very important
Guards are where you should handle your authorization. With Vue.js, it is possible to write component level route guard. But my suggestion is to refrain from doing so. Do it only when absolutely necessary. It is basically a separation of concern. Your routing module should possess the knowledge of authorization of your app. And technically, authorization exists/applies to a route than a component. That is the reason, why we created routing as a separate module altogether.
I am assuming that you are using some sort of data store like Redux or Vuex for the very large application. If you are going to write route level guards, then you will need to consult with data from Redux/Vuex store to take authorization decisions. It means you need to inject store into routing module. The simplest way to do that is to wrap your router initialization into a function like this:
export function makeRouter(store: Store<AppState>): VueRouter {
// Now you can access store here
return new VueRouter({
mode: 'history',
routes: [
getWelcomeRoute(store),
]
});
}
Now you can simply call this function from your entry-point file.
6. Routing Module - Default route
Remember to define a default catch-all route to show generic/intelligent 404 message to your users.
7. Routing Module - Routing data
Since we are really talking about very large application, it is better to avoid direct access to a router within your component. Instead, keep your router data in sync with your data store like vuex-router-sync
. You will save the painful amount of bugs by doing this.
8. Routing Module - Side effects
You will often use $router.replace() or $router.push() within your components. From a component perspective, it is a side effect. Instead, handle programmatic router navigation outside of your component. Create a central place for all router navigation. Dispatch a request/action to this external entity to handle these side effects for you. TLDR; Don't do routing side effect directly within your components. It will make your components SOLID and easy to test. In our case, we use redux-observable to handle routing side effects.
I hope this covers all the aspects of routing for a very large scale application.
If you go with SPA app, please make sure you are using these practices:
Lazy loading/async components. We usually do lazy loading for static assets. In the same spirit, we only need to load the components when the routes are visited. Vue will only trigger the factory function when the component needs to be rendered and will cache the result for future re-renders.
import MainPage from './routes/MainPage.vue'
const Page1 = r => require.ensure([], () => r(require('./routes/Page1.vue')))
const routes = [
{ path: '/main', component: MainPage },
{ path: '/page1', component: Page1 }
]
Combining routes: (related to above) For example, in the following case, 2 routes are output in the same chunk and bundle, causing that bundle to be lazy-loaded when either route is accessed.
const Page1 = r => require.ensure([], () => r(require('./routes/Page1.vue')), 'big-pages')
const Page2 = r => require.ensure([], () => r(require('./routes/Page2.vue')), 'big-pages')
Nuxt can help you with that. It generates your folder Structur dynamically to a router config file. Have a look at https://nuxtjs.org/guide/routing
It has even more help functions than routing. But especially for large applications in general an idea to set on nuxt
I am looking for some input regarding the naming conventions I use for route names and view directory structures.
Say I have the following routes:
Route::get('/teams/choose', 'ChooseTeamController#index')->name('teams.choose.index');
Route::post('/teams/choose', 'ChooseTeamController#choose')->name('teams.choose');
Route::get('/teams/{team}/manage', 'ManageTeamController#index')->name('teams.team.manage.index');
For the get routes, I would nornally put the views in a directory structure matching the route name. E.g. resources/views/teams/team/manage/index.blade.php. However, I feel that this is way too verbose.
I feel that it would be confusing all round (to myself and other developers) if I was to use a view directory structure like so, rather than the last example: resources/views/team/manage/index.blade.php- the plural of team is not used, so when I have other views, like so (using the original examples convention): resources/views/teams/choose.index they dont visually have the relationship intended. I.e. they have a differing 'root' directory- teams vs team.
Any input or advice would be appreciated.
For the get routes, I would normally put the views in a directory structure matching the route name. E.g. resources/views/teams/team/manage/index.blade.php. However, I feel that this is way too verbose.
I agree.
From the Laravel docs:
Laravel uses the typical RESTful "CRUD" approach when assigning resource routes to a controller. Each verb (i.e. GET, POST, PUT, DELETE) gets a designated URI, an action (technically, a controller method) and a route-name (sometimes, /path/to/blade/view).
So, from your snippet:
// return view(teams.index)
Route::get('/teams', 'TeamController#index');
// return view(teams.create)
Route::get('/teams/create', 'TeamsController#create');
// redirect('/home');
Route::post('/teams', 'TeamController#store');
// return view('teams.profile')
Route::get('/teams/profile', 'TeamController#profile')->name('profile');
I use this resource table to remind me what-to-do and what-not-do all the time.
Perhaps, inspecting some of the awesome Laravel codebases, might help. Plus, a perspective on how other teams are doing things is always priceless.
I found these to be very helpful:
RESTful API Best Practices and Common Pitfalls
RESTful API Design - A Cookbook
Update
The key is to stick to the standard CRUD actions i.e. index, show, create, store, edit, update and delete. The views will fall, right into their place.
Check out Adam Wathan's talk at Laracon EU as he demonstrates how, anything can be CRUDDY with a little imagination.
There are so many ways to maintain routes based on the requirement but i always follow below guidelines which helps me to maintain the file structure and easy to understand.
//listing
Route::get('/teams', 'TeamController#index');
//Create
Route::get('/teams/create', 'TeamController#create');
//Store
Route::post('/teams/store', 'TeamController#store');
//Show
Route::get('/teams/{id}', 'TeamController#show');
//Edit
Route::get('/teams/{id}/edit', 'TeamController#edit');
//Update
Route::put('/teams/{id}/update', 'TeamController#update');
//Delete
Route::delete('/teams/{id}/delete', 'TeamController#delete');
for more information related to proper naming convention you may follow below link
https://laravel.com/docs/7.x/controllers#restful-nested-resources
if you are building with consuming by api as a concern, you wouldn't need the create and edit forms so endpoints can be reduced to:
//listing
Route::get('/teams', 'TeamController#index');
//Store
Route::post('/teams', 'TeamController#store');
//Show
Route::get('/teams/{id}', 'TeamController#show');
//Update
Route::put('/teams/{id}', 'TeamController#update');
//Delete
Route::delete('/teams/{id}', 'TeamController#delete');
So I’m looking to make some routes within my super cool can.js application. Aiming for something like this…
#!claims ClaimsController - lists claims
#!claims/:id ClaimController - views a single claim
#!claims/new ClaimController - creates a new claim
#!claims/:id/pdf - do nothing, the ClaimController will handle it
#!admin AdminController - loads my Administrative panel with menu
#!admin/users - do nothing, the AdminController will handle it
#!admin/settings - do nothing, the AdminController will handle it
So how might we do this?
“claims route”: function() { load('ClaimsController'); },
“claims/:id route”: function() { load('ClaimController'); },
“admin”: function() { load(‘AdminController’); },
Cool beans, we’re off. So what if someone sends a link to someone like...
http://myapp#!claims/1/pdf
Nothing happens! Ok, well let’s add the route.
“claims/:id/pdf route”: function() { load('ClaimController'); },
Great. Now that link works. Here, the router’s job is only to load the controller. The controller will recognize that the pdf action is wanted, and show the correct view.
So pretend I’ve loaded up a claim claims/:id and I edit one or two things. Then I click the Print Preview button to view the PDF and change my route to claims/:id/pdf.
What should happen… the Claim Controller is watching the route and shows the pdf view.
What actually happens… the router sees the change, matches the claims/:id/pdf route we added, and reloads the Claim Controller, displaying a fresh version of the claim pulled from the server/cache, losing my changes.
To try and define the problem, I need the router to identify when the route changes, what controller the route belongs to, and if the controller is already loaded, ignore it. But this is hard!
claims //
claims/:id // different controllers!
claims/:id //
claims/:id/pdf // same controller!
We could just bind on the "controller" change. So defining routes like can.route(':controller') and binding on :controller.
{can.route} controller
// or
can.route.bind('controller', function() {...})
But clicking on a claim (changing from ClaimsController to ClaimController) won't trigger, as the first token claim is the same in both cases.
Is there a convention I can lean on? Should I be specifying every single route in the app and checking if the controller is loaded? Are my preferred route urls just not working?
The following is how I setup routing in complex CanJS applications. You can see an example of this here.
First, do not use can.Control routes. It's an anti-pattern and will be removed in 3.0 for something like the ideas in this issue.
Instead you setup a routing app module that imports and sets up modules by convention similar to this which is used here.
I will explain how to setup a routing app module in a moment. But first, it's important to understand how can.route is different from how you are probably used to thinking of routing. Its difference makes it difficult to understand at first, but once you get it; you'll hopefully see how powerful and perfect it is for client-side routing.
Instead of thinking of urls, think of can.route's data. What is in can.route.attr(). For example, your URLs seem to have data like:
page - the primary area someone is dealing with
subpage - an optional secondary area within the page
id - the id of a type
For example, admin/users might want can.route.attr() to return:
{page: "admin", subpage: "users"}
And, claims/5 might translate into:
{page: "claims", id: "5"}
When I start building an application, I only use urls that look like #!page=admin&subpage=users and ignore the pretty routing until later. I build an application around state first and foremost.
Once I have the mental picture of the can.route.attr() data that encapsulates my application's state, I build a routing app module that listens to changes in can.route and sets up the right controls or components. Yours might look like:
can.route.bind("change", throttle(function(){
if( can.route.attr("page") == "admin" ) {
load("AdminController")
} else if(can.route.attr("page") === "claims" && can.route.attr("id") {
load("ClaimController")
} else if ( ... ) {
...
} else {
// by convention, load a controller for whatever page is
load(can.capitalize(can.route.attr("page")+"Controller")
}
}) );
Finally, after setting all of that up, I make my pretty routes map to my expected can.route.attr() values:
can.route(":page"); // for #!claims, #!admin
can.route("claims/new", {page: "claims", subpage: "new"});
can.route("claims/:id", {page: "claims"});
can.route("admin/:subpage",{page: "admin"});
By doing it this way, you keep your routes independent of rest of the application. Everything simply listens to changes in can.route's attributes. All your routing rules are maintained in one place.
I'd like for changes in the URL to drive my application, and for changes in the application to change the URL, but not actually change state.
I have a route like this. The country/city example is a bit contrived, hopefully that doesn't confuse things. The relationship in the real application is somewhat hierarchical. Child views don't seem a fit though because there's no need for nested views.
$stateProvider.state( 'viewMap', {
url: '/viewMap/:country/:city',
templateUrl: 'pages/viewMap/viewMap.html',
controller: 'ViewMapController'
};
In ViewMapController, I can construct the page based on $stateParams.country and .city. As these values change, my application reacts and I want the url to stay in sync. I don't want to reload the whole page, however. I just want to update the url and push a history state on to the stack.
I understand I could manually construct a string:
updateUrl = function() {
window.location.hash = '#/viewMap/'+ $stateParams.country +'/'+ $stateParams.city
}
This feels fragile, as the way I build the string is separate from the way the framework parses it. I would prefer for the framework to build me a string based on the current params, but $state.href('.') describes the current route, which doesn't include $stateParams that haven't yet been activated/navigated to.
I've also looked at reloadOnSearch, but I think it only applies to query params.
Is there a better way to model this? It feels like I'm fighting the framework over something simple.
You can pass state params to $state.href function to get the complete URL
$state.href('.', $stateParams)
To generate arbitrary urls you can pass non-current params and/or configuration:
$state.href('.', {country:'usa',city:'sf'}, {absolute:true})
I'm integrating a JavaScript library into an ASP.NET MVC3 web app. The library assumes it will be installed next to the page that references it, and so it uses document-relative URLs to find its components.
For example, the default directory layout looks like
container-page.html
jslibrary/
library.js
images/
icon.png
extensions/
extension.js
extension-icon.png
However, I want to reference the library from the view in /Home/edit. I install the library in the default Scripts\jslibrary\ When I reference the library in the view in Views\Home\edit.cshtml, the library's document-relative links like
images/icon.png
end up as requests to
http://localhost/Home/images/icon.png
which results in a File Not Found (404) error. How do I construct a route to look for
{anyControllerName}/images/{anyRemainingPathInfo}
and serve up
http://localhost/Scripts/jslibrary/images/{anyRemainingPathInfo}
?
(full disclosure: I'm still on IIS 6 in Production, and not much chance of going to IIS7 any time soon, so if this is better done at the IIS level, please account for IIS6. Thanks!)
You could create a controller for handling you redirect logic - for example an "Images"controller. Register a global route in your Global.asax file, using the pattern (more on this type of pattern here:
routes.MapRoute(
"Images", // Route name
"{xyz}/{controller}/{path}", // URL with parameters
new {controller = "Images", action = "Index", path= UrlParameter.Optional} // Parameter defaults);
In your controller:
public ActionResult Index(string path)
{
//format path, parse request segments, or do other work needed to Id file to return...
return base.File(path, "image/jpeg"); //once you have the path pointing to the right place...
}
Not sure if this solution will work for you, wish I could come up with something more elegant. Best of Luck!
Short of rewriting the library and having it check for the appropriate directory the only solution I can think of is to include the views, library and supporting files in a directory structure that the library can access. This of course would break MVC's convention over configuration way of finding views, so you would have to write a custom override of the way Razor looks for views, which is not too complex to do, but you might be making life more difficult for yourself down the road depending on your application. Your call which is the lesser of the two evils :) (I'd go for fixing the library)
Make a help function
#functions{
public string AbsoluteUrl(string relativeContentPath)
{
Uri contextUri = HttpContext.Current.Request.Url;
var baseUri = string.Format("{0}://{1}{2}", contextUri.Scheme,
contextUri.Host, contextUri.Port == 80 ? string.Empty : ":" + contextUri.Port);
return string.Format("{0}{1}", baseUri, VirtualPathUtility.ToAbsolute(relativeContentPath));
}
}
Calling
#AbsoluteUrl("~/Images/myImage.jpg") <!-- gives the full path like: http://localhost:54334/Images/myImage.jpg -->
This example are from
https://dejanvasic.wordpress.com/2013/03/26/generating-full-content-url-in-mvc/