From 8e5bad8ecd8be2a8ef5bd2ca79059f1740f5efbb Mon Sep 17 00:00:00 2001 From: David Diaz Date: Mon, 11 Mar 2019 21:58:07 -0600 Subject: [PATCH] Allows using full urls in the request key This allows you to break out of the top-level endpoint. If you send a full url instead of a path it'll be used instead of the top level endpoint. Example: ``` endpoint: http://example.com GET /posts: get-posts POST http://api.example.com/posts: post-post ``` --- src/__tests__/request.spec.js | 24 ++++++++++++++++++++++++ src/request.js | 7 +++++-- src/shared.js | 14 +++++++++++++- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/__tests__/request.spec.js b/src/__tests__/request.spec.js index edb0098..0433d94 100644 --- a/src/__tests__/request.spec.js +++ b/src/__tests__/request.spec.js @@ -73,4 +73,28 @@ describe('Request', () => { requestPromiseNativeMock.fail = true; await expect(requestWithoutDependencies.exec()).rejects.toThrow(Error); }); + + it(`should use the full url if given one as part of the path instead of the global endpoint`, async () => { + const requestWithPath = new Request({ + endpoint: 'http://example.com', + request: 'GET http://martianwabbit.com/user', + alias: 'get-user' + }); + + const requestWithoutPath = new Request({ + endpoint: 'http://example.com', + request: 'GET /user', + alias: 'get-user' + }); + + await expect(requestWithPath.exec()).resolves.toHaveProperty( + 'request.endpoint', + 'http://martianwabbit.com/user' + ); + + await expect(requestWithoutPath.exec()).resolves.toHaveProperty( + 'request.endpoint', + 'http://example.com/user' + ); + }); }); diff --git a/src/request.js b/src/request.js index 748d06e..a3d5aa6 100644 --- a/src/request.js +++ b/src/request.js @@ -6,7 +6,8 @@ const { requestRegex, replacementRegex, UpperCaseKeys, - removeOptionalKeys + removeOptionalKeys, + isUrl } = require('./shared'); class Request { @@ -63,8 +64,10 @@ class Request { } async exec(cache = new RequestCache()) { + const isPathFullUrl = isUrl(this.PATH); + let settings = cache.parse({ - baseUrl: this.ENDPOINT, + baseUrl: isPathFullUrl ? '' : this.ENDPOINT, uri: this.PATH, method: this.VERB, jar: this.COOKIEJAR, diff --git a/src/shared.js b/src/shared.js index d0d16f8..b1499c2 100644 --- a/src/shared.js +++ b/src/shared.js @@ -1,3 +1,5 @@ +const { URL } = require('url'); + const httpVerbs = [ 'GET', 'HEAD', @@ -66,6 +68,15 @@ const replaceInObject = function(obj, fn) { const moduleVersion = () => parseInt(require('../package.json').version, 10); +const isUrl = function(str) { + try { + new URL(str); + return true; + } catch (e) { + return false; + } +}; + module.exports = { requestRegex, replacementRegex, @@ -74,5 +85,6 @@ module.exports = { removeOptionalKeys, toKebabCase, replaceInObject, - moduleVersion + moduleVersion, + isUrl };