简体   繁体   中英

Having a fixed response structure with node.js and Express

We have recently started using Node.js for our API server instead of Java . Apart from all the good things which Node.js provides, one thing I miss the most is having a proper response object for an API.

Since Javascript being dynamically typed languages, objects can be created on the fly while returning the response. This is in contrast to Java, where I can have a class , an instance of which will be serialized in the response. I can anytime lookup this class to determine what the response of the API will be.

Is there such a design pattern in Node.Js / Javascript. We would like our API's to have strict conformance to such templated object.

You can make them yourself.

If you're using ES6 for example, you can have various error and response modules, and perform your own validation in the class that creates those responses.

For example,

// sample-response.js

class SampleResponse {
  constructor(message) {
    // validate `message` somehow

    this.data = message
  }
}

module.exports = {
  SampleResponse
}

Then however you're structuring your HTTP interface, you can send back whichever response you'd like (for example, with Express):

res.send(new SampleResponse(message))

Same goes with errors, etc. You're not necessarily limited by a lack of types with JavaScript, you just have to enforce things differently.

If you're not using ES6, you can do something like this:

module.exports = {
  SampleResponse: function(message) {
    // do some validation

    return { data: message }; // or whatever you want
  }
};
  1. You can use Flow or TypeScript for you code.

  2. You can use contract testing tools. Depending on the contract for your REST API:

My choice is to use TypeScript and Abao+RAML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM