2017-02-26 9 views
0

superagentでノードテストを実行するたびにhttp://localhostと書いていることに気付きました。絶対URL接頭辞付きのスーパーエージェント

import superagent from 'superagent'; 

const request = superagent.agent(); 
request 
    .get('http://localhost/whatever') 
    .end((err, res) => { ... }); 

localhostの部分を避ける方法はありますか?

const baseUrl = 'http://localhost:3030'; 

request 
    .get(`${baseUrl}/whatever`) 

しかし、私はまだ毎回剤でbaseUrlを携帯する必要があります。

は、私の知る限り行ってきたように、リクエストがホストにハードコードされないようにすることです。

答えて

0

TL; DR:superagent-absoluteがそうです。詳細

あなたはsuperagentの上に1つの抽象化レイヤを作成することができます。 DELETE、HEAD、PATCH、POSTとPUT:今、あなたが同じことを行う必要があるだろう/

global.request = superagentAbsolute(agent)('http://localhost:3030'); 

始まる呼び出されたときagent.getをオーバーライドします

function superagentAbsolute(agent) { 
    return baseUrl => ({ 
    get: url => url.startsWith('/') ? agent.get(baseUrl + url) : agent.get(url), 
    }); 
} 

⬑。

https://github.com/zurfyx/superagent-absolute/blob/master/index.js

const OVERRIDE = 'delete,get,head,patch,post,put'.split(','); 
const superagentAbsolute = agent => baseUrl => (
    new Proxy(agent, { 
    get(target, propertyName) { 
     return (...params) => { 
     if (OVERRIDE.indexOf(propertyName) !== -1 
      && params.length > 0 
      && typeof params[0] === 'string' 
      && params[0].startsWith('/')) { 
      const absoluteUrl = baseUrl + params[0]; 
      return target[propertyName](absoluteUrl, ...params.slice(1)); 
     } 
     return target[propertyName](...params); 
     }; 
    }, 
    }) 
); 

それとも、単にsuperagent-absoluteを使用することができます。

const superagent = require('superagent'); 
const superagentAbsolute = require('superagent-absolute'); 

const agent = superagent.agent(); 
const request = superagentAbsolute(agent)('http://localhost:3030'); 

it('should should display "It works!"', (done) => { 
    request 
    .get('/') // Requests "http://localhost:3030/". 
    .end((err, res) => { 
     expect(res.status).to.equal(200); 
     expect(res.body).to.eql({ msg: 'It works!' }); 
     done(); 
    }); 
}); 
関連する問題