UNPKG

arrow-docgen

Version:
60 lines (57 loc) 2.22 kB
// jscs:disable jsDoc function generate(object, api, endpoint, opts) { var code = []; code.push('\t### Web Example for ' + endpoint.name); code.push('\tThis is an example you can use in your web page:'); code.push('```web'); code.push('var xhr = new XMLHttpRequest();'); code.push('xhr.onreadystate = function() {'); code.push('\tif (this.readyState===4) {'); code.push('\t\talert(this.status+\':\'+this.responseText);'); code.push('\t}'); code.push('};'); var url = opts.url; var idx = opts.url.indexOf('/:'); if (idx > 0) { url = opts.url.substring(0, idx); } var q = [], b = {}; endpoint.parameters && Object.keys(endpoint.parameters).forEach(function (k) { var param = endpoint.parameters[k]; if (param.type === 'query') { q.push(param.name + '=' + param.default || ''); } else if (param.type === 'path') { url += '/' + param.name.toUpperCase(); } else { b[param.name] = param.default || ''; } }); if (q.length) { url += '?' + q.join('&'); } code.push('xhr.open("' + endpoint.method + '","' + url + '");'); if (object.server.auth) { if (object.server.auth.type === 'basic' || object.server.auth.type === 'ldap') { code.push('//FIXME: you need to fetch your APIKey but not store in code'); code.push('//It must be returned as a Base64 encoded value "apikey:"'); code.push('//Define as the APIKEY variable or set below'); code.push('var authstr = \'Basic \' + APIKEY.replace(/[\\r\\n]+/gm,\'\');'); code.push('xhr.setRequestHeader(\'Authorization\', authstr);'); } else if (object.server.auth.type === 'apikey') { code.push('//FIXME: you need to fetch your APIKey but not store it in code'); code.push('//Define as the APIKEY variable or set below'); code.push('xhr.setRequestHeader(\'APIKey\', \'' + (object.server.auth.apikey || 'YOUR_APIKEY_GOES_HERE') + '\');'); } } if (endpoint.method === 'POST' || endpoint.method === 'PUT') { code.push('xhr.setRequestHeader(\'Content-Type\',\'application/json\');'); } if (Object.keys(b).length) { code.push('xhr.send(JSON.stringify(' + JSON.stringify(b, null, '\t') + '));'); } else { code.push('xhr.send();'); } code.push('```'); return code.join('\n'); } exports.generate = generate;