Abstracting the superagent

139 views Asked by At

Our application consists of nodejs, express, reactjs, and newforms. To make rest calls we are using :

var RestClient = require('superagent-ls')

And we are making rest calls like:

cleanBirthDate(callback) {
    var {birthDate} = this.cleanedData
    var formattedDob = moment (birthDate).format('DDMMYYYY')

    RestClient.get(Global.getBirthDateServiceUrl() + '/' + formattedDob)
        .end((err, res) => {
          if (err) {
            callback (err)
          }
          else if (res.clientError) {
            var message = errorsMappingSwitch(res.body.error)
            callback(null, forms.ValidationError(message))
          }
          else {
            callback(null)
          }
        })
  },

We want to move the RestClient related code to our own file say RestCleint.js and then require it and use it across the application. By doing so we can apply some generalised code(like error handling, logging, redirect to specific error pages depending on the error code) in one place.

Appreciate any help in this direction.

2

There are 2 answers

0
Rei Dien On

you can always require it like

RestClient.js

export default function callApi(callback) {
//your rest code
// use the callback here in the callback of your call.
}

app.js

import {callApi} from './RestClient';

callApi((err, result) => {
  if (err) console.log(err)
});
0
BradByte On

I did the exact same thing you require (even with using superagent). I created modules with the API code in a /utils folder and required them where applicable. For even more abstraction we're using CoffeeScript to create classes that inherit from a BaseAPIObject and invoke using something like API.Posts.getAll().end() etc.

This article was very helpful in understanding how to write your own modules: Export This: Interface Design Patterns for Node.js Modules.