How can I annotate the interface of a JSON-response in google closure?
I have to use a JSONP interface which actually transforms some XML into JSON and provides it as a parameter to my callback. But unfortunately the origin XML contains some attributes so I get a JSON-Object with #attributes-fields e.g.
{
"output": {
"foo": "bar"
},
"#attributes": {
"baz": "attr"
}
}
I created an google-closure interface so the compiler will not minify my fields by accident and I get the neat auto-complition in my IDE.
/**
* #interface
*/
var JsonResult = function() {};
/**
* #type {JsonResultOutput}
*/
JsonResult.prototype.output;
/**
* #type {JsonResultAttributes}
*/
JsonResult.prototype['#attributes'];
/**
* #interface
*/
var JsonResultOutput = function() {};
/**
* #type {string}
*/
JsonResultOutput.prototype.foo;
/**
* #interface
*/
var JsonResultAttributes = function() {};
/**
* #type {string}
*/
JsonResultAttributes.prototype.baz;
Unfortunetly the compiler fires a warning if I try to annotate fields in brackets and strings. So my question is now: How should I annotate this to remove the warning? Maybe I can just remove this field in the interface, due to the problem that I have to write this field in the same way in the code as well, so the compiler will never minify this field. But I also want to document the object in it's full structure.
This looks like a bug to me. Feel free to file an issue at https://github.com/google/closure-compiler
For a workaround, you'll have to use object literal keys:
JsonResult.prototype = {
/**
* #type {JsonResultAttributes}
*/
'#attributes': {}
};
Related
Background
I have a project in Nodejs using ECMA6 classes and I am using JSDoc to comment my code, as to make it more accessible to other developers.
However, my comments are not well accepted by the tool, and my documentation is a train wreck.
Problem
My problem is that I don't know how to document ECMA6 classes with JSDoc and I can't find any decent information.
What I tried
I tried reading the official example but I find it lacking and incomplete. My classes have members, constant variables and much more, and I don't usually know which tags to use for what.
I also made an extensive search in the web, but most information I found is prior to 2015 where JSDocs didn't support ECMA6 scripts yet. Recent articles are scarce and don't cover my needs.
The closest thing I found was this GitHub Issue:
https://github.com/jsdoc3/jsdoc/issues/819
But it is outdated by now.
Objective
My main objective is to learn how to document ECMA6 classes in NodeJS with JSDoc.
I have a precise example that I would like to see work properly:
/**
* #fileOverview What is this file for?
* #author Who am I?
* #version 2.0.0
*/
"use strict";
//random requirements.
//I believe you don't have to document these.
let cheerio = require('cheerio');
//constants to be documented.
//I usually use the #const, #readonly and #default tags for them
const CONST_1 = "1";
const CONST_2 = 2;
//An example class
class MyClass {
//the class constructor
constructor(config) {
//class members. Should be private.
this.member1 = config;
this.member2 = "bananas";
}
//A normal method, public
methodOne() {
console.log( methodThree("I like bananas"));
}
//Another method. Receives a Fruit object parameter, public
methodTwo(fruit) {
return "he likes " + fruit.name;
}
//private method
methodThree(str) {
return "I think " + str;
}
}
module.exports = MyClass;
Question
Given this mini class example above, how would you go about documenting it using JSDoc?
An example will be appreciated.
Late answer, but since I came across this googling something else I thought I'd have a crack at it.
You've probably found by now that the JSDoc site has decent explanations and examples on how to document ES6 features.
Given that, here's how I would document your example:
/**
* module description
* #module MyClass
*/
//constants to be documented.
//I usually use the #const, #readonly and #default tags for them
/** #const {String} [description] */
const CONST_1 = "1";
/** #const {Number} [description] */
const CONST_2 = 2;
//An example class
/** MyClass description */
class MyClass {
//the class constructor
/**
* constructor description
* #param {[type]} config [description]
*/
constructor(config) {
//class members. Should be private.
/** #private */
this.member1 = config;
/** #private */
this.member2 = "bananas";
}
//A normal method, public
/** methodOne description */
methodOne() {
console.log( methodThree("I like bananas"));
}
//Another method. Receives a Fruit object parameter, public
/**
* methodTwo description
* #param {Object} fruit [description]
* #param {String} fruit.name [description]
* #return {String} [description]
*/
methodTwo(fruit) {
return "he likes " + fruit.name;
}
//private method
/**
* methodThree description
* #private
* #param {String} str [description]
* #return {String} [description]
*/
methodThree(str) {
return "I think " + str;
}
}
module.exports = MyClass;
Note that #const implies readonly and default automatically. JSDoc will pick up the export, the #class and the #constructor correctly, so only the oddities like private members need to be specified.
For anyone visiting this question in 2019:
The answer given by #FredStark is still correct, however, the following points should be noted:
Most/all of the links in this page are dead. For the documentation of the JSDoc, you can see here.
In many IDEs or code editors (such as VSCode), you will find auto-completions such as #class or #constructor which are not necessary for the case of ES6 classes since these editors will recognize the constructor after the new keyword.
I want to produce a warning for a number if a string is assigned to it. So, I thought typedef of Closure might do this for me. I tried the following -
var Widget = function()
{
/** #typedef {number} */
this.size = null;
};
new Widget().size = "kaboom!"
When I compile it using http://closure-compiler.appspot.com/home it doesn't throw a warning or error. What am I doing wrong? And/or what other tool should I be using?
Turn the optimization up to Advanced in the closure compiler service to catch these warnings. You still won't see any for your example (well, you will see some, but not what you are expecting), because typedefs are used to define custom types. Also, you need to annotate your constructor. Run the following example in advanced mode and you will see your warnings. Instead of making a typedef for a simple thing like number, I would just use #type, but this example is to show you the proper use of typedef.
/** #typedef {number} */
var customType;
/** #constructor */
var Widget = function()
{
/** #type {customType} */
this.size = null;
};
new Widget().size = "kaboom!"
I compile my source with closure compiler and when i call a function that got an event object from network the application throws an error in console.
The function called is:
/**
* #param {goog.events.Event} event Socket.io-Wrapper Event.
*/
de.my.app.admin.prototype.onSaved = function(event){
var category = event.data[0].category; //<-- here it throws the error because category get compiled.
var id = event.data[0].id;
var oldid = event.data[0].oldid;
[...]
}
the event object looks like this
{ data:{
0: {
category: 'someString',
id: 5,
oldid: -5
} }
[...someMoreValuesAddedBySocketIO...]
}
that is the behavior i expected.
now i add an externs declaration like this to my externs file but i didn't alter the type declaration of the #param at the function and the error disappears:
var xterns;
/**
* #typedef {{
* category : string,
* oldid : number,
* id : number
* }}
*/
xterns.NOTUSEDNAME;
/**
* #type {string}
*/
xterns.NOTUSEDNAME.prototype.category;
/**
* #type {number}
*/
xterns.NOTUSEDNAME.prototype.oldid;
/**
* #type {number}
*/
xterns.NOTUSEDNAME.prototype.id;
In short: I have a #param {goog.events.Event} event declaration and an extern for xterns.NOTUSEDNAME solves the compiler problems...
Can anyone explain why this happens?
This is a common misconception. Closure-compiler will not rename a property if any extern object contains a property of the same name. See the FAQ. If the type based optimizations are enabled, then this is no longer true and I would expect your code to break again.
To make this code type safe and compile without warnings, you would need to either:
Reference the data properties using quoted syntax event.data[0]['category']. Your properties will never be renamed by the compiler using this method (which is often used by JSON Data).
Extend the goog.events.Event type with a custom object that defines the data object as a strongly typed array.
Example:
/**
* #constructor
* #extends {goog.events.Event}
*/
de.my.app.AdminEvent = function() {};
goog.inherits(de.my.app.AdminEvent, goog.events.Event);
/** #type {Array.<{category:string, id:number, oldid:number}>} */
de.my.app.AdminEvent.prototype.data = [];
Depending on your exact situation, an interface might be a better option.
I'm creating an AngularJS service to validate form inputs and I can't for the life of me figure out how to use JSDoc3 to create reasonable documentation.
Ideally I need to export the documentation for the validator service as well as the documentation for each validator (internal objects)
After googling around a bit I was able to get it kind of working by hacking around a bit with namespaces, but I'm wondering if there's a right way to do this. A way that won't muck up somebody else's JSDoc if they include my service.
Example:
angular.module('services.utility')
.factory('validator', [function () {
var validators = {
/**
* Requires a field to have something in it.
* #param {String|Boolean} val The value to be checked.
* #return {Object}
*/
'required': function(val){
// check against validator
return {'valid': true, 'msg': 'passed!'};
},
/**
* Requires a field to be less than a number.
* #param {Number} val The value to be checked.
* #param {Number} check The value to be checked against.
* #return {Object}
*/
'lessThan': function(val){
// check against validator
return {'valid': true, 'msg': 'passed!'};
}
};
return {
/**
* This is the main validation routine.
* #param {Object} vObjs An object to be processed.
* #return {Boolean}
*/
'validate': function(thingsToValidate){
// run some validations from the validators
// and return a bool.
}
};
}]);
In a perfect world, modifications to the above would let me generate a nice, non-global, JSDoc hierarchy where a user could read about how to use the validator as a whole, or dive in and look what needed to be passed in for each type of validation.
Thanks so much for any help you can give!
The way my team works is that we actually only document the actual factory function as if the user were going to read it. You've actually skipped over that guy. Either way, you can treat that as the entry point for your documentation and combine it with your "method" documentation for the full picture. You could make use of the #namespace documentation in combination with this.
/** Here is how you use my factory. #param #return */
my.validator.factory = function() { return { validate: function(){} }; }
/** Here are some validators. #enum {Function(*):ValidationResult} **/
my.validator.Validators = {}
module.factory('validator', my.validator.factory);
Depending on what you really want, you may prefer to use a prototype. That's where documentation can really shine:
/** Here is how you use my factory. #param #return #constructor */
my.Validator = function() {}
/** My validation function. #param #return */
my.Validator.prototype.validate = function() {}
/** Here are some validators. #enum {Function(*):ValidationResult} **/
my.Validator.Validators = {}
module.service('validator', my.Validator);
Using the prototype with your documentation really sticks it all together for me. It's like documenting your validator as one class entity, which makes the most sense to me.
I have a JavaScript singleton object created with closure method:
/**
* This is the singleton.
*
* #namespace window.Something.Singleton
*/
window.Something.Singleton = (function() {
/**
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
/**
* #lends window.Something.Singleton#
*/
return {
/**
* #borrows window.Something-_foo
* #function
*/
foo: _foo
};
}());
But the jsdoc-toolkit does not generate the inherited documentation from _foo method to the foo method what I would like to have.
If I write #see instead of #borrows it works (inserts a link to the correct method), but I don't want to copy&paste the documentation for the foo method to have a public documentation as well.
I did some tests, and I have good news and bad news :). The good news is that it looks like you can get this to work by putting the #borrows tag in the Singleton doc comment:
/**
* This is the singleton.
*
* #namespace Something.Singleton
* #borrows Something.Singleton-_foo as foo
*/
Something.Singleton = (function() {
// etc
})());
But this has several ramifications, good and bad:
The foo function is marked static. This is probably a good thing, as it seems to be accurate as I understand your code.
With the code as it is currently shown (i.e. no more methods on the singleton, etc), you can dispense with the #lends tag entirely, unless you want to include it for clarity. If all methods are listed as #borrows on the top singleton namespace, then you don't need to further document them in the returned object. Again, this is probably a good thing.
The bad news is that I couldn't get this to work unless the borrowed method was explicitly marked #public - which makes it show up, redundantly, in the documentation. I think this is unavoidable - if jsdoc-toolkit thinks the method is private, it won't create documentation, so you can't refer to it (I get WARNING: Can't borrow undocumented Something.Singleton-_foo.). If the method is public, it gets displayed in the documentation.
So this works:
/**
* This is the singleton.
*
* #namespace Something.Singleton
* #borrows Something.Singleton-_foo as foo
*/
Something.Singleton = (function() {
/**
* #public
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
return {
foo: _foo
};
}());
...in that it copies the documentation for _foo to foo, but it will display _foo in the documentation page as well:
Method Summary
<inner> _foo()
<static> Something.Singleton.foo()
Probably the best workaround is simply to forget #borrows entirely and explicitly name _foo as Something.Singleton.foo in the doc comment, marking it as a public function (you could dispense with #public if you didn't name your inner function with an underscore, but this tells jsdoc-toolkit to treat it as private unless told otherwise):
/**
* This is the singleton.
*
* #namespace Something.Singleton
*/
Something.Singleton = (function() {
/**
* #name Something.Singleton#foo
* #public
* #function
* Foo method.
*
* #return {String} this method always returns with <code>bar</code>
*/
function _foo() { return "bar"; }
return {
foo: _foo
};
}());
This will produce the code documentation you're looking for, and puts the comment next to the actual code it relates to. It doesn't fully satisfy one's need to have the computer do all the work - you have to be very explicit in the comment - but I think it's just as clear, if not more so, than what you had originally, and I don't think it's much more maintenance (even in your original example, you'd have to change all your doc comments if you renamed Something.Singleton).
http://code.google.com/p/jsdoc-toolkit/wiki/TagBorrows
#borrows otherMemberName as thisMemberName
otherMemberName - Required: the namepath to the other member.
thisMemberName - Required: the new name that the member is being assigned to in this class.
/** #constructor */
function Remote() {
}
/** Connect to a remote address. */
Remote.prototype.transfer = function(address, data) {
}
/**
* #constructor
* #borrows Remote#transfer as this.send
*/
function SpecialWriter() {
this.send = Remote.prototype.transfer;
}
Any documentation for Remote#transfer will also appear as documentation for SpecialWriter#send.