mardi 17 novembre 2020

With node.js, is using the same class in both front and back a good or bad practice?

We are working in a react projet with node.js.

We need to format data in back end before send it (in JSON) to the front.

Is it a good idea to import, in our back application the module we will use in the front one?

Example :

// IN THE BACK END
const express = require("express");
const app = express();
const path = require("path");
const myModule = require("myModule");
  
const backVersion = new myModule();
backVersion.addStuff("foo", 12345);
backVersion.addOtherKindOfStuff("bar", dataFormSomewhere);
...
  
app.get("/getData", (req, res) => {
        res.header("Content-Type", "application/json");
        res.json(backVersion);
});


 // When you call MyUrl:1234/getData
{
        stuffs : [{name:"foo", value:12345), {......}],
        otherKinfOfStuffs : [{key:"bar", data:{...},{...}]
}

// IN THE FRONT
import { getJson } from "./endpoints";
import myModule from "myModule";

const dataFromBack = await getJson("/getData");
const frontVersion = new myModule();

frontVersion.initFromJson(dataFromBack);

CONS :

  1. We load twice the same module
  2. We need to get sure it's the same version.

PROS :

  1. As we are using the same class, we are sure the resulting JSON is well formated for the front.
  2. We can use the addStuff() and addOtherKindOfStuff() to format our data.

Thank you.

Aucun commentaire:

Enregistrer un commentaire