REST API Node.js, organization - javascript

I m actually developping a REST API using Node.js and Express 4.0 and I wanted to clarify something.
The service is actually working, but in a single javascript file, and I m looking for a good way to cut it into multiples parts.
I was thinking about MVC, but with the actual route system, what is the controller ? Is it the declaration function of the route ?
How can I separate the different route into multiple files ? (like user_routes, billing_routes) etc... I know how to export module etc... but having app = express() in multiple file seems to not work (different instanciation)
And where to start to the listen the part ?
These are beginner questions, but please, but explicit :-)
Thanks for advance

You can check out some these examples:
mvc: https://github.com/visionmedia/express/tree/master/examples/mvc and
route-separation: https://github.com/visionmedia/express/tree/master/examples/route-separation
Also here there are 2 good posts on SO about the subject:
https://stackoverflow.com/a/13611448/2846161
ExpressJS How to structure an application?

Related

NuxtJs dynamic routing

In NuxtJS (vuejs framework), I am having some difficulty with routes, I wanted to ask how we can create this kind of route using pages directory or any other approach?
Example:
Sample routes:
/some-route-of-page-2021
/some-route-of-page-2022 and so on for every year.
2021/2021 is the year and that will be dynamic
Having a dynamic variable inside of a path itself is supported in Nuxt3 . In Nuxt2, you can only have /some-route-of-page/XXX. In this case, it seems a bit more logical to have this kind of structure anyway. Usually, you don't have a lot of variables interpolated in the path itself, can be kinda confusing IMO.
Dynamic Pages are handled by adding an underscore in front of the parameter. For example "_pageyear.vue"
Docs: https://nuxtjs.org/examples/routing/dynamic-pages/
Sandbox: https://codesandbox.io/s/github/nuxtlabs/examples/tree/master/routing/dynamic-pages?from-embed

How to create multiple html pages using one main route?

I'm trying to create a website that has multiple community feeds like one for bowling and another for poker like so: localhost:8088/communities/bowling & localhost:8088/communities/poker.
I use actix as my webserver operating under the Rust programming language.
Is there a way where all addresses operating under localhost:8088/communities encounter the same web files so that I can just have one main route?
Then store the additional header like /bowling or /poker so that I can commit to separate requests to the server for the relevant post feeds? Maybe I can save the additional header information in a javascript variable when the web page is called? -Like when I go to /poker, a variable named communityType gets set to poker. How would I do something like that?
Because there's no way anyone is making HTML pages for each of ~100s different communities.
Thanks for the help in advance!
I'm not very familiar with this crate, but based on the docs it looks like you can use #[get("/route/this/function/will/support")] to define how a route is handled. Assuming that I wrote it correctly, this should respond with small message telling you which community route you are on when using.
use actix_web::{get, web, App, HttpServer, Responder};
#[get("/communities/{name}")]
async fn communities_route(web::Path(name): web::Path<String>) -> impl Responder {
format!("This is the page for the {:} community!", name)
}
You could also expand it to have routes for say #[get("/communities/{name}/forums")] or #[get("/communities/{name}/{file}")] to handle common routes all communities have on a per community basis.
Edit:
It sounds like you also need to include .service(communities_route) in your main function when initializing the App to use #[get(x)]. You also have better control over how the route is handled if you configure the services directly.
Here is one snippet from their hello world example. It looks like it prints the request on the server so long as you visit any route other than "/index.html".
async fn index(req: HttpRequest) -> &'static str {
println!("REQ: {:?}", req);
"Hello world!"
}
App::new()
.service(web::resource("/index.html").to(|| async { "Hello world!" }))
.service(web::resource("/").to(index))
I recommend looking through their examples on github. It looks like they have a bunch of concise examples for many different use cases.

Distributable/Distributed Web App with VueJS

I need to build a distributable app using VueJS. I'll describe the scene, so that it can be understood better.
Immagine the following:
Four companies have the same products database
Each of them has it's own politics, prices, custom colors, parameters, all of which are also stored in that database
These 4 companies want to integrate into their relative websites a page which shows their own catalogue (with their custom prices and politics and whatever), as well as, when you click on some of the products, the related information about that product
The question is: how can I make such an app using VueJS? Write it once and distribute it to these 4 different company websites?
And I've started to answer to my question doing the following:
I created an API which can be accessed by API Keys
Assigned to each company its very own API Key, so that requests coming with that API Key are associated with the given company
I created an app using VueCLI (which uses vue-router, for the pages/views, and axios for the API calls as well), wrote all my logic and components and styles and whatever else...and for development purposes I tried to use one of the 4 API keys (hard coding it into the axios.defaults.headers) to see if it all works...and it does!
Now, here comes the problem: I need to build/export the app in such a way that I can do something like this:
In www.company1.com/catalogue
Call catalogue.js and pass it the company1 API key
In www.company2.com/catalogue
Call catalogue.js and pass it the company2 API key
In www.company3.com/catalogue
Call catalogue.js and pass it the company3 API key
... I'll omit the company4 cause i'm sure you already got me.
Obviously I could export 4 different versions with the hard coded 4 different API's...but seems like a pretty stupid idea to me! Also, it exposes my client a lot cause, well, everybody could link to some of the companies' catalogue.js and, without configuration or whatever, visualise on it's own website my clients products..(which is obviously a problem).
I would like to have:
ONLY ONE catalogue.js file with some exposed parameters, as, for example: the API Key needed to identify the company.
In this way, everybody could still use that catalogue.js file, but with wrong credentials, it wouldn't produce a thing (i.e. will get an API error of unrecognized API key).
How on earth am I supposed to do this?
I'm banging my head on the wall from 2 weeks.
I've tried to export the app as Library, get errors like: Unknown custom element: <router-link> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
I tried to export the app as Web Component...got same error and others as well.
Please help me understand where I go wrong, and how should I approach the problem.
Look into Vue Environment Variables https://cli.vuejs.org/guide/mode-and-env.html
Or you can make independent settings.json file and load it through the axios

Can AdonisJs be used for REST APIS?

Sorry for a nooby question. I'd ask it anyway!
I am playing around with AdonisJs. I understand it is a MVC framework. But I want to write REST APIs using the said framework. I could not find much help on the internet.
I have two questions:
Does the framework support writing REST APIs?
If yes to 1. then what could be the best starting point?
1. I've created 3 API projects with AdonisJS and think it's ideal for quick setup. It has many functions already included from start, supports database migrations and is pretty well documented in general.
You can create routes easily with JSON responses:
http://adonisjs.com/docs/3.2/response
Route.get('/', function * (request, response) {
const users = yield User.all()
response.json(users)
})
Or add them to a controller, and even fairly easily add route authentication with token protection (all documented):
Route.post('my_api/v1/authenticate', 'ApiController.authenticate')
Route.group('api', function () {
Route.get('users', 'ApiController.getUsers')
}).prefix('my_api/v1').middleware('auth:api')
2. Take a look at the official tutorial, you can probably finish it in about half an hour. http://adonisjs.com/docs/3.2/overview#_simplest_example
Start with defining some routes and try out echoing simple variables with JSON and just in regular views.
Move the test logic to Controllers
Read a bit more about the database migrations and add some simple models.
Don't forget the Commands and Factory, as you can easily define test data commands there. This will save you a lot of time in the long run.
Just keep in mind that you need to have a server with Node.JS installed to run the system on production (personally I'm keeping it running using a tool like Node Forever JS.
In order to create just a RESTful api you can use
npm i -g #adonisjs/cli
# Create a new Adonis app
adonis new project-name --api-only

How to load angular module

I've just started using angular and javascript and I can't really figure out how to structure my application.
I started writing a Controller and my first reflex is to put what I would call my model into a class in a different file.
I have different option
1 - putting everything (model + controller ) in one file
2 - using requireJS so my controller can 'include' my model. I've managed to do it, put it wasn't straight forward and I still have problem to make the yeoman dist version to work.
3 - use angular module, which seems to be the recommended way, but if choose this solution do I need to load explicitly my model file in the main html file. I understand that not hardcoding the dependency between files can be a good thing, so you can for example swap or change some components, but it seems wrong when for example a subclass need to requires its parent class. If I need to split a module in lots of angular submodules, do I need to load them all explicitly ? That's seem totally wrong.
Am I missing something ? what is the standard way to do so ?
What I found quite useful are the MTV meetup sessions. They give a good overview about how to apply best practices in AngularJS:
Best Practices: http://www.youtube.com/watch?v=ZhfUv0spHCY
Angular+Yeoman: http://www.youtube.com/watch?v=XOmwZopzcTA
There are many more videos on youtube. I hope this helps giving a first idea.

Categories