NextJS multiple dynamic routes with different destionation - dynamic

In my project I have the following requirement: having 2 routes that are dynamic but that are going to be drawn by different components.
More context:
I have a CMS that provides all the info and in most of the cases I'm going to read from a "page" model. This is going to be drawn by the Page component and its going to have a getServerSideProps that makes a call to a CMS endpoint to get that information
The endpoint and component are not the same for the other case with a dynamic route
Both types of routes are completely dynamic so I cannot prepare then in advance (or at least I'm trying to find another solution) since they come from the CMS
As an example, I can have this slugs
mypage.com/about-us (page endpoint & component)
mypage.com/resource (resources endpoint & component)
Both routes are configured using dynamic routes like this
{
source: '/:pages*',
destination: '/cms/pages'
}
The problem here is that it can only match one of the endpoints and the logic for both calling the endpoint and the component used to draw it are completely different
Is there a way of fallbacking to the next matched URL in case that there's more than one that matches similar to the return {notFound: true}?
Some solutions that I have are:
Somehow hardcode all the resources urls (since are less than pages) and pass them as defined routes instead of dynamic routes
Make some dirty code that will check if the slug is from a resource and if not fallback to a page and then return a Resource component or a Page component depending on that (this idea I like it less since it makes the logic of the Page component super dirty)
Thanks so much!

Related

Vue page cannot open after refreshing the page

I added the routes dynamically to the router and I can visit all pages with router-view. However, when I try to refresh the page I cannot visit the page again although the URL is the same. It is http://localhost:8081/me.
this.$router.addRoute("Main", {
path: '/me',
name: 'Me',
component: () => import(`#/components/Me.vue`)
});
As I said, I can normally visit the page "Me", but when I refresh it, I cannot see its content anymore with the warning:
[Vue Router warn]: No match found for location with path "/me"
I tried to create router with createWebHistory("/") after reading the cause of the error but nothing seems to change. I will appreciate any help.
There are two reasons why this would happen.
First serving SPA application from the server.
Make sure that your back-end is set to serve index.html file for all routes since back-end server is unaware of the routes set by client-side router. Something like express-history-api-fallback-middleware can help is using Node.js/Express.js.
Second problem is that of using addRoute.
As you described, the problem could be that Vue router is taking routing decision before your code in components/common/LeftMenu.vue is getting executed which is responsible for calling addRoute(). Ensure that this code is called before routing decision is being made. Best way would be to move this logic in top-level application component. And, if you can move that to top-level components, that means you can try to declare all routes while defining the router.
Why that should be done?
Using addRoute is not necessarily an anti-pattern but having to rely on addRoute is often code smell. You would really need it in extremely rare scenarios. Routing is a high-level architectural concern for your application and thus better to be declared upfront somewhere at top-level module even before application is getting initialized. Low level components should not attempt to manipulate routing data structure (violation of DIP principles).
One scenario where you might be tempted to use addRoute is taking decision after some data manipulation by the component with addition of some API call. That seems legitimate need but then to address that there are better ways. Considering using route guards (guards support async resolution too!) and prevent user from entering the view till the guard is resolved successfully.

VueJS Process complete template before operations

Good afternoon.
I have an interesting problem at the moment. We have a third party server that offer translations for static html content. I need to fetch this content via Ajax and display it in my Vue components.
The current situation
These translations are fetched via a dictionary-like data structure, i.e. via a category and a key. We have incorporated a Vue plugin to load these into our components via a function t, like this:
<template>
<section>
<h1>{{ t('CommonHeaders', 'HomePage') }}</h1>
<p v-html="t('Articles', 'SiteDescription')"></p>
</section>
</template>
At the moment these translations are shipped to the browser by embedding them in the HTML, after which our client-side hydration mechanism reads them and adds them to the Vuex store. The t function then looks up the translations and displays them where needed. These translations are reactive and accept data parameters to format translations.
We use Vue SFC to render user flows in an SPA-like fashion, although the site is not yet an SPA.
The problem
In order for this to work the translations required for a page have to be listed in the back-end controller methods in a dictionary.
This has become un-maintainable and much more data is shipped to the front-end than what is necessary. Additionally, the back-end system has no definitive end-point when a page is built before being shipped to the browser that we can hook into in order to add the translations to the HTML and content often end up being duplicated.
The back-end system was built using DotNet MVC 4, so we have no SSR capabilities at this point.
The solution (hopefully)
In order to better maintain our code I would like to utilise the 't' function from the plugin to load translations via an AJAX call before the vue engine has rendered the template, i.e. via the beforeCreate or created hook. The problem is that the Vue instance will have to know about translations required in child component templates before the AJAX call can be fired, and I have no idea how to accomplish this.
On a side note, delaying rendering like this goes against all my instincts but it doesn't look like we have a choice at this point.
I am planning to cache the translations client side with a content hash in case they get updated, so the ajax calls will hopefully not be required very often, only on first load.
The site is gradually being converted into an SPA, at which point I will be able to split off the FE and utilise SSR via node. Up until that point though this is the best idea I could come up with.
Any help will be greatly appreciated.
I have been thinking about this my self as at the moment I just send an entire cached json to the client on App Init with a loading screen, is not bad at the moment since there is not a lot to translate but was considering the following approach otherwise:
Have an array in the translation vuex module store a list of keys that need to translate (array).
Have t() push the keys to translate if not already in translated store and return either empty string or a placeholder until the translation is re-actively available.
On mounted dispatch a fetch method on the store to perform the ajax call and set the translation state and clear out the translate list when complete.
Vue should by default it's behavior re-render upon the VUEX state being changed and cause t() in the template body to be recalled and return matching values on nextTick instead of placeholder value previously returned.

Adding custom route to Zend REST controller

I am using Zend F/W 1.12 in order to build a REST server.
One of my requirements are to have an action that Is outside the boundaries of what Zend can recognize as a "Restfull" action. What I mean is that I would like to have an action that is called something like mymedia and would like tou routes requests that are directed to //mymedia . Currently, Zend understand it as the id to a getAction and off course this is not what I want.
Any help will be highly appreciated!
Thanks
The implementation of Zend_Rest_Route does not allow much customization but instead provides a rudimental routing scheme for out-of-the-box usage.
So if you need to change the way how URIs are interpreted you can extend Zend_Rest_Route, Zend_Controller_Router_Route_Module or Zend_Controller_Router_Route_Abstract class to create your own kind of routing.
Have a look at the match method of those classes and what they do - e.g. they populate the $_values property array (while respecting the $_moduleKey, $_controllerKey and $_actionKey properties).
You can then add it e.g. as the first route within your bootstrap class:
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$router->addRoute('myRoute', new My_Route($frontController));
$router->addRoute('restRoute', new Zend_Rest_Route($frontController));
See:
http://framework.zend.com/manual/1.12/en/zend.controller.router.html#zend.controller.router.basic
Routing is a simple process of iterating through all provided routes and matching its definitions to current request URI. When a positive match is found, variable values are returned from the Route instance and are injected into the Zend_Controller_Request object for later use in the dispatcher as well as in user created controllers. On a negative match result, the next route in the chain is checked.
I once wrote a custom route for zend framework 1 that can handle custom restful routes. it served me well until now. see https://github.com/aporat/Application_Rest_Controller_Route for more details.
for example, if you want to have a url such as /users/30/messages mapped correctly into a zend controller action, use this route in your bootstrap:
$frontController = Zend_Controller_Front::getInstance();
$frontController->getRouter()->addRoute('users-messages', new Application_Rest_Controller_Route($frontController, 'users/:user_id/messages', ['controller' => 'users-messages']));

Sails.js - Change routing order (custom routes after blueprints)

I am having a very similar issue to this post here: How to use custom route middleware with Sails.js? (ExpressJS)
in that I want all non ajax requests (or all routes with the prefix /api) to load the same view, regardless of route. I have implemented the given answer in that question, but came across the issue that the policy is not called for any unspecified routes.
If I was to catch all routes so that the policy was called, all my blueprints would be overwritten.
Ideally, I would catch all routes last, after the blueprints, since every non API route should be sent to the front end.
I am using angularjs for the front end and want angular to deal with all non API routing.
I would rather not use a .htaccess file as I need to put session information into the page on it's initial load.
Thanks
It seems like your use case is very similar to a HTTP 404 Error situation - you want all requests which don't satisfy blueprint (and possibly route.js) routes to be handled in the same manner.
From api/responses/notFound.js:
* NOTE:
* If a request doesn't match any explicit routes (i.e. `config/routes.js`)
* or route blueprints (i.e. "shadow routes", Sails will call `res.notFound()`
* automatically.
*/
You can have special handling code here which calls the appropriate view if the request path contains /api:
if (req.path.match('^/api')) {
return res.view('your-view-here');
}

Parsing and mapping REST-like formatted URIs for custome event handling (iOS)

I need to implement a custom event handler, which should for example handle URIs like:
- SomeAppName://SomeDomainClassName/ID to fetch a record from a database table
or
- SomeAppName://SomeControllerName/PushView/SomeAdditionalOptions to push a view controller and set additional options, for example this could be a calendar view which should be focused to show the calendar at a certain date.
I have been searching for existing REST frameworks, but so far I didn't figure how any exising framework could allow me to define formats for URIs and map them to local classes, actions, whatever it will be.
How could I 1) define and interpret REST like URIs and 2) map them to local actions or objects, without reinventing the wheel (e.g. inheriting from RESTKit)?
Or should I end up to write my own parser? In that case, pointers to good REST like URI lex/flex are welcome.
What I was looking for is called an URL router in Ruby worlds. There exist a few also for Objective C, more or less useful.
I ended up to write a custom URL Router, that is like ruby URL routers just split into basically two components (router and route). For the Router part (the mapper and URL dispatcher so to say) I looked at TTURLMap, which is part of Three20, but threw away 90% of code and changed the action handling to fit my needs. It has lot's of boilerpate code, but basically was what I needed for getting an idea for the router.
For the particular route handling I use SOCKit, which seems great and has well tested code.
Now I can for example have a local function hello which takes two params to show some values passed as URL:
Roter *router = [[Router alloc] init];
[router map:#"soc://:ident/:saySomething" toInstance:self with:#selector(hello:sayWhat:)];
[router dispatch:#"soc://3/hi"];
I'll add blocks as well, but for most cases selectors work well, because SOCKit passes them the actual values for basic parameter types (no need to use parse the dictionary with values from the URL).