Skip to content

Commit

Permalink
back: Add getSiblings method in Region Controller.
Browse files Browse the repository at this point in the history
This commit introduces a new method getSiblings in regionController.js.
This method seeks to return sibling regions for a given region ID and
hierarchy ID. It also modifies the Hierarchy model to include a
getSiblings method and updates the regionRoutes.js to add a new route
for this functionality.

Issue: #159

Signed-off-by: Nikolay Martyanov <[email protected]>
  • Loading branch information
OhmSpectator committed Dec 27, 2023
1 parent d5fbec7 commit 10cf654
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
26 changes: 26 additions & 0 deletions backend/src/controllers/regionController.js
Original file line number Diff line number Diff line change
Expand Up @@ -400,3 +400,29 @@ exports.getSubregions = async (req, res) => {
) : { message: subregions.message };
return res.status(subregions.status).json(result);
};

exports.getSiblings = async (req, res) => {
const { regionId } = req.params;
const hierarchyId = req.query.hierarchyId || 1;

console.log('regionId: ', regionId);

// Check if the region exists
const region = await Hierarchy.findOne({
where: {
regionId,
hierarchyId,
},
});
if (!region) {
return res.status(404).json({ message: 'Region not found' });
}

try {
const siblings = await region.getSiblings();
return res.status(200).json(siblings.map((sibling) => sibling.toApiFormat()));
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Internal Server Error' });
}
};
9 changes: 9 additions & 0 deletions backend/src/models/Hierarchy.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ class Hierarchy extends Model {
};
}

async getSiblings() {
return Hierarchy.findAll({
where: {
parentId: this.parentId,
hierarchyId: this.hierarchyId,
},
});
}

static async getAncestors(regionId, hierarchyId) {
const ancestors = await sequelize.query(`
WITH RECURSIVE Ancestors AS (
Expand Down
16 changes: 16 additions & 0 deletions backend/src/routes/regionRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,20 @@ router.get(
},
);

router.get(
'/:regionId/siblings',
...[
check('regionId').isInt().withMessage('Region ID must be an integer'),
check('hierarchyId').optional().isInt().withMessage('Hierarchy ID must be an integer'),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const errorMessages = errors.array().map((error) => error.msg);
return res.status(400).json({ errors: errorMessages });
}
return regionController.getSiblings(req, res);
},
);

module.exports = router;

0 comments on commit 10cf654

Please sign in to comment.