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 :
- We load twice the same module
- We need to get sure it's the same version.
PROS :
- As we are using the same class, we are sure the resulting JSON is well formated for the front.
- We can use the addStuff() and addOtherKindOfStuff() to format our data.
Thank you.
Aucun commentaire:
Enregistrer un commentaire