3

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.

1
  • You can look into Swagger to have a way to document and validate response\request objects. Alternatively you can use Typescript to have compile-time type-check Commented Nov 5, 2016 at 16:50

2 Answers 2

3

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
  }
};
Sign up to request clarification or add additional context in comments.

Comments

1
  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.

Comments

Your Answer

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.