'Best Practice for Route Architecture
I'm trying to set up routes for my backend. I have two ways that I've tried setting these routes up, and I'm wondering which way fits best practices (or neither?). The differences are minimal, but I'd love to know if there is an objective "best" here.
Here are my attempts:
const express = require("express");
const router = express.Router();
const flashcardController = require('../controllers/flashcardController');
router.get('/', flashcardController.readFlashcard);
router.post('/', flashcardController.createFlashcard);
router.patch('/', flashcardController.updateFlashcard);
router.delete('/', flashcardController.deleteFlashcard);
module.exports = router
VS
const express = require("express");
const router = express.Router();
const flashcardController = require('../controllers/flashcardController');
module.exports = (app) => {
router.get('/api/flashcard', flashcardController.readFlashcard);
router.post('/api/flashcard', flashcardController.createFlashcard);
router.patch('/api/flashcard', flashcardController.updateFlashcard);
router.delete('/api/flashcard', flashcardController.deleteFlashcard);
app.use('/', router);
};
Of course, my app.js (entry-point for my backend) file will need to be coded slightly differently for each of these options.
Solution 1:[1]
I think because of lineId returned to you, instead of checking lineId equality you should check if the incoming lineId includes your lineId.
in your code: instead of line.lineId === item.lineId
check this: (item.lineId).includes(line.lineId)
maybe it works...
Solution 2:[2]
Does this work for you(mapNames function)...
const lines = [
{
lineId: "R_X002_ACCESS",
localName: "ACCESS",
name: "ACCESS"
},
{
lineId: "R_X00R_X002_BIB2_ACCESS",
localName: "BIB",
name: "BIB"
},
{
lineId: "R_X002_KNORR",
localName: "Knorr",
name: "Knorr"
},
{
lineId: "R_X002_POWDER",
localName: "Powder",
name: "Powder"
},
];
const items = [
{
lineId: "R_X002_POWDER"
},
{
lineId: "R_X00R_X002_BIB2_ACCESS,R_X002_ACCESS"
},
{
lineId: "R_X002_POWDER"
}
];
function mapNames(lines, items) {
const mappedLines = {};
lines.forEach(lineItem => {
if (!mappedLines[lineItem.lineId]) {
mappedLines[lineItem.lineId] = lineItem;
}
});
const mappedItems = items
.map(item => {
return {
lineId: item.lineId,
name: item.lineId.split(",")
.map(lineItem => mappedLines[lineItem].name || "")
.filter(x => x)
.join(",")
};
});
return mappedItems;
}
console.log("Mapped Names:\n", mapNames(lines, items));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | omidfarzadian |
| Solution 2 | Nalin Ranjan |
