I am trying to figure out a good way to build an API in Node/Express. I was watching a video on YouTube by Dan Kwon & Velocity 360. I emailed and asked him some questions but he never replied. I feel like this method is kind of hacky and I was told by another developer that this method poses security threats. I actually don't like the code below but I like the concept of having a single "API". Personally, I would write all of this in TypeScript.
So, I guess my real questions are, is the following code good practice or bad practice and if it is bad practice, is the concept good? For example, could I refactor this in TypeScript and have a decent API? Like so:
class ApiRouter {
public getRequests(): void {
router.get('/:resource', (req, res, next) => {
let resource = req.params.resource
let controller = controllers[resource]
if (!controller) {
res.status(404).json({ error: '404 - Resource Not Found' });
}
controller.get(req.query, false, (err, results) => {
if (err) {
res.status(500).json({ err });
}
res.status(200).json({ results });
});
});
}
}
Dan Kwon's Code:
Link to repo: https://github.com/velocity-360/bookmark
var express = require('express')
var router = express.Router()
var entryController = require('../controllers/EntryController')
var profileController = require('../controllers/ProfileController')
var controllers = {
entry: entryController,
profile: profileController
}
router.get('/:resource', function(req, res, next) {
var resource = req.params.resource
var controller = controllers[resource]
if (controller == null){
res.json({
confirmation:'fail',
message: 'Invalid Resource'
})
return
}
controller.get(req.query, false, function(err, results){
if (err){
res.json({
confirmation:'fail',
message: err
})
return
}
res.json({
confirmation:'success',
results: results
})
return
})
})
Sorry for the formatting of the code. Hopefully the link to the repo will serve better for this question.
via Clayton Ray
No comments:
Post a Comment