BarryBones41 BarryBones41 - 1 month ago 20
Javascript Question

How to document returned data in JsDoc

How can I document the returned JSON result of a request to a server?

Example

/**
* Gets a user's data
* @returns {jQuery}
*/
function getUserData(userId){
return $.get('/usr/' + userId);
}


In the above example the returned data would be an object of JSON such as

{
"name" : "Bob",
"status" : 2
}

Answer
/**
 * Gets a user's data request
 * @return {jQuery.jqXHR}
 */
function getUserData(userId){
   return $.getJSON('/usr/' + userId);
}

/*
 * Handles the result of a user data request.
 * @param {Object} data The JSON object, already converted to an Object.
 */
function doSomethingWithUserData(data) {
  console.log('do something with user data:', data);
}

getUserData(userId).done(handleUserData);

As Felix points out, the return value is not JSON, it's not even an Object.

Quote JQuery's types documentation:

As of jQuery 1.5, the $.ajax() method returns the jqXHR object, which is a superset of the XMLHTTPRequest object. For more information, see the jqXHR section of the $.ajax entry

Since $.get and $.getJSON are both shorthands for $.ajax, the same applies.

In the example I'm using the promise and a handler. I've made a function from the handler so it could be documented more clearly, but this is often done with an anonymous function.

I've also converted $.get to $.getJSON, which will do the JSON.parse call for you (which converts the reply from a string to an object). $.get's handler would take a @param {string} instead.

Update

In a comment OP asked how to handle this with custom data so that a future dev would know what to expect in the call.

Now that we've got the data, let's look at documenting it.

There are 3 good solutions for documentation, depending on complexity and if you have initialization to do.

The simplest would be to create a @typedef using @property to describe the properties, this requires no additional code, and is purely documentation.

goog.provide('UserData');
/* 
 * UserData (in the style of Closure's JSDocs)
 * @typedef {{
 *   name: {string},
 *   title: {string}
 * }}
 */
UserData;

or

/* 
 * UserData (in the style of useJSDocs)
 * @typedef {Object}
 * @property {string} name
 * @property {string} title
 * }}
 */
var UserData;

in use:

/*
 * Handles the result of a user data request.
 * @param {UserData} data The JSON object, already converted to an Object,
 * cast to UserData
 */
function doSomethingWithUserData(data) {
  console.log('do something with user data:', data);
}

And @interface @record which is similar and may be more useful to you.

Finally there's a straight up class, where you'd let user = new UserData(jsonUser), if you can gather up more than a few lines of default setting / initialization and place it in the class, this is how I'd suggest going.

Comments