it ('attach same daemon to different uris', function *() { yield suite.test(function(service) { service.from('http://0.0.0.0:8080/bar') .to(function() { this.body = this.body.url; }) .to('mock:bar'); service.from('http://0.0.0.0:8080') .to(function() { this.body = this.body.url; }) .to('mock:foo'); }); yield request('http://localhost:8080') .timeout(500); yield request('http://localhost:8080/bar') .timeout(500); if (suite.get('mock:foo').data.messages.length !== 1) { throw new Error('Message not arrived yet'); } if (suite.get('mock:bar').data.messages.length !== 1) { throw new Error('Message not arrived yet'); } });
export default async ({ service, env }) => { const path = `node_modules/.worona/${service}/${env}`; mkdirSync(path); console.log('Downloading the needed files... please wait.'); const manifest = await request(`https://prebackend.worona.io/packages/dist/vendors-${service}-worona/${service}/${env}/json/manifest.json`); writeFileSync(`${path}/vendors-manifest.json`, JSON.stringify(manifest.body, null, 2)); const core = await request(`https://prebackend.worona.io/api/v1/settings/package-development/${service}/${env}`); writeFileSync(`${path}/core-files.json`, JSON.stringify(core.body, null, 2)); console.log('Downloading finished.\n'); };
return function(opts, cb){ var uri = route_join(opts.host, route_path_interpolate(route, [opts.device_id])); // Instantiate a http request var r = sa(route.method, uri); if (route.auth && opts.access_token) r.set('Authorization', 'Bearer '+ opts.access_token); r.set('Accept', 'application/vnd.littlebits.v'+ opts.version +'+json'); // Custom payload data can be provided by the user under the payload key if (opts.payload) r.set(opts.payload); // For each known valid endpoint payload/query param, // look for provided data in opts. var add_params = param_adder(route.path, route.method, r, opts); if (route.payloadParams.children) { route.payloadParams.children.forEach(add_params); } if (route.queryParams.children) { route.queryParams.children.forEach(add_params); } // Do the HTTP request r.end(function(err, response){ if (err) return cb(err); if (response.error) return cb(extract_err(response)); cb(null, response.body); }); };
export function request(endpoint) { if (endpoint.indexOf(API_ROOT) === -1) { endpoint = API_ROOT + endpoint; } return superagent(endpoint); }
it('should allow connections without redirection', function(done) { request('http://localhost:7777/event/1') .end(function(res) { res.status.should.equal(200); done(); }); });
exports.request = function(method, path, data, cb) { if (!secret) { throw new Error("Balanced secret not set. Call `balanced.config(secret)` first.") } if ('function' == typeof data) { cb = data data = {} } if (typeof cb !== 'function') { throw new Error("callback function is required") } if (path.indexOf('/v1/') !== 0) { return cb(new Error("invalid balanced url (should start with /v1/): " + path)) } var req = superagent(method, BASE+path).auth(secret, '') if (method === 'GET') { req.query(data) } else { req.send(data) } req.end(function(err, r) { if (err) return cb(err) if (r.error) { if (exports.logErrors) console.error(r.body) r.error.balanced = r.body r.error.message += " - " + r.body.description return cb(r.error) } cb(null, r.body) }) }
request.get = function(url, data, fn){ var req = request('GET', url); if ('function' == typeof data) fn = data, data = null; if (data) req.query(data); if (fn) req.end(fn); return req; };
it("should retrieve a resource when api/recursos/pauta-publicitaria-2012/ is called", function(done){ request(host + 'api/recursos/pauta-publicitaria-2012', function(res){ expect(res.ok).to.be.ok(); var recurso = res.body; expect(recurso).to.be.an('object'); expect(recurso.nombre).to.be.equal('Pauta Publicitaria 2012'); expect(recurso.grupo).to.be.an('object'); expect(recurso.grupo.nombre).to.be.equal('Pauta Publicitaria'); expect(recurso.grupo.uri).to.be.equal(host + "api/grupos/pauta-publicitaria"); expect(recurso.grupo.categoria).to.be.an('object'); expect(recurso.grupo.categoria.nombre).to.be.equal('Finanzas Públicas'); expect(recurso.grupo.categoria.uri).to.be.equal(host + "api/categorias/finanzas-publicas"); expect(recurso.cantidad).to.be.equal(3); expect(recurso.propiedades.length).to.be.equal(2); expect(recurso.datos).to.be.an('array'); expect(recurso.datos.length).to.be.equal(3); var pauta = recurso.datos[1]; expect(pauta.medio).to.be.equal("A MEDIO CAMINO"); expect(pauta.monto).to.be.equal(25338.60); done(); }); });
it("should retrieve a list of groups when api/grupos/ is called", function(done){ request(host + 'api/grupos', function(res){ expect(res.ok).to.be.ok(); var grupos = res.body; expect(grupos).to.be.an('array'); expect(grupos.length).to.be.equal(4); var _grupos = _.sortBy(grupos, function(g){ return g.uri; }); expect(_grupos[0].nombre).to.be.equal("Áreas de Protección Histórica"); expect(_grupos[1].nombre).to.be.equal("Ejecución Presupuestaria 2012"); expect(_grupos[2].nombre).to.be.equal("Pauta Publicitaria"); expect(_grupos[3].nombre).to.be.equal("Visitas a la web de GCBA 2011"); expect(_grupos[0].uri).to.be.equal(host + "api/grupos/areas-proteccion-historica"); expect(_grupos[1].uri).to.be.equal(host + "api/grupos/ejecucion-presupuestaria-2012"); expect(_grupos[2].uri).to.be.equal(host + "api/grupos/pauta-publicitaria"); expect(_grupos[3].uri).to.be.equal(host + "api/grupos/visitas-web-GCBA-2011"); expect(_grupos[0].descripcion).to.be.equal("Información sobre las zonas de la Ciudad consultadas."); expect(_grupos[1].descripcion).to.be.equal("Información acorde a la Ley 70 la cual establece que el Poder Ejecutivo"); expect(_grupos[2].descripcion).to.be.equal("Montos (IVA incluído) destinados a las contrataciones de publicidad"); expect(_grupos[3].descripcion).to.be.equal("Información sobre el análisis del trafico de visitas de la web"); expect(_grupos[0].categoria).to.be.equal(host + "api/categorias/desarrollo-urbano"); expect(_grupos[1].categoria).to.be.equal(host + "api/categorias/finanzas-publicas"); expect(_grupos[2].categoria).to.be.equal(host + "api/categorias/finanzas-publicas"); expect(_grupos[3].categoria).to.be.equal(host + "api/categorias/informacion-digital"); done(); }); });
return new Promise((resolve) => { request('/reports/' + location) .end((err, res) => { resolve(res.body); return res.body; }) });
socket.on("search", function (q, fn) { request("http://tinysong.com/s/" + encodeURIComponent(q) + "?key=" + apiKey + "&format=json", function (res) { if (res.status === 200) { fn(JSON.parse(res.text)); } }); });
EZTV.prototype.latest = function() { var defer = Q.defer(); var episodes = []; request(BASE_URL + LATEST, function(res) { if(!res.ok) { return defer.reject(res.text); } var $ = cheerio.load(res.text); var show_rows = $('tr.forum_header_border[name="hover"]').filter(function() { episode_rows = $(this).children('.forum_thread_post'); if(episode_rows.length > 0) { return true; } return false; }); show_rows.each(function() { var entry = $(this); var info = parseRow(entry); if(info != null) { episodes.push(info); } }); defer.resolve(episodes); }) return defer.promise; }
const ajax = (method, resourceUrl, data, headers = {}, onprogress) => { debug(method, resourceUrl, data, headers); const promise = new AVPromise(); const req = request(method, resourceUrl) .set(headers) .send(data) .end((err, res) => { if (res) { debug(res.status, res.body, res.text); } if (err) { if (res) { err.statusCode = res.status; err.responseText = res.text; err.response = res.body; } return promise.reject(err); } return promise.resolve(res.body, res.status, res); }); if (onprogress) { req.on('progress', onprogress); } return promise; };
EZTV.prototype.getEpisodes = function(data, cb) { var defer = Q.defer(); var episodes = {}; request(BASE_URL + SHOWS + data.id + '/'+ data.slug +'/', function (res) { if(!res.ok) return defer.reject(res.text); var $ = cheerio.load(res.text); var show_rows = $('tr.forum_header_border[name="hover"]').filter(function() { episode_rows = $(this).children('.forum_thread_post'); if(episode_rows.length > 0) { return true; } return false; }); if(show_rows.length === 0) return defer.reject('Show Not Found: '+ data.slug); show_rows.each(function() { var entry = $(this); var info = parseRow(entry); if(!episodes[info.season]) episodes[info.season] = {}; if(!episodes[info.season][info.episode]) episodes[info.season][info.episode] = {}; if(!episodes[info.season][info.episode][info.quality] || info.repack) episodes[info.season][info.episode][info.quality] = info.torrent; episodes.dateBased = info.dateBased; }); defer.resolve(episodes); }); return defer.promise; }
EZTV.prototype.getShowList = function() { var defer = Q.defer(); request(BASE_URL + SHOWLIST, function(res){ if(!res.ok) { return defer.reject(res.text); } var $ = cheerio.load(res.text); var title, show; var allShows = []; $('.thread_link').each(function(){ var entry = $(this); var show = entry.text(); if(show) { var id = entry.attr('href').match(/\/shows\/(.*)\/(.*)\//)[1]; var slug = entry.attr('href').match(/\/shows\/(.*)\/(.*)\//)[2]; slug = slug in mappings ? mappings[slug]: slug; allShows.push({show: show, id: id, slug: slug}); } }); return defer.resolve(allShows); }); return defer.promise; }
value: function exec(cb) { var u = getURL(this.url, this.key, this.queryObj); var req = http(this.method.toUpperCase(), u).set('Authorization', 'Bearer ' + this.token); if (isBrowser) req.withCredentials(); req.end(function(err, response) { return cb(err, response.body); }); this.key = undefined; }
it('should run the callback for a method just once', function (done) { request('DELETE',appalluri + '/tobi').end(function(err,res){ console.log("delete response" + JSON.stringify([err,res])); assert(res.status == 404, "response should be 404 Not Found"); done(); }); });
requireOrFetchViz: function(vizName, cb) { var self = this; try { var Viz = require('viz/' + vizName); cb(null, Viz); } catch(e) { self.addStylesheet('/css/dynamic/viz/?visualizations[]=' + vizName); request('/js/dynamic/viz/?visualizations[]=' + vizName, function(err, res) { if(err) { return cb(err); } eval(res.text); var Viz = require('viz/' + vizName); cb(null, Viz); }); } }
it('get-started should be running', function (done) { request(URL + '/activities/get-started').end(function (err, resp, body) { if (err) throw err resp.statusCode.should.equal(200) // app is running done() }) })
request.options = function(url, data, fn){ var req = request('OPTIONS', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; };
it("should retrieve a list of resources when api/recursos/ is called", function(done){ request(host + 'api/recursos', function(res){ expect(res.ok).to.be.ok(); var recursos = res.body; expect(recursos).to.be.an('array'); expect(recursos.length).to.be.equal(4); var _recursos = _.sortBy(recursos, function(g){ return g.uri; }); expect(_recursos[0].nombre).to.be.equal("Áreas de Protección Histórica 2012"); expect(_recursos[1].nombre).to.be.equal("Cantidad de Visitas 2011"); expect(_recursos[2].nombre).to.be.equal("Pauta Publicitaria 2012"); expect(_recursos[3].nombre).to.be.equal("Presupuesto Devengado Primer Trimestre de 2012"); expect(_recursos[0].uri).to.be.equal(host + "api/recursos/areas-proteccion-historica-2012"); expect(_recursos[1].uri).to.be.equal(host + "api/recursos/cantidad-visitas-2011"); expect(_recursos[2].uri).to.be.equal(host + "api/recursos/pauta-publicitaria-2012"); expect(_recursos[3].uri).to.be.equal(host + "api/recursos/presupuesto-devengado-primer-trimestre-2012"); expect(_recursos[0].descripcion).to.be.equal("Información de las APH, dirección, estado de tramite, protección, imagen."); expect(_recursos[1].descripcion).to.be.equal("Cantidad de visitas por día para el año 2011"); expect(_recursos[2].descripcion).to.be.equal("Montos (IVA incluído) destinados a pauta publicitaria 2012 según medio proveedor."); expect(_recursos[3].descripcion).to.be.equal("Información provisoria del detalle de la ejecución trimestral del presupuesto."); expect(_recursos[0].grupo).to.be.equal(host + "api/grupos/areas-proteccion-historica"); expect(_recursos[1].grupo).to.be.equal(host + "api/grupos/visitas-web-GCBA-2011"); expect(_recursos[2].grupo).to.be.equal(host + "api/grupos/pauta-publicitaria"); expect(_recursos[3].grupo).to.be.equal(host + "api/grupos/ejecucion-presupuestaria-2012"); done(); }); });
return new Promise((resolve, reject) => { var request = api(baseUrl + type + '/' + index) request.set({ Accept: 'application/vnd.anapioficeandfire+json; version=1' }) if (cache[type][index]) { request.set({'If-None-Match': cache[type][index].etag}) } request.end((err, res) => { if (err && (!res || res.status != 304)) { return reject(err) } if (res.status != 304) { // Save result in cache cache[type][index] = { etag: res.headers.etag, data: res.body } } resolve(cache[type][index].data) }) })
it("should retrieve the details of the category when api/categorias/finanzas-publicas/ is called", function(done){ request(host + 'api/categorias/finanzas-publicas', function(res){ expect(res.ok).to.be.ok(); var category = res.body; expect(category).to.be.an('object'); expect(category.nombre).to.be.equal("Finanzas Públicas"); expect(category.grupos).to.be.an('array'); expect(category.grupos.length).to.be.equal(2); var grupos = _.sortBy(category.grupos, function(g){ return g.nombre; }); expect(grupos[0].nombre).to.be.equal("Ejecución Presupuestaria 2012"); expect(grupos[1].nombre).to.be.equal("Pauta Publicitaria"); expect(grupos[0].uri).to.be.equal(host + "api/grupos/ejecucion-presupuestaria-2012"); expect(grupos[1].uri).to.be.equal(host + "api/grupos/pauta-publicitaria"); expect(grupos[0].descripcion).to.be.equal("Información acorde a la Ley 70 la cual establece que el Poder Ejecutivo"); expect(grupos[1].descripcion).to.be.equal("Montos (IVA incluído) destinados a las contrataciones de publicidad"); done(); }); });
var APIRequest = function(endpoint, params, callback) { var self = this; // insert meetupAPIkey only if it exists. Note: for oauth it requires // that you passed the 'access_token' field instead of 'key' field. if (MeetupAPIkey != undefined) { params.key = MeetupAPIkey; } // supply url vars var url = endpoint.resource, url_vars = endpoint.resource.match(/\/:\w+/g) || []; url_vars.forEach(function(url_var) { url = url.replace(url_var, '/' + params[url_var.substr(2)]); delete params[url_var.substr(2)]; }); // generate request var req = request(endpoint.method, url) .query(params) .set('Accept', '*/*') .set('User-Agent', 'Meetup API lib for Node.js (' + Meetup.version + ')') .buffer(true) .end(function(res) { if (!Object.keys(res.body).length) { callback(res.error, JSON.parse(res.text)); } else { callback(res.error, res.body); } }); };
var ajax = function ajax(method, resourceUrl, data) { var headers = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; var onprogress = arguments[4]; debug(method, resourceUrl, data, headers); var promise = new Promise(); var req = request(method, resourceUrl).set(headers).send(data).end(function (err, res) { if (res) { debug(res.status, res.body, res.text); } if (err) { if (res) { err.statusCode = res.status; err.responseText = res.text; err.response = res.body; } return promise.reject(err); } return promise.resolve(res.body, res.status, res); }); if (onprogress) { req.on('progress', onprogress); } return promise; };
return new Promise((resolve, reject) => { const requestId = uuid.v4(); log("Requesting %s %s with Request ID %s", method, url, requestId); const superagentRequest = superagent(method, url) .set("Accept", accept); superagentRequest.set("X-Request-ID", requestId); if (data) { superagentRequest.set("Content-Type", dataType) .send(data); } superagentRequest.end((err, res) => { const parsed = parser ? parser(res.text) : res.text; const response = { res: res, text: res.text, headers: res.headers, status: res.status, statusText: res.statusText, data: parsed }; if (res.ok) { log("HTTP Request OK: ", res); resolve(response); } else { log("HTTP Error: ", res); reject(response); } }); });
request.patch = function(url, data, fn){ var req = request('PATCH', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; };
function noaaForResort(resortId, { overwrite }) { const descriptor = readDescriptor(resortId); const { ll } = descriptor; const url = `https://api.weather.gov/points/${points(ll)}/forecast`; superagent(url) .redirects(0) .accept('application/geo+json') .ok(({ status }) => status === 301) .then(function({ headers: { location } }) { let match = location.match(/^\/gridpoints\/(\S+)\/forecast$/); if (match) { let noaa = match[1]; if (overwrite) { descriptor.noaa = noaa; writeDescriptor(resortId, descriptor); } console.log(resortId, match[1]); } else { console.log('Invalid redirection', resortId, location); } }, function() { console.error('Cannot find NOAA station for:', resortId); }); }
request.head = function(url, data, fn){ var req = request('HEAD', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; };
it('should return without error', function(done) { request('http://localhost:7777/').end(function(res) { should.exist(res); res.status.should.equal(200); done(); }); });