Which directory to put object constructors in node / express - node.js

I want to create an object constructor for a new sign up within express. Where should this be located? Within the model? The controller?

It's really up to you to decide on your directory structure. Express doesn't enforce any particular structure.
That said, an object constructor clearly seems to fall into the model category. The model should include any data structures and logic for interacting with the database. The view is just what the user sees and interacts with, and the controller mediates between the view and the model (express routes would fit into this category).
For a short example using express with the sort of directory structure you seem to have, see this. Although the example uses a mongoose schema, the same principle should apply if you are using an ordinary object constructor. You might also want to look at some of the examples in the Express repository, including a different implementation of an mvc pattern.

Related

express js folder structure

I am learning express and i want to find a good folder structure for my project.
i found folder by feature and chose it to my project so I searched some articles to learn this structure.
Now, I have some questions:
where should I put validations? i use Joi for body requests validator and I am confused about where to put the validation.
i can put it into controller and i can create middleware for validated that endpoint, which one is better ? is another way better for that ?
where to put the models, because some models like the user.model used in auth feature and user feature and etc, can I put the models in the feature folder or create general folder for models ?

Bigger projects Node.js and RESTful API

I'm looking into node.js which really seem like a pretty nice environment. I've worked with a lot of different Technologies and for server, mainly php and Java (jsp), but dabbled in som RoR and Python.
I find node.js really easy to get up and running and it feels quite natural to work with, and I found some good entry level tutorials.
I just am missing some more intermediate resources. For example when creating bigger frameworks or api's how would you structure or architect it. I set up some smaller api's to try it out where it would go something like this:
I've made use of the Express framework to create a http server, listen to a port, set up an express object and bound some requests.
However these have been quite small, and the purpose has been learning, if I think about scaling up the size of the API for production, perhaps wanting to do other stuff like serve web-pages as well. I find it hard to see how the architecture would look.
It's vague as I am still new to node.js but I'm mainly thinking about things like if you typically keep all api in one file or if there are good ways to split it up into modules? And if anyone know any resource talking a bit more about how to design the architecture when working in node.js
Sorry for the vague question and thanks for reading.
In my opinion, Express is the good way to go if you want to build complex or big APIs.
It is among others easily testable (for instance with Mocha or Jasmine) and customizable, especially thanks to its middlewares.
For the directory structure, what I usually use is (at least) the following:
app.js : the main entrypoint. Will create the express application, indicate which controller to use for every route prefix, and assign the middlewares. Example from a previous project
controllers : will contain the controllers, the functions which will handle the requests, in the same style as in standard MVC frameworks (e.g. UserController, ...). Each controller would create an express Router object and export it. Inside the controllers, individual handlers are in charge of individual API requests, such as /api/users/list. It would use some library to access your data (e.g. Mongoose for MongoDB), and would then send the response to the client. Example (UserController.js)
models : will contain the models with all their attributes and methods. In my case, it would be the Mongoose models. Example (Song.js)
middlewares : will contain the various middlewares of the project. A practical example would be a middleware checking for an access token in the incoming request, and returning a 403 HTTP error if not. Example (AuthMiddleware.js)
helpers : various helpers
tests : unit tests of you API
This could be the minimal directory organization. On top of that, you may want to use a templating engine such as EJS to serve webpage. Take a look at « Use EJS to template your node application ».
This is only to give you an overview of what an express directory structure could look like, but there are of course plenty (better?) other possibilities. Hope that gives you a quick and useful insight :)

Sequelize REST API generator

I am developing a Nodejs application and my database is Postgres and I am using Sequelize as my ORM because of its excellent support for migrations.
I am on the lookout for a good REST API generator based on the schema I have defined. There are two main hurdles I am facing and they are that the generators don't do a good job of creating association API routes and lack of ACL support.
On the associations front, my schema has multiple levels of association i.e. for example..
Student.hasMany(Courses);
Courses.hasMany(Subjects);
So ideally the generated REST API should be something like
/student/:student_id/course/:course_id/subject/:subjectId
I found a few projects that are doing this, but are incomplete.
https://github.com/sequelize/sequelize-restful - is good but does not have ACL support
https://www.npmjs.org/package/restizr - is in alpha stage and does not generate API routes for associations.
Is there any module that supports this?
What you were doing here is writing a webservice without a domain model. https://en.wikipedia.org/wiki/Anemic_domain_model Ofc. you have every right to do it, but I wonder if you really understood what a webservice means. https://stackoverflow.com/a/1530607/607033 It is not a database with CRUD HTTP interface normally, though nowadays it is popular doing something this way and call it REST. A response to a REST HTTP request is a viewmodel https://softwareengineering.stackexchange.com/a/425001/65755 and it contains not just data, but a lot of metadata and hyperlinks. A REST API is a special type of webservice with many constraints. https://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf http://www.markus-lanthaler.com/research/hydra-a-vocabulary-for-hypermedia-driven-web-apis.pdf Your ORM is used 2 layers deeper in the data layer and it has nothing to do with the presentation layer where your REST API should be. I really wonder why people are making applications, which are doing nothing except serving data directly from the database and use the most inconvenient technology to do it. I guess there are databases nowadays with ACL and REST API support, so all you need is just using them. https://learn.microsoft.com/en-us/rest/api/sql/ Or there was something for PgSQL and Nodejs too around the time you asked this. https://github.com/QBisConsult/psql-api

Is there a way to link a specific method to a Route in ServiceStack?

The Problem
I'm aware of the basic way to create a route/endpoint in ServiceStack using methods with names like "Get", "Post", "Any", etc inside a service but in the particular case that I'm trying to work with I have an existing service (which I can make an IService via inheritance) that can not be retrofitted w/ServiceStack attributes and currently uses DTOs for the requests and responses.
This service contains many functions that I do not want to manually mask (as this is a pass-through layer) but otherwise already conform to ServiceStack's requirements. What I'm wondering is if there's a way to manually create these routes in a way that would work like I've mocked up here. My existing functions and DTOs already contain the information I would need to define the routes so if this approach is possible it would only require me to enumerate them at initialization time as opposed to generating the services layer manually.
I noticed there is an extension method on Routes.Add that takes an Expression of type Expression> but I was not able to get that working because I believe the underlying code makes assumptions about the type of Expression generated (LambdaExpression vs MemberExpression or something like that). I also may be barking up the wrong tree if that's not the intended purpose of that function but I can not find documentation anywhere on how that variant is supposed to work.
Why?
I'm not sure this is necessary but to shed some light on why I want to do this as opposed to retrofitting my existing layers: The current code is also used outside of a web service context and is consumed by other code internally. Retrofitting ServiceStack in to this layer would make every place that consumes it require ServiceStack's assemblies and be aware of the web service which is a concern I want separated from the lower code. We were previously using MVC/WCF to accomplish this goal but we want some of the features available from ServiceStack.
the current architecture looks like this:
data -> DAL -> discrete business logic -> composition -> web service
Hopefully that makes enough sense and I'm not being obtuse. If you would like any more details about what I want to do or why I'll try to update this post as soon as possible.
Thanks!
You might use the fallback route in order to provide your own routing mechanism.
Then you get the request.Path property and route using your own mapping of path:Function which can be stored in a simple dictionary.
Anyway, if you go this path I don't see much benefit in using servicestack. It seems you just need an http handler that routes requests to existing services.

Separating models, logic and DAOs in express/node.js

What's the best way to separate the different tiers of an express application, so that my app.js file doesn't get crammed full of functions? I'm coming from a Java world, so I typically have my models, business logic and DAO code in separate tiers.
The other question, that has been bothering me: how do I open a connection to a DB in app.js and then share that among the various pieces of code that need access to it? Not the routed functions, but the business logic modules.
See this project as separate files as follows:
https://github.com/lethus/popbroker
routes.js - Here we put the routes, usually referenced to controllers
models.js - Model here you put the functions of MongoDB
forms.js - You work the validation of objects
controllers / users.js - That would be something like java UI, here we call the models.js and do the insert, update, list, Finds

Resources