4
\$\begingroup\$

I am creating a nodejs middleware server that will handle api transactions from a frontend and relay them to various api's (internal and external). The primary goal is to hide api keys from the frontend. It can also consolidate requests that may require 2 or more endpoints, and modify data structures, thus simplifying our frontend code.

I am hoping for feedback on overall design/structure which will allow us to create a project that will be flexible as we add more apis while keeping it DRY

URLs, keys, etc. are stored in a .env file

index.js

require('dotenv').load();
const express = require('express'),
 app = express(),
 request = require("./request").request,
 bodyParser = require('body-parser');
app.use(bodyParser.json());
//returns all locations
app.get("/locations", (req, res) => {
 let URL = '...';
 request({
 method: 'get',
 url: URL,
 api: 'apiName'
 }).then((resp) => {
 res.json(resp);
 })
});
//send password reset link
app.post("/resetemail", (req, res) => {
 let URL = '...';
 let DATA = req.body;
 request({
 method: 'post',
 url: URL,
 api: 'apiName',
 data: DATA
 }).then((resp) => {
 res.json(resp);
 })
});
app.listen(3000);

request.js

module.exports.request = function (options) {
 const client = require('./' + options.api).instance;
 const handleError = require('./' + options.api).handleError;
 const onSuccess = function (response) {
 console.log('Request Successful!', response);
 return response.data;
 }
 return client(options)
 .then(onSuccess)
 .catch(handleError);
}

apiName.js

const axios = require('axios');
const axiosInstance = axios.create({
 headers: { "token": process.env.API_TOKEN },
 baseURL: process.env.API_BASE_URL,
 timeout: 2000
});
const handleError = function (error) {
 console.error('Request Failed:', error.config);
 if (error.response) {
 console.error('Status:', error.response.status);
 console.error('Data:', error.response.data);
 console.error('Headers:', error.response.headers);
 } else {
 console.error('Error Message:', error.message);
 }
 return Promise.reject(error.response || error.message);
}
module.exports = {
 instance: axiosInstance,
 handleError: handleError
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jan 12, 2018 at 21:47
\$\endgroup\$
3
  • \$\begingroup\$ Just so I understand you correctly, "The primary goal is to hide api keys from the frontend." - it's providing the authentication layer for untrusted external clients? \$\endgroup\$ Commented Jan 16, 2018 at 21:31
  • 2
    \$\begingroup\$ Yes. We want to prevent users from making requests directly to a vendor's api using our api keys. This node/express app will be on the same server as the frontend so the frontend can make api requests to 'localhost' which this code will then 'proxy' to the vendor's API. Does that make sense? \$\endgroup\$ Commented Jan 16, 2018 at 22:04
  • \$\begingroup\$ "It can also consolidate requests that may require 2 or more endpoints" - am I missing this in the code, or is there an example of this at all in the sample code? \$\endgroup\$ Commented Jan 22, 2018 at 20:24

1 Answer 1

1
\$\begingroup\$

I think you need to add some middle-wares that helps to run your API code after that middle-ware with proper structuring way.

I would suggest the NPM Module express-app-generator

The advantages of it include:

  • Code Management in clean way.
  • Structured Routing.
  • Add Multiple Middle-Wares in filters array.
  • Create CRUD API's with REST or CRUD Keyword.
Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
answered Jan 17, 2018 at 16:56
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.