| Quaintous | Published: |
(tags)
|
(category)
|
|
| Updated: | ||||
| Sharing Models on Client and Server Side | ||||
|
Back in the days as I wasn’t a Node.js developer yet, we used to have our MVC models implemented in a server side language such as Ruby (as in Ruby on Rails) and once again on the client side in JavaScript. In our newest project as we decided to use Node for our backend and was discussing on wether to use AngularJS or React for the frontend, I voted for React because I thought we don’t need to implement yet another MVC system (such as Angular) on the frontend. The rationale was to share the models on both server and client side and use a lightweight library (such as React) just for the view. In the following I suggest a simple approach enabling the models to be shared both on the server and client side. The only assumption is that Node is used in the backend and JavaScript in the frontend. ModelsThe models are inspired by Rails’ Active Record Models. Each model contains a list of properties and a set of validators. The basic stub (without specific implementation) is as follows: Upon initiation the
ValidatorsA class implementing the Validators can be attached to properties of a model and are invoked upon setting the value of that property by calling the The advantage of embedding validators inside a model is that you can use it both on server side (e.g. just before persisting data in a database) and the front end (e.g. just before submitting a form). Serializing and DeserializingSince the data exchange between the frontend and backend is succeeded in JSON format and both ends are written in JavaScript, the (de)serializing is done at little to no cost. As mentioned earlier the The An ExampleConsider we want to model a nuclear plant: The |
||||
| License: | ![]() |
🟢 No JavaScript | (Notes) | |
| 🟢 No Tracking | ||||
