I recently put together an Express/Node API that consumes and transforms an additional third party API.
And while everything is working great, I feel there may be ways to improve the architecture and implementation.
This is my current implementation:
nodes_modules/
routes/
...api.js
...search.js
index.js
.babelrc
.config.js
.package.json
api.js
import express from "express";
let router = express.Router();
router.use('/search', require('./search'));
module.exports = router;
search.js
import express from "express";
import axios from "axios";
import transformer from "transformer";
const router = express.Router();
router.get('/:type', (req, res) => {
const type = req.params.type;
axios.get('http://example.com/api/' + type)
.then((response) => {
let transformed = {};
switch(type) {
case "people":
transformed = transformer.search(response.data, "results[*].{ name: name }");
break;
case "aircrafts":
transformed = transformer.search(response.data, "results[*].{ name : aircraftName }");
break;
default:
res.status(400).send({ error : "Bad request" });
break;
}
res.send({original: response.data, transformed: transformed });
})
.catch( () => {
res.status(400).send({ error : "Bad request" });
});
});
module.exports = router;
index.js
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', require('./routes/api'));
app.use('*', (req,res) => {
res.status(404).send('Page Not Found');
});
app.listen(3030, function() {
console.log('running on port 3030');
});
I appreciate any suggestions for improvement, pointing out of any flaws or useful changes that can be made to the current implementation. Thank you