Abstracting the superagent

时间:2015-07-28 22:44:40

标签: node.js reactjs superagent newforms

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 个答案:

答案 0 :(得分:1)

我做了你需要的完全相同的事情(即使使用superagent)。我在/ utils文件夹中创建了带有API代码的模块,并在适用的地方需要它们。为了更加抽象,我们使用CoffeeScript创建从BaseAPIObject继承并使用API​​.Posts.getAll()。end()等方式调用的类。

本文非常有助于理解如何编写自己的模块:Export This: Interface Design Patterns for Node.js Modules

答案 1 :(得分:0)

你总是可以像

一样要求它
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)
});