Skip to content

Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia

:lipstick: add tests section to UI

Nicholas Palenchar3ecf62857c57
diff --git a/pages/index.vue b/pages/index.vue
index 71926504f..cc4a8cce1 100644
--- a/pages/index.vue
+++ b/pages/index.vue
@@ -117,7 +117,8 @@
:source="validContentTypes"
:spellcheck="false"
v-model="contentType"
- >Content Type</autocomplete
+ >Content Type
+ </autocomplete
>
</li>
</ul>
@@ -276,10 +277,30 @@
class="material-icons"
:class="showPreRequestScript"
v-if="!showPreRequestScript"
- >code</i
+ >code</i
>
<i class="material-icons" :class="showPreRequestScript" v-else
- >close</i
+ >close</i
+ >
+ </button>
+ <button
+ :class="'icon' + (showPreRequestScript ? ' info-response' : '')"
+ id="preRequestScriptButto"
+ v-tooltip.bottom="{
+ content: !testsEnabled
+ ? 'Enable Tests'
+ : 'Disable Tests'
+ }"
+ @click="testsEnabled = !testsEnabled"
+ >
+ <i
+ class="material-icons"
+ :class="testsEnabled"
+ v-if="!testsEnabled"
+ >code</i
+ >
+ <i class="material-icons" :class="testsEnabled" v-else
+ >close</i
>
</button>
</span>
@@ -315,9 +336,46 @@
</span>
</div>
</pw-section>
+ <pw-section
+ v-if="testsEnabled"
+ class="orange"
+ label="Tests"
+ ref="postRequestTests"
+ >
+ <ul>
+ <li>
+ <div class="flex-wrap">
+ <label for="generatedCode">{{ $t("javascript_code") }}</label>
+ <div>
+ <a
+ href="https://github.com/liyasthomas/postwoman/wiki/Post-Request-Tests"
+ target="_blank"
+ rel="noopener"
+ >
+ <button class="icon" v-tooltip="$t('wiki')">
+ <i class="material-icons">help</i>
+ </button>
+ </a>
+ </div>
+ </div>
+ <Editor
+ v-model="postRequestTests"
+ :lang="'javascript'"
+ :options="{
+ maxLines: responseBodyMaxLines,
+ minLines: '16',
+ fontSize: '16px',
+ autoScrollEditorIntoView: true,
+ showPrintMargin: false,
+ useWorker: false
+ }"
+ />
+ </li>
+ </ul>
+ </pw-section>
<section id="options">
- <input id="tab-one" type="radio" name="options" checked="checked" />
+ <input id="tab-one" type="radio" name="options" checked="checked"/>
<label for="tab-one">{{ $t("authentication") }}</label>
<div class="tab">
<pw-section
@@ -376,12 +434,12 @@
<i
class="material-icons"
v-if="passwordFieldType === 'text'"
- >visibility</i
+ >visibility</i
>
<i
class="material-icons"
v-if="passwordFieldType !== 'text'"
- >visibility_off</i
+ >visibility_off</i
>
</button>
</li>
@@ -545,7 +603,7 @@
</ul>
</pw-section>
</div>
- <input id="tab-two" type="radio" name="options" />
+ <input id="tab-two" type="radio" name="options"/>
<label for="tab-two">{{ $t("headers") }}</label>
<div class="tab">
<pw-section class="orange" label="Headers" ref="headers">
@@ -627,7 +685,7 @@
</ul>
</pw-section>
</div>
- <input id="tab-three" type="radio" name="options" />
+ <input id="tab-three" type="radio" name="options"/>
<label for="tab-three">{{ $t("parameters") }}</label>
<div class="tab">
<pw-section class="pink" label="Parameters" ref="parameters">
@@ -745,7 +803,7 @@
<ul v-for="(value, key) in response.headers" :key="key">
<li>
<label :for="key">{{ key }}</label>
- <input :id="key" :value="value" :name="key" readonly />
+ <input :id="key" :value="value" :name="key" readonly/>
</li>
</ul>
<ul v-if="response.body">
@@ -830,12 +888,12 @@
</div>
<aside v-if="activeSidebar" class="sticky-inner inner-right">
<section>
- <input id="history-tab" type="radio" name="side" checked="checked" />
+ <input id="history-tab" type="radio" name="side" checked="checked"/>
<label for="history-tab">{{ $t("history") }}</label>
<div class="tab">
- <history @useHistory="handleUseHistory" ref="historyComponent" />
+ <history @useHistory="handleUseHistory" ref="historyComponent"/>
</div>
- <input id="collection-tab" type="radio" name="side" />
+ <input id="collection-tab" type="radio" name="side"/>
<label for="collection-tab">{{ $t("collections") }}</label>
<div class="tab">
<pw-section
@@ -843,7 +901,7 @@
:label="$t('collections')"
ref="collections"
>
- <collections />
+ <collections/>
</pw-section>
</div>
</section>
@@ -1000,7 +1058,7 @@
/>
</li>
<li>
- <input :value="token.value" readonly />
+ <input :value="token.value" readonly/>
</li>
<div class="flex-wrap">
<li>
@@ -1093,7 +1151,7 @@
<ul>
<li>
<label for="token-req-name">{{ $t("token_req_name") }}</label>
- <input v-model="tokenReqName" />
+ <input v-model="tokenReqName"/>
</li>
</ul>
<ul>
@@ -1126,659 +1184,661 @@
</template>
<script>
-import section from "../components/section";
-import url from "url";
-import querystring from "querystring";
-import textareaAutoHeight from "../directives/textareaAutoHeight";
-import parseCurlCommand from "../assets/js/curlparser.js";
-import getEnvironmentVariablesFromScript from "../functions/preRequest";
-import parseTemplateString from "../functions/templating";
-import AceEditor from "../components/ace-editor";
-import { tokenRequest, oauthRedirect } from "../assets/js/oauth";
-import { sendNetworkRequest } from "../functions/network";
+ import section from "../components/section";
+ import url from "url";
+ import querystring from "querystring";
+ import textareaAutoHeight from "../directives/textareaAutoHeight";
+ import parseCurlCommand from "../assets/js/curlparser.js";
+ import getEnvironmentVariablesFromScript from "../functions/preRequest";
+ import parseTemplateString from "../functions/templating";
+ import AceEditor from "../components/ace-editor";
+ import {tokenRequest, oauthRedirect} from "../assets/js/oauth";
+ import {sendNetworkRequest} from "../functions/network";
-const statusCategories = [
- {
- name: "informational",
- statusCodeRegex: new RegExp(/[1][0-9]+/),
- className: "info-response"
- },
- {
- name: "successful",
- statusCodeRegex: new RegExp(/[2][0-9]+/),
- className: "success-response"
- },
- {
- name: "redirection",
- statusCodeRegex: new RegExp(/[3][0-9]+/),
- className: "redir-response"
- },
- {
- name: "client error",
- statusCodeRegex: new RegExp(/[4][0-9]+/),
- className: "cl-error-response"
- },
- {
- name: "server error",
- statusCodeRegex: new RegExp(/[5][0-9]+/),
- className: "sv-error-response"
- },
- {
- // this object is a catch-all for when no other objects match and should always be last
- name: "unknown",
- statusCodeRegex: new RegExp(/.*/),
- className: "missing-data-response"
- }
-];
-const parseHeaders = xhr => {
- const headers = xhr
- .getAllResponseHeaders()
- .trim()
- .split(/[\r\n]+/);
- const headerMap = {};
- headers.forEach(line => {
- const parts = line.split(": ");
- const header = parts.shift().toLowerCase();
- const value = parts.join(": ");
- headerMap[header] = value;
- });
- return headerMap;
-};
-export const findStatusGroup = responseStatus =>
- statusCategories.find(status => status.statusCodeRegex.test(responseStatus));
+ const statusCategories = [
+ {
+ name: "informational",
+ statusCodeRegex: new RegExp(/[1][0-9]+/),
+ className: "info-response"
+ },
+ {
+ name: "successful",
+ statusCodeRegex: new RegExp(/[2][0-9]+/),
+ className: "success-response"
+ },
+ {
+ name: "redirection",
+ statusCodeRegex: new RegExp(/[3][0-9]+/),
+ className: "redir-response"
+ },
+ {
+ name: "client error",
+ statusCodeRegex: new RegExp(/[4][0-9]+/),
+ className: "cl-error-response"
+ },
+ {
+ name: "server error",
+ statusCodeRegex: new RegExp(/[5][0-9]+/),
+ className: "sv-error-response"
+ },
+ {
+ // this object is a catch-all for when no other objects match and should always be last
+ name: "unknown",
+ statusCodeRegex: new RegExp(/.*/),
+ className: "missing-data-response"
+ }
+ ];
+ const parseHeaders = xhr => {
+ const headers = xhr
+ .getAllResponseHeaders()
+ .trim()
+ .split(/[\r\n]+/);
+ const headerMap = {};
+ headers.forEach(line => {
+ const parts = line.split(": ");
+ const header = parts.shift().toLowerCase();
+ const value = parts.join(": ");
+ headerMap[header] = value;
+ });
+ return headerMap;
+ };
+ export const findStatusGroup = responseStatus =>
+ statusCategories.find(status => status.statusCodeRegex.test(responseStatus));
-export default {
- directives: {
- textareaAutoHeight
- },
+ export default {
+ directives: {
+ textareaAutoHeight
+ },
- components: {
- "pw-section": section,
- "pw-toggle": () => import("../components/toggle"),
- "pw-modal": () => import("../components/modal"),
- history: () => import("../components/history"),
- autocomplete: () => import("../components/autocomplete"),
- collections: () => import("../components/collections"),
- saveRequestAs: () => import("../components/collections/saveRequestAs"),
- Editor: AceEditor
- },
- data() {
- return {
- showModal: false,
- showPreRequestScript: false,
- preRequestScript: "// pw.env.set('variable', 'value');",
- copyButton: '<i class="material-icons">file_copy</i>',
- downloadButton: '<i class="material-icons">get_app</i>',
- doneButton: '<i class="material-icons">done</i>',
- isHidden: true,
- response: {
- status: "",
- headers: "",
- body: ""
- },
- previewEnabled: false,
- paramsWatchEnabled: true,
- expandResponse: false,
- showTokenList: false,
- showTokenRequest: false,
- showTokenRequestList: false,
+ components: {
+ "pw-section": section,
+ "pw-toggle": () => import("../components/toggle"),
+ "pw-modal": () => import("../components/modal"),
+ history: () => import("../components/history"),
+ autocomplete: () => import("../components/autocomplete"),
+ collections: () => import("../components/collections"),
+ saveRequestAs: () => import("../components/collections/saveRequestAs"),
+ Editor: AceEditor
+ },
+ data() {
+ return {
+ showModal: false,
+ showPreRequestScript: false,
+ testsEnabled: false,
+ preRequestScript: "// pw.env.set('variable', 'value');",
+ postRequestTests: "// pw.expect('variable').toBe('value);",
+ copyButton: '<i class="material-icons">file_copy</i>',
+ downloadButton: '<i class="material-icons">get_app</i>',
+ doneButton: '<i class="material-icons">done</i>',
+ isHidden: true,
+ response: {
+ status: "",
+ headers: "",
+ body: ""
+ },
+ previewEnabled: false,
+ paramsWatchEnabled: true,
+ expandResponse: false,
+ showTokenList: false,
+ showTokenRequest: false,
+ showTokenRequestList: false,
- /**
- * These are content types that can be automatically
- * serialized by postwoman.
- */
- knownContentTypes: [
- "application/json",
- "application/x-www-form-urlencoded"
- ],
+ /**
+ * These are content types that can be automatically
+ * serialized by postwoman.
+ */
+ knownContentTypes: [
+ "application/json",
+ "application/x-www-form-urlencoded"
+ ],
- /**
- * These are a list of Content Types known to Postwoman.
- */
- validContentTypes: [
- "application/json",
- "application/hal+json",
- "application/xml",
- "application/x-www-form-urlencoded",
- "text/html",
- "text/plain"
- ],
+ /**
+ * These are a list of Content Types known to Postwoman.
+ */
+ validContentTypes: [
+ "application/json",
+ "application/hal+json",
+ "application/xml",
+ "application/x-www-form-urlencoded",
+ "text/html",
+ "text/plain"
+ ],
- commonHeaders: [
- "WWW-Authenticate",
- "Authorization",
- "Proxy-Authenticate",
- "Proxy-Authorization",
- "Age",
- "Cache-Control",
- "Clear-Site-Data",
- "Expires",
- "Pragma",
- "Warning",
- "Accept-CH",
- "Accept-CH-Lifetime",
- "Early-Data",
- "Content-DPR",
- "DPR",
- "Device-Memory",
- "Save-Data",
- "Viewport-Width",
- "Width",
- "Last-Modified",
- "ETag",
- "If-Match",
- "If-None-Match",
- "If-Modified-Since",
- "If-Unmodified-Since",
- "Vary",
- "Connection",
- "Keep-Alive",
- "Accept",
- "Accept-Charset",
- "Accept-Encoding",
- "Accept-Language",
- "Expect",
- "Max-Forwards",
- "Cookie",
- "Set-Cookie",
- "Cookie2",
- "Set-Cookie2",
- "Access-Control-Allow-Origin",
- "Access-Control-Allow-Credentials",
- "Access-Control-Allow-Headers",
- "Access-Control-Allow-Methods",
- "Access-Control-Expose-Headers",
- "Access-Control-Max-Age",
- "Access-Control-Request-Headers",
- "Access-Control-Request-Method",
- "Origin",
- "Service-Worker-Allowed",
- "Timing-Allow-Origin",
- "X-Permitted-Cross-Domain-Policies",
- "DNT",
- "Tk",
- "Content-Disposition",
- "Content-Length",
- "Content-Type",
- "Content-Encoding",
- "Content-Language",
- "Content-Location",
- "Forwarded",
- "X-Forwarded-For",
- "X-Forwarded-Host",
- "X-Forwarded-Proto",
- "Via",
- "Location",
- "From",
- "Host",
- "Referer",
- "Referrer-Policy",
- "User-Agent",
- "Allow",
- "Server",
- "Accept-Ranges",
- "Range",
- "If-Range",
- "Content-Range",
- "Cross-Origin-Opener-Policy",
- "Cross-Origin-Resource-Policy",
- "Content-Security-Policy",
- "Content-Security-Policy-Report-Only",
- "Expect-CT",
- "Feature-Policy",
- "Public-Key-Pins",
- "Public-Key-Pins-Report-Only",
- "Strict-Transport-Security",
- "Upgrade-Insecure-Requests",
- "X-Content-Type-Options",
- "X-Download-Options",
- "X-Frame-Options",
- "X-Powered-By",
- "X-XSS-Protection",
- "Last-Event-ID",
- "NEL",
- "Ping-From",
- "Ping-To",
- "Report-To",
- "Transfer-Encoding",
- "TE",
- "Trailer",
- "Sec-WebSocket-Key",
- "Sec-WebSocket-Extensions",
- "Sec-WebSocket-Accept",
- "Sec-WebSocket-Protocol",
- "Sec-WebSocket-Version",
- "Accept-Push-Policy",
- "Accept-Signature",
- "Alt-Svc",
- "Date",
- "Large-Allocation",
- "Link",
- "Push-Policy",
- "Retry-After",
- "Signature",
- "Signed-Headers",
- "Server-Timing",
- "SourceMap",
- "Upgrade",
- "X-DNS-Prefetch-Control",
- "X-Firefox-Spdy",
- "X-Pingback",
- "X-Requested-With",
- "X-Robots-Tag",
- "X-UA-Compatible"
- ],
- showRequestModal: false,
- editRequest: {},
+ commonHeaders: [
+ "WWW-Authenticate",
+ "Authorization",
+ "Proxy-Authenticate",
+ "Proxy-Authorization",
+ "Age",
+ "Cache-Control",
+ "Clear-Site-Data",
+ "Expires",
+ "Pragma",
+ "Warning",
+ "Accept-CH",
+ "Accept-CH-Lifetime",
+ "Early-Data",
+ "Content-DPR",
+ "DPR",
+ "Device-Memory",
+ "Save-Data",
+ "Viewport-Width",
+ "Width",
+ "Last-Modified",
+ "ETag",
+ "If-Match",
+ "If-None-Match",
+ "If-Modified-Since",
+ "If-Unmodified-Since",
+ "Vary",
+ "Connection",
+ "Keep-Alive",
+ "Accept",
+ "Accept-Charset",
+ "Accept-Encoding",
+ "Accept-Language",
+ "Expect",
+ "Max-Forwards",
+ "Cookie",
+ "Set-Cookie",
+ "Cookie2",
+ "Set-Cookie2",
+ "Access-Control-Allow-Origin",
+ "Access-Control-Allow-Credentials",
+ "Access-Control-Allow-Headers",
+ "Access-Control-Allow-Methods",
+ "Access-Control-Expose-Headers",
+ "Access-Control-Max-Age",
+ "Access-Control-Request-Headers",
+ "Access-Control-Request-Method",
+ "Origin",
+ "Service-Worker-Allowed",
+ "Timing-Allow-Origin",
+ "X-Permitted-Cross-Domain-Policies",
+ "DNT",
+ "Tk",
+ "Content-Disposition",
+ "Content-Length",
+ "Content-Type",
+ "Content-Encoding",
+ "Content-Language",
+ "Content-Location",
+ "Forwarded",
+ "X-Forwarded-For",
+ "X-Forwarded-Host",
+ "X-Forwarded-Proto",
+ "Via",
+ "Location",
+ "From",
+ "Host",
+ "Referer",
+ "Referrer-Policy",
+ "User-Agent",
+ "Allow",
+ "Server",
+ "Accept-Ranges",
+ "Range",
+ "If-Range",
+ "Content-Range",
+ "Cross-Origin-Opener-Policy",
+ "Cross-Origin-Resource-Policy",
+ "Content-Security-Policy",
+ "Content-Security-Policy-Report-Only",
+ "Expect-CT",
+ "Feature-Policy",
+ "Public-Key-Pins",
+ "Public-Key-Pins-Report-Only",
+ "Strict-Transport-Security",
+ "Upgrade-Insecure-Requests",
+ "X-Content-Type-Options",
+ "X-Download-Options",
+ "X-Frame-Options",
+ "X-Powered-By",
+ "X-XSS-Protection",
+ "Last-Event-ID",
+ "NEL",
+ "Ping-From",
+ "Ping-To",
+ "Report-To",
+ "Transfer-Encoding",
+ "TE",
+ "Trailer",
+ "Sec-WebSocket-Key",
+ "Sec-WebSocket-Extensions",
+ "Sec-WebSocket-Accept",
+ "Sec-WebSocket-Protocol",
+ "Sec-WebSocket-Version",
+ "Accept-Push-Policy",
+ "Accept-Signature",
+ "Alt-Svc",
+ "Date",
+ "Large-Allocation",
+ "Link",
+ "Push-Policy",
+ "Retry-After",
+ "Signature",
+ "Signed-Headers",
+ "Server-Timing",
+ "SourceMap",
+ "Upgrade",
+ "X-DNS-Prefetch-Control",
+ "X-Firefox-Spdy",
+ "X-Pingback",
+ "X-Requested-With",
+ "X-Robots-Tag",
+ "X-UA-Compatible"
+ ],
+ showRequestModal: false,
+ editRequest: {},
- urlExcludes: {},
- responseBodyText: "",
- responseBodyType: "text",
- responseBodyMaxLines: 16,
- activeSidebar: true
- };
- },
- watch: {
- urlExcludes: {
- deep: true,
- handler() {
- this.$store.commit("postwoman/applySetting", [
- "URL_EXCLUDES",
- Object.assign({}, this.urlExcludes)
- ]);
- }
- },
- contentType(val) {
- this.rawInput = !this.knownContentTypes.includes(val);
- },
- rawInput(status) {
- if (status && this.rawParams === "") this.rawParams = "{}";
- else this.setRouteQueryState();
+ urlExcludes: {},
+ responseBodyText: "",
+ responseBodyType: "text",
+ responseBodyMaxLines: 16,
+ activeSidebar: true
+ };
},
- "response.body": function(val) {
- if (
- this.response.body === this.$t("waiting_send_req") ||
- this.response.body === this.$t("loading")
- ) {
- this.responseBodyText = this.response.body;
- this.responseBodyType = "text";
- } else {
+ watch: {
+ urlExcludes: {
+ deep: true,
+ handler() {
+ this.$store.commit("postwoman/applySetting", [
+ "URL_EXCLUDES",
+ Object.assign({}, this.urlExcludes)
+ ]);
+ }
+ },
+ contentType(val) {
+ this.rawInput = !this.knownContentTypes.includes(val);
+ },
+ rawInput(status) {
+ if (status && this.rawParams === "") this.rawParams = "{}";
+ else this.setRouteQueryState();
+ },
+ "response.body": function (val) {
if (
- this.responseType === "application/json" ||
- this.responseType === "application/hal+json"
+ this.response.body === this.$t("waiting_send_req") ||
+ this.response.body === this.$t("loading")
) {
- this.responseBodyText = JSON.stringify(this.response.body, null, 2);
- this.responseBodyType = "json";
- } else if (this.responseType === "text/html") {
- this.responseBodyText = this.response.body;
- this.responseBodyType = "html";
- } else {
this.responseBodyText = this.response.body;
this.responseBodyType = "text";
- }
- }
- },
- params: {
- handler: function(newValue) {
- if (!this.paramsWatchEnabled) {
- this.paramsWatchEnabled = true;
- return;
- }
- let path = this.path;
- let queryString = newValue
- .filter(({ key }) => !!key)
- .map(({ key, value }) => `${key}=${value}`)
- .join("&");
- queryString = queryString === "" ? "" : `?${queryString}`;
- if (path.includes("?")) {
- path = path.slice(0, path.indexOf("?")) + queryString;
} else {
- path = path + queryString;
+ if (
+ this.responseType === "application/json" ||
+ this.responseType === "application/hal+json"
+ ) {
+ this.responseBodyText = JSON.stringify(this.response.body, null, 2);
+ this.responseBodyType = "json";
+ } else if (this.responseType === "text/html") {
+ this.responseBodyText = this.response.body;
+ this.responseBodyType = "html";
+ } else {
+ this.responseBodyText = this.response.body;
+ this.responseBodyType = "text";
+ }
}
+ },
+ params: {
+ handler: function (newValue) {
+ if (!this.paramsWatchEnabled) {
+ this.paramsWatchEnabled = true;
+ return;
+ }
+ let path = this.path;
+ let queryString = newValue
+ .filter(({key}) => !!key)
+ .map(({key, value}) => `${key}=${value}`)
+ .join("&");
+ queryString = queryString === "" ? "" : `?${queryString}`;
+ if (path.includes("?")) {
+ path = path.slice(0, path.indexOf("?")) + queryString;
+ } else {
+ path = path + queryString;
+ }
- this.path = path;
+ this.path = path;
+ },
+ deep: true
},
- deep: true
- },
- selectedRequest(newValue, oldValue) {
- // @TODO: Convert all variables to single request variable
- if (!newValue) return;
- this.url = newValue.url;
- this.path = newValue.path;
- this.method = newValue.method;
- this.auth = newValue.auth;
- this.httpUser = newValue.httpUser;
- this.httpPassword = newValue.httpPassword;
- this.passwordFieldType = newValue.passwordFieldType;
- this.bearerToken = newValue.bearerToken;
- this.headers = newValue.headers;
- this.params = newValue.params;
- this.bodyParams = newValue.bodyParams;
- this.rawParams = newValue.rawParams;
- this.rawInput = newValue.rawInput;
- this.contentType = newValue.contentType;
- this.requestType = newValue.requestType;
- },
- editingRequest(newValue) {
- this.editRequest = newValue;
- this.showRequestModal = true;
- }
- },
- computed: {
- url: {
- get() {
- return this.$store.state.request.url;
- },
- set(value) {
- this.$store.commit("setState", { value, attribute: "url" });
- }
- },
- method: {
- get() {
- return this.$store.state.request.method;
+ selectedRequest(newValue, oldValue) {
+ // @TODO: Convert all variables to single request variable
+ if (!newValue) return;
+ this.url = newValue.url;
+ this.path = newValue.path;
+ this.method = newValue.method;
+ this.auth = newValue.auth;
+ this.httpUser = newValue.httpUser;
+ this.httpPassword = newValue.httpPassword;
+ this.passwordFieldType = newValue.passwordFieldType;
+ this.bearerToken = newValue.bearerToken;
+ this.headers = newValue.headers;
+ this.params = newValue.params;
+ this.bodyParams = newValue.bodyParams;
+ this.rawParams = newValue.rawParams;
+ this.rawInput = newValue.rawInput;
+ this.contentType = newValue.contentType;
+ this.requestType = newValue.requestType;
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "method" });
+ editingRequest(newValue) {
+ this.editRequest = newValue;
+ this.showRequestModal = true;
}
},
- path: {
- get() {
- return this.$store.state.request.path;
+ computed: {
+ url: {
+ get() {
+ return this.$store.state.request.url;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "url"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "path" });
- }
- },
- label: {
- get() {
- return this.$store.state.request.label;
+ method: {
+ get() {
+ return this.$store.state.request.method;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "method"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "label" });
- }
- },
- auth: {
- get() {
- return this.$store.state.request.auth;
+ path: {
+ get() {
+ return this.$store.state.request.path;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "path"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "auth" });
- }
- },
- httpUser: {
- get() {
- return this.$store.state.request.httpUser;
+ label: {
+ get() {
+ return this.$store.state.request.label;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "label"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "httpUser" });
- }
- },
- httpPassword: {
- get() {
- return this.$store.state.request.httpPassword;
+ auth: {
+ get() {
+ return this.$store.state.request.auth;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "auth"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "httpPassword" });
- }
- },
- bearerToken: {
- get() {
- return this.$store.state.request.bearerToken;
+ httpUser: {
+ get() {
+ return this.$store.state.request.httpUser;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "httpUser"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "bearerToken" });
- }
- },
- tokens: {
- get() {
- return this.$store.state.oauth2.tokens;
+ httpPassword: {
+ get() {
+ return this.$store.state.request.httpPassword;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "httpPassword"});
+ }
},
- set(value) {
- this.$store.commit("setOAuth2", { value, attribute: "tokens" });
- }
- },
- tokenReqs: {
- get() {
- return this.$store.state.oauth2.tokenReqs;
+ bearerToken: {
+ get() {
+ return this.$store.state.request.bearerToken;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "bearerToken"});
+ }
},
- set(value) {
- this.$store.commit("setOAuth2", { value, attribute: "tokenReqs" });
- }
- },
- tokenReqSelect: {
- get() {
- return this.$store.state.oauth2.tokenReqSelect;
+ tokens: {
+ get() {
+ return this.$store.state.oauth2.tokens;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {value, attribute: "tokens"});
+ }
},
- set(value) {
- this.$store.commit("setOAuth2", { value, attribute: "tokenReqSelect" });
- }
- },
- tokenReqName: {
- get() {
- return this.$store.state.oauth2.tokenReqName;
+ tokenReqs: {
+ get() {
+ return this.$store.state.oauth2.tokenReqs;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {value, attribute: "tokenReqs"});
+ }
},
- set(value) {
- this.$store.commit("setOAuth2", { value, attribute: "tokenReqName" });
- }
- },
- accessTokenName: {
- get() {
- return this.$store.state.oauth2.accessTokenName;
- },
- set(value) {
- this.$store.commit("setOAuth2", {
- value,
- attribute: "accessTokenName"
- });
- }
- },
- oidcDiscoveryUrl: {
- get() {
- return this.$store.state.oauth2.oidcDiscoveryUrl;
- },
- set(value) {
- this.$store.commit("setOAuth2", {
- value,
- attribute: "oidcDiscoveryUrl"
- });
- }
- },
- authUrl: {
- get() {
- return this.$store.state.oauth2.authUrl;
+ tokenReqSelect: {
+ get() {
+ return this.$store.state.oauth2.tokenReqSelect;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {value, attribute: "tokenReqSelect"});
+ }
},
- set(value) {
- this.$store.commit("setOAuth2", { value, attribute: "authUrl" });
- }
- },
- accessTokenUrl: {
- get() {
- return this.$store.state.oauth2.accessTokenUrl;
+ tokenReqName: {
+ get() {
+ return this.$store.state.oauth2.tokenReqName;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {value, attribute: "tokenReqName"});
+ }
},
- set(value) {
- this.$store.commit("setOAuth2", { value, attribute: "accessTokenUrl" });
- }
- },
- clientId: {
- get() {
- return this.$store.state.oauth2.clientId;
+ accessTokenName: {
+ get() {
+ return this.$store.state.oauth2.accessTokenName;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {
+ value,
+ attribute: "accessTokenName"
+ });
+ }
},
- set(value) {
- this.$store.commit("setOAuth2", { value, attribute: "clientId" });
- }
- },
- scope: {
- get() {
- return this.$store.state.oauth2.scope;
+ oidcDiscoveryUrl: {
+ get() {
+ return this.$store.state.oauth2.oidcDiscoveryUrl;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {
+ value,
+ attribute: "oidcDiscoveryUrl"
+ });
+ }
},
- set(value) {
- this.$store.commit("setOAuth2", { value, attribute: "scope" });
- }
- },
- state: {
- get() {
- return this.$store.state.oauth2.state;
+ authUrl: {
+ get() {
+ return this.$store.state.oauth2.authUrl;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {value, attribute: "authUrl"});
+ }
},
- set(value) {
- this.$store.commit("setOAuth2", { value, attribute: "state" });
- }
- },
- headers: {
- get() {
- return this.$store.state.request.headers;
+ accessTokenUrl: {
+ get() {
+ return this.$store.state.oauth2.accessTokenUrl;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {value, attribute: "accessTokenUrl"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "headers" });
- }
- },
- params: {
- get() {
- return this.$store.state.request.params;
+ clientId: {
+ get() {
+ return this.$store.state.oauth2.clientId;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {value, attribute: "clientId"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "params" });
- }
- },
- bodyParams: {
- get() {
- return this.$store.state.request.bodyParams;
+ scope: {
+ get() {
+ return this.$store.state.oauth2.scope;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {value, attribute: "scope"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "bodyParams" });
- }
- },
- rawParams: {
- get() {
- return this.$store.state.request.rawParams;
+ state: {
+ get() {
+ return this.$store.state.oauth2.state;
+ },
+ set(value) {
+ this.$store.commit("setOAuth2", {value, attribute: "state"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "rawParams" });
- }
- },
- rawInput: {
- get() {
- return this.$store.state.request.rawInput;
+ headers: {
+ get() {
+ return this.$store.state.request.headers;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "headers"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "rawInput" });
- }
- },
- requestType: {
- get() {
- return this.$store.state.request.requestType;
+ params: {
+ get() {
+ return this.$store.state.request.params;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "params"});
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "requestType" });
- }
- },
- contentType: {
- get() {
- return this.$store.state.request.contentType;
+ bodyParams: {
+ get() {
+ return this.$store.state.request.bodyParams;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "bodyParams"});
+ }
+ },
+ rawParams: {
+ get() {
+ return this.$store.state.request.rawParams;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "rawParams"});
+ }
+ },
+ rawInput: {
+ get() {
+ return this.$store.state.request.rawInput;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "rawInput"});
+ }
+ },
+ requestType: {
+ get() {
+ return this.$store.state.request.requestType;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "requestType"});
+ }
+ },
+ contentType: {
+ get() {
+ return this.$store.state.request.contentType;
+ },
+ set(value) {
+ this.$store.commit("setState", {value, attribute: "contentType"});
+ }
+ },
+ passwordFieldType: {
+ get() {
+ return this.$store.state.request.passwordFieldType;
+ },
+ set(value) {
+ this.$store.commit("setState", {
+ value,
+ attribute: "passwordFieldType"
+ });
+ }
},
- set(value) {
- this.$store.commit("setState", { value, attribute: "contentType" });
- }
- },
- passwordFieldType: {
- get() {
- return this.$store.state.request.passwordFieldType;
- },
- set(value) {
- this.$store.commit("setState", {
- value,
- attribute: "passwordFieldType"
- });
- }
- },
- selectedRequest() {
- return this.$store.state.postwoman.selectedRequest;
- },
- editingRequest() {
- return this.$store.state.postwoman.editingRequest;
- },
- requestName() {
- return this.label;
- },
- statusCategory() {
- return findStatusGroup(this.response.status);
- },
- isValidURL() {
- if (this.showPreRequestScript) {
- // we cannot determine if a URL is valid because the full string is not known ahead of time
- return true;
- }
- const protocol = "^(https?:\\/\\/)?";
- const validIP = new RegExp(
- protocol +
+ selectedRequest() {
+ return this.$store.state.postwoman.selectedRequest;
+ },
+ editingRequest() {
+ return this.$store.state.postwoman.editingRequest;
+ },
+ requestName() {
+ return this.label;
+ },
+ statusCategory() {
+ return findStatusGroup(this.response.status);
+ },
+ isValidURL() {
+ if (this.showPreRequestScript) {
+ // we cannot determine if a URL is valid because the full string is not known ahead of time
+ return true;
+ }
+ const protocol = "^(https?:\\/\\/)?";
+ const validIP = new RegExp(
+ protocol +
"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
- );
- const validHostname = new RegExp(
- protocol +
+ );
+ const validHostname = new RegExp(
+ protocol +
"(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9/])$"
- );
- return validIP.test(this.url) || validHostname.test(this.url);
- },
- hasRequestBody() {
- return ["POST", "PUT", "PATCH"].includes(this.method);
- },
- pathName() {
- return this.path.match(/^([^?]*)\??/)[1];
- },
- rawRequestBody() {
- const { bodyParams } = this;
- if (this.contentType === "application/json") {
- try {
- const obj = JSON.parse(
- `{${bodyParams
- .filter(({ key }) => !!key)
- .map(
- ({ key, value }) => `
+ );
+ return validIP.test(this.url) || validHostname.test(this.url);
+ },
+ hasRequestBody() {
+ return ["POST", "PUT", "PATCH"].includes(this.method);
+ },
+ pathName() {
+ return this.path.match(/^([^?]*)\??/)[1];
+ },
+ rawRequestBody() {
+ const {bodyParams} = this;
+ if (this.contentType === "application/json") {
+ try {
+ const obj = JSON.parse(
+ `{${bodyParams
+ .filter(({key}) => !!key)
+ .map(
+ ({key, value}) => `
"${key}": "${value}"
`
- )
- .join()}}`
- );
- return JSON.stringify(obj);
- } catch (ex) {
- return "invalid";
+ )
+ .join()}}`
+ );
+ return JSON.stringify(obj);
+ } catch (ex) {
+ return "invalid";
+ }
+ } else {
+ return bodyParams
+ .filter(({key}) => !!key)
+ .map(({key, value}) => `${key}=${encodeURIComponent(value)}`)
+ .join("&");
}
- } else {
- return bodyParams
- .filter(({ key }) => !!key)
- .map(({ key, value }) => `${key}=${encodeURIComponent(value)}`)
+ },
+ headerString() {
+ const result = this.headers
+ .filter(({key}) => !!key)
+ .map(({key, value}) => `${key}: ${value}`)
+ .join(",\n");
+ return result === "" ? "" : `${result}`;
+ },
+ queryString() {
+ const result = this.params
+ .filter(({key}) => !!key)
+ .map(({key, value}) => `${key}=${encodeURIComponent(value)}`)
.join("&");
- }
- },
- headerString() {
- const result = this.headers
- .filter(({ key }) => !!key)
- .map(({ key, value }) => `${key}: ${value}`)
- .join(",\n");
- return result === "" ? "" : `${result}`;
- },
- queryString() {
- const result = this.params
- .filter(({ key }) => !!key)
- .map(({ key, value }) => `${key}=${encodeURIComponent(value)}`)
- .join("&");
- return result === "" ? "" : `?${result}`;
- },
- responseType() {
- return (this.response.headers["content-type"] || "")
- .split(";")[0]
- .toLowerCase();
- },
- requestCode() {
- if (this.requestType === "JavaScript XHR") {
- const requestString = [];
- requestString.push("const xhr = new XMLHttpRequest()");
- const user =
- this.auth === "Basic Auth" ? "'" + this.httpUser + "'" : null;
- const pswd =
- this.auth === "Basic Auth" ? "'" + this.httpPassword + "'" : null;
- requestString.push(
- "xhr.open('" +
+ return result === "" ? "" : `?${result}`;
+ },
+ responseType() {
+ return (this.response.headers["content-type"] || "")
+ .split(";")[0]
+ .toLowerCase();
+ },
+ requestCode() {
+ if (this.requestType === "JavaScript XHR") {
+ const requestString = [];
+ requestString.push("const xhr = new XMLHttpRequest()");
+ const user =
+ this.auth === "Basic Auth" ? "'" + this.httpUser + "'" : null;
+ const pswd =
+ this.auth === "Basic Auth" ? "'" + this.httpPassword + "'" : null;
+ requestString.push(
+ "xhr.open('" +
this.method +
"', '" +
this.url +
@@ -1789,976 +1849,977 @@ export default {
", " +
pswd +
")"
- );
- if (this.auth === "Bearer Token" || this.auth === "OAuth 2.0") {
- requestString.push(
- "xhr.setRequestHeader('Authorization', 'Bearer " +
- this.bearerToken +
- "')"
);
- }
- if (this.headers) {
- this.headers.forEach(element => {
+ if (this.auth === "Bearer Token" || this.auth === "OAuth 2.0") {
requestString.push(
- "xhr.setRequestHeader('" +
+ "xhr.setRequestHeader('Authorization', 'Bearer " +
+ this.bearerToken +
+ "')"
+ );
+ }
+ if (this.headers) {
+ this.headers.forEach(element => {
+ requestString.push(
+ "xhr.setRequestHeader('" +
element.key +
"', '" +
element.value +
"')"
+ );
+ });
+ }
+ if (["POST", "PUT", "PATCH"].includes(this.method)) {
+ const requestBody = this.rawInput
+ ? this.rawParams
+ : this.rawRequestBody;
+ requestString.push(
+ "xhr.setRequestHeader('Content-Length', " + requestBody.length + ")"
);
- });
- }
- if (["POST", "PUT", "PATCH"].includes(this.method)) {
- const requestBody = this.rawInput
- ? this.rawParams
- : this.rawRequestBody;
- requestString.push(
- "xhr.setRequestHeader('Content-Length', " + requestBody.length + ")"
- );
- requestString.push(
- "xhr.setRequestHeader('Content-Type', '" +
+ requestString.push(
+ "xhr.setRequestHeader('Content-Type', '" +
this.contentType +
"; charset=utf-8')"
+ );
+ requestString.push("xhr.send(" + requestBody + ")");
+ } else {
+ requestString.push("xhr.send()");
+ }
+ return requestString.join("\n");
+ } else if (this.requestType === "Fetch") {
+ const requestString = [];
+ let headers = [];
+ requestString.push(
+ 'fetch("' + this.url + this.pathName + this.queryString + '", {\n'
);
- requestString.push("xhr.send(" + requestBody + ")");
- } else {
- requestString.push("xhr.send()");
- }
- return requestString.join("\n");
- } else if (this.requestType === "Fetch") {
- const requestString = [];
- let headers = [];
- requestString.push(
- 'fetch("' + this.url + this.pathName + this.queryString + '", {\n'
- );
- requestString.push(' method: "' + this.method + '",\n');
- if (this.auth === "Basic Auth") {
- const basic = this.httpUser + ":" + this.httpPassword;
- headers.push(
- ' "Authorization": "Basic ' +
+ requestString.push(' method: "' + this.method + '",\n');
+ if (this.auth === "Basic Auth") {
+ const basic = this.httpUser + ":" + this.httpPassword;
+ headers.push(
+ ' "Authorization": "Basic ' +
window.btoa(unescape(encodeURIComponent(basic))) +
'",\n'
- );
- } else if (this.auth === "Bearer Token" || this.auth === "OAuth 2.0") {
- headers.push(
- ' "Authorization": "Bearer ' + this.bearerToken + '",\n'
- );
- }
- if (["POST", "PUT", "PATCH"].includes(this.method)) {
- const requestBody = this.rawInput
- ? this.rawParams
- : this.rawRequestBody;
- requestString.push(" body: " + requestBody + ",\n");
- headers.push(' "Content-Length": ' + requestBody.length + ",\n");
- headers.push(
- ' "Content-Type": "' + this.contentType + '; charset=utf-8",\n'
- );
- }
- if (this.headers) {
- this.headers.forEach(element => {
+ );
+ } else if (this.auth === "Bearer Token" || this.auth === "OAuth 2.0") {
headers.push(
- ' "' + element.key + '": "' + element.value + '",\n'
+ ' "Authorization": "Bearer ' + this.bearerToken + '",\n'
);
- });
- }
- headers = headers.join("").slice(0, -2);
- requestString.push(" headers: {\n" + headers + "\n },\n");
- requestString.push(' credentials: "same-origin"\n');
- requestString.push("}).then(function(response) {\n");
- requestString.push(" response.status\n");
- requestString.push(" response.statusText\n");
- requestString.push(" response.headers\n");
- requestString.push(" response.url\n\n");
- requestString.push(" return response.text()\n");
- requestString.push("}).catch(function(error) {\n");
- requestString.push(" error.message\n");
- requestString.push("})");
- return requestString.join("");
- } else if (this.requestType === "cURL") {
- const requestString = [];
- requestString.push("curl -X " + this.method + " \n");
- requestString.push(
- " '" + this.url + this.pathName + this.queryString + "' \n"
- );
- if (this.auth === "Basic Auth") {
- const basic = this.httpUser + ":" + this.httpPassword;
+ }
+ if (["POST", "PUT", "PATCH"].includes(this.method)) {
+ const requestBody = this.rawInput
+ ? this.rawParams
+ : this.rawRequestBody;
+ requestString.push(" body: " + requestBody + ",\n");
+ headers.push(' "Content-Length": ' + requestBody.length + ",\n");
+ headers.push(
+ ' "Content-Type": "' + this.contentType + '; charset=utf-8",\n'
+ );
+ }
+ if (this.headers) {
+ this.headers.forEach(element => {
+ headers.push(
+ ' "' + element.key + '": "' + element.value + '",\n'
+ );
+ });
+ }
+ headers = headers.join("").slice(0, -2);
+ requestString.push(" headers: {\n" + headers + "\n },\n");
+ requestString.push(' credentials: "same-origin"\n');
+ requestString.push("}).then(function(response) {\n");
+ requestString.push(" response.status\n");
+ requestString.push(" response.statusText\n");
+ requestString.push(" response.headers\n");
+ requestString.push(" response.url\n\n");
+ requestString.push(" return response.text()\n");
+ requestString.push("}).catch(function(error) {\n");
+ requestString.push(" error.message\n");
+ requestString.push("})");
+ return requestString.join("");
+ } else if (this.requestType === "cURL") {
+ const requestString = [];
+ requestString.push("curl -X " + this.method + " \n");
requestString.push(
- " -H 'Authorization: Basic " +
+ " '" + this.url + this.pathName + this.queryString + "' \n"
+ );
+ if (this.auth === "Basic Auth") {
+ const basic = this.httpUser + ":" + this.httpPassword;
+ requestString.push(
+ " -H 'Authorization: Basic " +
window.btoa(unescape(encodeURIComponent(basic))) +
"' \n"
- );
- } else if (this.auth === "Bearer Token" || this.auth === "OAuth 2.0") {
- requestString.push(
- " -H 'Authorization: Bearer " + this.bearerToken + "' \n"
- );
- }
- if (this.headers) {
- this.headers.forEach(element => {
+ );
+ } else if (this.auth === "Bearer Token" || this.auth === "OAuth 2.0") {
requestString.push(
- " -H '" + element.key + ": " + element.value + "' \n"
+ " -H 'Authorization: Bearer " + this.bearerToken + "' \n"
);
- });
- }
- if (["POST", "PUT", "PATCH"].includes(this.method)) {
- const requestBody = this.rawInput
- ? this.rawParams
- : this.rawRequestBody;
- requestString.push(
- " -H 'Content-Length: " + requestBody.length + "' \n"
- );
- requestString.push(
- " -H 'Content-Type: " + this.contentType + "; charset=utf-8' \n"
- );
- requestString.push(" -d '" + requestBody + "' \n");
+ }
+ if (this.headers) {
+ this.headers.forEach(element => {
+ requestString.push(
+ " -H '" + element.key + ": " + element.value + "' \n"
+ );
+ });
+ }
+ if (["POST", "PUT", "PATCH"].includes(this.method)) {
+ const requestBody = this.rawInput
+ ? this.rawParams
+ : this.rawRequestBody;
+ requestString.push(
+ " -H 'Content-Length: " + requestBody.length + "' \n"
+ );
+ requestString.push(
+ " -H 'Content-Type: " + this.contentType + "; charset=utf-8' \n"
+ );
+ requestString.push(" -d '" + requestBody + "' \n");
+ }
+ return requestString.join("").slice(0, -2);
}
- return requestString.join("").slice(0, -2);
- }
- },
- tokenReqDetails() {
- const details = {
- oidcDiscoveryUrl: this.oidcDiscoveryUrl,
- authUrl: this.authUrl,
- accessTokenUrl: this.accessTokenUrl,
- clientId: this.clientId,
- scope: this.scope
- };
- return JSON.stringify(details, null, 2);
- }
- },
- methods: {
- checkCollections() {
- const checkCollectionAvailability =
- this.$store.state.postwoman.collections &&
- this.$store.state.postwoman.collections.length > 0;
- return checkCollectionAvailability;
- },
- scrollInto(view) {
- this.$refs[view].$el.scrollIntoView({
- behavior: "smooth"
- });
- },
- handleUseHistory({
- label,
- method,
- url,
- path,
- usesScripts,
- preRequestScript
- }) {
- this.label = label;
- this.method = method;
- this.url = url;
- this.path = path;
- this.showPreRequestScript = usesScripts;
- this.preRequestScript = preRequestScript;
- this.scrollInto("request");
- },
- getVariablesFromPreRequestScript() {
- if (!this.preRequestScript) {
- return {};
+ },
+ tokenReqDetails() {
+ const details = {
+ oidcDiscoveryUrl: this.oidcDiscoveryUrl,
+ authUrl: this.authUrl,
+ accessTokenUrl: this.accessTokenUrl,
+ clientId: this.clientId,
+ scope: this.scope
+ };
+ return JSON.stringify(details, null, 2);
}
- return getEnvironmentVariablesFromScript(this.preRequestScript);
},
- async makeRequest(auth, headers, requestBody, preRequestScript) {
- const requestOptions = {
- method: this.method,
- url: this.url + this.pathName + this.queryString,
- auth,
- headers,
- data: requestBody ? requestBody.toString() : null,
- credentials: true
- };
- if (preRequestScript) {
- const environmentVariables = getEnvironmentVariablesFromScript(
- preRequestScript
- );
- requestOptions.url = parseTemplateString(
- requestOptions.url,
- environmentVariables
- );
- requestOptions.data = parseTemplateString(
- requestOptions.data,
- environmentVariables
- );
- for (let k in requestOptions.headers) {
- const kParsed = parseTemplateString(k, environmentVariables);
- const valParsed = parseTemplateString(
- requestOptions.headers[k],
+ methods: {
+ checkCollections() {
+ const checkCollectionAvailability =
+ this.$store.state.postwoman.collections &&
+ this.$store.state.postwoman.collections.length > 0;
+ return checkCollectionAvailability;
+ },
+ scrollInto(view) {
+ this.$refs[view].$el.scrollIntoView({
+ behavior: "smooth"
+ });
+ },
+ handleUseHistory({
+ label,
+ method,
+ url,
+ path,
+ usesScripts,
+ preRequestScript
+ }) {
+ this.label = label;
+ this.method = method;
+ this.url = url;
+ this.path = path;
+ this.showPreRequestScript = usesScripts;
+ this.preRequestScript = preRequestScript;
+ this.scrollInto("request");
+ },
+ getVariablesFromPreRequestScript() {
+ if (!this.preRequestScript) {
+ return {};
+ }
+ return getEnvironmentVariablesFromScript(this.preRequestScript);
+ },
+ async makeRequest(auth, headers, requestBody, preRequestScript) {
+ const requestOptions = {
+ method: this.method,
+ url: this.url + this.pathName + this.queryString,
+ auth,
+ headers,
+ data: requestBody ? requestBody.toString() : null,
+ credentials: true
+ };
+ if (preRequestScript) {
+ const environmentVariables = getEnvironmentVariablesFromScript(
+ preRequestScript
+ );
+ requestOptions.url = parseTemplateString(
+ requestOptions.url,
environmentVariables
);
- delete requestOptions.headers[k];
- requestOptions.headers[kParsed] = valParsed;
+ requestOptions.data = parseTemplateString(
+ requestOptions.data,
+ environmentVariables
+ );
+ for (let k in requestOptions.headers) {
+ const kParsed = parseTemplateString(k, environmentVariables);
+ const valParsed = parseTemplateString(
+ requestOptions.headers[k],
+ environmentVariables
+ );
+ delete requestOptions.headers[k];
+ requestOptions.headers[kParsed] = valParsed;
+ }
+ }
+ if (typeof requestOptions.data === "string") {
+ requestOptions.data = parseTemplateString(requestOptions.data);
}
- }
- if (typeof requestOptions.data === "string") {
- requestOptions.data = parseTemplateString(requestOptions.data);
- }
- return await sendNetworkRequest(requestOptions, this.$store);
- },
- async sendRequest() {
- this.$toast.clear();
- this.scrollInto("response");
+ return await sendNetworkRequest(requestOptions, this.$store);
+ },
+ async sendRequest() {
+ this.$toast.clear();
+ this.scrollInto("response");
- if (!this.isValidURL) {
- this.$toast.error(this.$t("url_invalid_format"), {
- icon: "error"
- });
- return;
- }
+ if (!this.isValidURL) {
+ this.$toast.error(this.$t("url_invalid_format"), {
+ icon: "error"
+ });
+ return;
+ }
- // Start showing the loading bar as soon as possible.
- // The nuxt axios module will hide it when the request is made.
- this.$nuxt.$loading.start();
+ // Start showing the loading bar as soon as possible.
+ // The nuxt axios module will hide it when the request is made.
+ this.$nuxt.$loading.start();
- if (this.$refs.response.$el.classList.contains("hidden")) {
- this.$refs.response.$el.classList.toggle("hidden");
- }
- this.previewEnabled = false;
- this.response.status = this.$t("fetching");
- this.response.body = this.$t("loading");
+ if (this.$refs.response.$el.classList.contains("hidden")) {
+ this.$refs.response.$el.classList.toggle("hidden");
+ }
+ this.previewEnabled = false;
+ this.response.status = this.$t("fetching");
+ this.response.body = this.$t("loading");
- const auth =
- this.auth === "Basic Auth"
- ? {
+ const auth =
+ this.auth === "Basic Auth"
+ ? {
username: this.httpUser,
password: this.httpPassword
}
- : null;
-
- let headers = {};
- let headersObject = {};
-
- Object.keys(headers).forEach(id => {
- headersObject[headers[id].key] = headers[id].value;
- });
- headers = headersObject;
+ : null;
- // If the request has a body, we want to ensure Content-Length and
- // Content-Type are sent.
- let requestBody;
- if (this.hasRequestBody) {
- requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;
+ let headers = {};
+ let headersObject = {};
- Object.assign(headers, {
- //'Content-Length': requestBody.length,
- "Content-Type": `${this.contentType}; charset=utf-8`
+ Object.keys(headers).forEach(id => {
+ headersObject[headers[id].key] = headers[id].value;
});
- }
-
- // If the request uses a token for auth, we want to make sure it's sent here.
- if (this.auth === "Bearer Token" || this.auth === "OAuth 2.0")
- headers["Authorization"] = `Bearer ${this.bearerToken}`;
+ headers = headersObject;
- headers = Object.assign(
- // Clone the app headers object first, we don't want to
- // mutate it with the request headers added by default.
- Object.assign({}, this.headers)
+ // If the request has a body, we want to ensure Content-Length and
+ // Content-Type are sent.
+ let requestBody;
+ if (this.hasRequestBody) {
+ requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;
- // We make our temporary headers object the source so
- // that you can override the added headers if you
- // specify them.
- // headers
- );
+ Object.assign(headers, {
+ //'Content-Length': requestBody.length,
+ "Content-Type": `${this.contentType}; charset=utf-8`
+ });
+ }
- Object.keys(headers).forEach(id => {
- headersObject[headers[id].key] = headers[id].value;
- });
- headers = headersObject;
+ // If the request uses a token for auth, we want to make sure it's sent here.
+ if (this.auth === "Bearer Token" || this.auth === "OAuth 2.0")
+ headers["Authorization"] = `Bearer ${this.bearerToken}`;
- try {
- const startTime = Date.now();
+ headers = Object.assign(
+ // Clone the app headers object first, we don't want to
+ // mutate it with the request headers added by default.
+ Object.assign({}, this.headers)
- const payload = await this.makeRequest(
- auth,
- headers,
- requestBody,
- this.showPreRequestScript && this.preRequestScript
+ // We make our temporary headers object the source so
+ // that you can override the added headers if you
+ // specify them.
+ // headers
);
- const duration = Date.now() - startTime;
- this.$toast.info(this.$t("finished_in", { duration }), {
- icon: "done"
+ Object.keys(headers).forEach(id => {
+ headersObject[headers[id].key] = headers[id].value;
});
+ headers = headersObject;
- (() => {
- const status = (this.response.status = payload.status);
- const headers = (this.response.headers = payload.headers);
+ try {
+ const startTime = Date.now();
- // We don't need to bother parsing JSON, axios already handles it for us!
- const body = (this.response.body = payload.data);
+ const payload = await this.makeRequest(
+ auth,
+ headers,
+ requestBody,
+ this.showPreRequestScript && this.preRequestScript
+ );
- const date = new Date().toLocaleDateString();
- const time = new Date().toLocaleTimeString();
+ const duration = Date.now() - startTime;
+ this.$toast.info(this.$t("finished_in", {duration}), {
+ icon: "done"
+ });
- // Addition of an entry to the history component.
- const entry = {
- label: this.requestName,
- status,
- date,
- time,
- method: this.method,
- url: this.url,
- path: this.path,
- usesScripts: Boolean(this.preRequestScript),
- preRequestScript: this.preRequestScript,
- duration,
- star: false
- };
- this.$refs.historyComponent.addEntry(entry);
- })();
- } catch (error) {
- console.error(error);
- if (error.response) {
- this.response.headers = error.response.headers;
- this.response.status = error.response.status;
- this.response.body = error.response.data;
+ (() => {
+ const status = (this.response.status = payload.status);
+ const headers = (this.response.headers = payload.headers);
- // Addition of an entry to the history component.
- const entry = {
- label: this.requestName,
- status: this.response.status,
- date: new Date().toLocaleDateString(),
- time: new Date().toLocaleTimeString(),
- method: this.method,
- url: this.url,
- path: this.path,
- usesScripts: Boolean(this.preRequestScript),
- preRequestScript: this.preRequestScript
- };
- this.$refs.historyComponent.addEntry(entry);
- return;
- } else {
- this.response.status = error.message;
- this.response.body = `${error}. ${this.$t("check_console_details")}`;
- this.$toast.error(`${error} ${this.$t("f12_details")}`, {
- icon: "error"
- });
- if (!this.$store.state.postwoman.settings.PROXY_ENABLED) {
- this.$toast.info(this.$t("enable_proxy"), {
- icon: "help",
- duration: 8000,
- action: {
- text: "Settings",
- onClick: (e, toastObject) => {
- this.$router.push({ path: "/settings" });
- }
- }
+ // We don't need to bother parsing JSON, axios already handles it for us!
+ const body = (this.response.body = payload.data);
+
+ const date = new Date().toLocaleDateString();
+ const time = new Date().toLocaleTimeString();
+
+ // Addition of an entry to the history component.
+ const entry = {
+ label: this.requestName,
+ status,
+ date,
+ time,
+ method: this.method,
+ url: this.url,
+ path: this.path,
+ usesScripts: Boolean(this.preRequestScript),
+ preRequestScript: this.preRequestScript,
+ duration,
+ star: false
+ };
+ this.$refs.historyComponent.addEntry(entry);
+ })();
+ } catch (error) {
+ console.error(error);
+ if (error.response) {
+ this.response.headers = error.response.headers;
+ this.response.status = error.response.status;
+ this.response.body = error.response.data;
+
+ // Addition of an entry to the history component.
+ const entry = {
+ label: this.requestName,
+ status: this.response.status,
+ date: new Date().toLocaleDateString(),
+ time: new Date().toLocaleTimeString(),
+ method: this.method,
+ url: this.url,
+ path: this.path,
+ usesScripts: Boolean(this.preRequestScript),
+ preRequestScript: this.preRequestScript
+ };
+ this.$refs.historyComponent.addEntry(entry);
+ return;
+ } else {
+ this.response.status = error.message;
+ this.response.body = `${error}. ${this.$t("check_console_details")}`;
+ this.$toast.error(`${error} ${this.$t("f12_details")}`, {
+ icon: "error"
});
+ if (!this.$store.state.postwoman.settings.PROXY_ENABLED) {
+ this.$toast.info(this.$t("enable_proxy"), {
+ icon: "help",
+ duration: 8000,
+ action: {
+ text: "Settings",
+ onClick: (e, toastObject) => {
+ this.$router.push({path: "/settings"});
+ }
+ }
+ });
+ }
}
}
- }
- },
- getQueryStringFromPath() {
- let queryString,
- pathParsed = url.parse(this.path);
- return (queryString = pathParsed.query ? pathParsed.query : "");
- },
- queryStringToArray(queryString) {
- let queryParsed = querystring.parse(queryString);
- return Object.keys(queryParsed).map(key => ({
- key: key,
- value: queryParsed[key]
- }));
- },
- pathInputHandler() {
- let queryString = this.getQueryStringFromPath(),
- params = this.queryStringToArray(queryString);
+ },
+ getQueryStringFromPath() {
+ let queryString,
+ pathParsed = url.parse(this.path);
+ return (queryString = pathParsed.query ? pathParsed.query : "");
+ },
+ queryStringToArray(queryString) {
+ let queryParsed = querystring.parse(queryString);
+ return Object.keys(queryParsed).map(key => ({
+ key: key,
+ value: queryParsed[key]
+ }));
+ },
+ pathInputHandler() {
+ let queryString = this.getQueryStringFromPath(),
+ params = this.queryStringToArray(queryString);
- this.paramsWatchEnabled = false;
- this.params = params;
- },
- addRequestHeader() {
- this.$store.commit("addHeaders", {
- key: "",
- value: ""
- });
- return false;
- },
- removeRequestHeader(index) {
- // .slice() gives us an entirely new array rather than giving us just the reference
- const oldHeaders = this.headers.slice();
+ this.paramsWatchEnabled = false;
+ this.params = params;
+ },
+ addRequestHeader() {
+ this.$store.commit("addHeaders", {
+ key: "",
+ value: ""
+ });
+ return false;
+ },
+ removeRequestHeader(index) {
+ // .slice() gives us an entirely new array rather than giving us just the reference
+ const oldHeaders = this.headers.slice();
- this.$store.commit("removeHeaders", index);
- this.$toast.error(this.$t("deleted"), {
- icon: "delete",
- action: {
- text: this.$t("undo"),
- onClick: (e, toastObject) => {
- this.headers = oldHeaders;
- toastObject.remove();
+ this.$store.commit("removeHeaders", index);
+ this.$toast.error(this.$t("deleted"), {
+ icon: "delete",
+ action: {
+ text: this.$t("undo"),
+ onClick: (e, toastObject) => {
+ this.headers = oldHeaders;
+ toastObject.remove();
+ }
}
- }
- });
- },
- addRequestParam() {
- this.$store.commit("addParams", { key: "", value: "" });
- return false;
- },
- removeRequestParam(index) {
- // .slice() gives us an entirely new array rather than giving us just the reference
- const oldParams = this.params.slice();
+ });
+ },
+ addRequestParam() {
+ this.$store.commit("addParams", {key: "", value: ""});
+ return false;
+ },
+ removeRequestParam(index) {
+ // .slice() gives us an entirely new array rather than giving us just the reference
+ const oldParams = this.params.slice();
- this.$store.commit("removeParams", index);
- this.$toast.error(this.$t("deleted"), {
- icon: "delete",
- action: {
- text: this.$t("undo"),
- onClick: (e, toastObject) => {
- this.params = oldParams;
- toastObject.remove();
+ this.$store.commit("removeParams", index);
+ this.$toast.error(this.$t("deleted"), {
+ icon: "delete",
+ action: {
+ text: this.$t("undo"),
+ onClick: (e, toastObject) => {
+ this.params = oldParams;
+ toastObject.remove();
+ }
}
- }
- });
- },
- addRequestBodyParam() {
- this.$store.commit("addBodyParams", { key: "", value: "" });
- return false;
- },
- removeRequestBodyParam(index) {
- // .slice() gives us an entirely new array rather than giving us just the reference
- const oldBodyParams = this.bodyParams.slice();
+ });
+ },
+ addRequestBodyParam() {
+ this.$store.commit("addBodyParams", {key: "", value: ""});
+ return false;
+ },
+ removeRequestBodyParam(index) {
+ // .slice() gives us an entirely new array rather than giving us just the reference
+ const oldBodyParams = this.bodyParams.slice();
- this.$store.commit("removeBodyParams", index);
- this.$toast.error(this.$t("deleted"), {
- icon: "delete",
- action: {
- text: this.$t("undo"),
- onClick: (e, toastObject) => {
- this.bodyParams = oldBodyParams;
- toastObject.remove();
+ this.$store.commit("removeBodyParams", index);
+ this.$toast.error(this.$t("deleted"), {
+ icon: "delete",
+ action: {
+ text: this.$t("undo"),
+ onClick: (e, toastObject) => {
+ this.bodyParams = oldBodyParams;
+ toastObject.remove();
+ }
}
+ });
+ },
+ copyRequest() {
+ if (navigator.share) {
+ let time = new Date().toLocaleTimeString();
+ let date = new Date().toLocaleDateString();
+ navigator
+ .share({
+ title: `Postwoman`,
+ text: `Postwoman • API request builder at ${time} on ${date}`,
+ url: window.location.href
+ })
+ .then(() => {
+ })
+ .catch(console.error);
+ } else {
+ const dummy = document.createElement("input");
+ document.body.appendChild(dummy);
+ dummy.value = window.location.href;
+ dummy.select();
+ document.execCommand("copy");
+ document.body.removeChild(dummy);
+ this.$refs.copyRequest.innerHTML = this.doneButton;
+ this.$toast.info(this.$t("copied_to_clipboard"), {
+ icon: "done"
+ });
+ setTimeout(
+ () => (this.$refs.copyRequest.innerHTML = this.copyButton),
+ 1000
+ );
}
- });
- },
- copyRequest() {
- if (navigator.share) {
- let time = new Date().toLocaleTimeString();
- let date = new Date().toLocaleDateString();
- navigator
- .share({
- title: `Postwoman`,
- text: `Postwoman • API request builder at ${time} on ${date}`,
- url: window.location.href
- })
- .then(() => {})
- .catch(console.error);
- } else {
- const dummy = document.createElement("input");
- document.body.appendChild(dummy);
- dummy.value = window.location.href;
- dummy.select();
+ },
+ copyRequestCode() {
+ this.$refs.copyRequestCode.innerHTML = this.doneButton;
+ this.$toast.success(this.$t("copied_to_clipboard"), {
+ icon: "done"
+ });
+ this.$refs.generatedCode.select();
document.execCommand("copy");
- document.body.removeChild(dummy);
- this.$refs.copyRequest.innerHTML = this.doneButton;
- this.$toast.info(this.$t("copied_to_clipboard"), {
+ setTimeout(
+ () => (this.$refs.copyRequestCode.innerHTML = this.copyButton),
+ 1000
+ );
+ },
+ ToggleExpandResponse() {
+ this.expandResponse = !this.expandResponse;
+ this.responseBodyMaxLines =
+ this.responseBodyMaxLines == Infinity ? 16 : Infinity;
+ },
+ copyResponse() {
+ this.$refs.copyResponse.innerHTML = this.doneButton;
+ this.$toast.success(this.$t("copied_to_clipboard"), {
icon: "done"
});
+ const aux = document.createElement("textarea");
+ const copy =
+ this.responseType === "application/json"
+ ? JSON.stringify(this.response.body)
+ : this.response.body;
+ aux.innerText = copy;
+ document.body.appendChild(aux);
+ aux.select();
+ document.execCommand("copy");
+ document.body.removeChild(aux);
setTimeout(
- () => (this.$refs.copyRequest.innerHTML = this.copyButton),
+ () => (this.$refs.copyResponse.innerHTML = this.copyButton),
1000
);
- }
- },
- copyRequestCode() {
- this.$refs.copyRequestCode.innerHTML = this.doneButton;
- this.$toast.success(this.$t("copied_to_clipboard"), {
- icon: "done"
- });
- this.$refs.generatedCode.select();
- document.execCommand("copy");
- setTimeout(
- () => (this.$refs.copyRequestCode.innerHTML = this.copyButton),
- 1000
- );
- },
- ToggleExpandResponse() {
- this.expandResponse = !this.expandResponse;
- this.responseBodyMaxLines =
- this.responseBodyMaxLines == Infinity ? 16 : Infinity;
- },
- copyResponse() {
- this.$refs.copyResponse.innerHTML = this.doneButton;
- this.$toast.success(this.$t("copied_to_clipboard"), {
- icon: "done"
- });
- const aux = document.createElement("textarea");
- const copy =
- this.responseType === "application/json"
- ? JSON.stringify(this.response.body)
- : this.response.body;
- aux.innerText = copy;
- document.body.appendChild(aux);
- aux.select();
- document.execCommand("copy");
- document.body.removeChild(aux);
- setTimeout(
- () => (this.$refs.copyResponse.innerHTML = this.copyButton),
- 1000
- );
- },
- downloadResponse() {
- const dataToWrite = JSON.stringify(this.response.body, null, 2);
- const file = new Blob([dataToWrite], { type: this.responseType });
- const a = document.createElement("a"),
- url = URL.createObjectURL(file);
- a.href = url;
- a.download = (
- this.url +
- this.path +
- " [" +
- this.method +
- "] on " +
- Date()
- ).replace(/\./g, "[dot]");
- document.body.appendChild(a);
- a.click();
- this.$refs.downloadResponse.innerHTML = this.doneButton;
- this.$toast.success(this.$t("download_started"), {
- icon: "done"
- });
- setTimeout(() => {
- document.body.removeChild(a);
- window.URL.revokeObjectURL(url);
- this.$refs.downloadResponse.innerHTML = this.downloadButton;
- }, 1000);
- },
- togglePreview() {
- this.previewEnabled = !this.previewEnabled;
- if (this.previewEnabled) {
- // If you want to add 'preview' support for other response types,
- // just add them here.
- if (this.responseType === "text/html") {
- // If the preview already has that URL loaded, let's not bother re-loading it all.
- if (
- this.$refs.previewFrame.getAttribute("data-previewing-url") ===
- this.url
- )
- return;
- // Use DOMParser to parse document HTML.
- const previewDocument = new DOMParser().parseFromString(
- this.response.body,
- this.responseType
- );
- // Inject <base href="..."> tag to head, to fix relative CSS/HTML paths.
- previewDocument.head.innerHTML =
- `<base href="${this.url}">` + previewDocument.head.innerHTML;
- // Finally, set the iframe source to the resulting HTML.
- this.$refs.previewFrame.srcdoc =
- previewDocument.documentElement.outerHTML;
- this.$refs.previewFrame.setAttribute("data-previewing-url", this.url);
+ },
+ downloadResponse() {
+ const dataToWrite = JSON.stringify(this.response.body, null, 2);
+ const file = new Blob([dataToWrite], {type: this.responseType});
+ const a = document.createElement("a"),
+ url = URL.createObjectURL(file);
+ a.href = url;
+ a.download = (
+ this.url +
+ this.path +
+ " [" +
+ this.method +
+ "] on " +
+ Date()
+ ).replace(/\./g, "[dot]");
+ document.body.appendChild(a);
+ a.click();
+ this.$refs.downloadResponse.innerHTML = this.doneButton;
+ this.$toast.success(this.$t("download_started"), {
+ icon: "done"
+ });
+ setTimeout(() => {
+ document.body.removeChild(a);
+ window.URL.revokeObjectURL(url);
+ this.$refs.downloadResponse.innerHTML = this.downloadButton;
+ }, 1000);
+ },
+ togglePreview() {
+ this.previewEnabled = !this.previewEnabled;
+ if (this.previewEnabled) {
+ // If you want to add 'preview' support for other response types,
+ // just add them here.
+ if (this.responseType === "text/html") {
+ // If the preview already has that URL loaded, let's not bother re-loading it all.
+ if (
+ this.$refs.previewFrame.getAttribute("data-previewing-url") ===
+ this.url
+ )
+ return;
+ // Use DOMParser to parse document HTML.
+ const previewDocument = new DOMParser().parseFromString(
+ this.response.body,
+ this.responseType
+ );
+ // Inject <base href="..."> tag to head, to fix relative CSS/HTML paths.
+ previewDocument.head.innerHTML =
+ `<base href="${this.url}">` + previewDocument.head.innerHTML;
+ // Finally, set the iframe source to the resulting HTML.
+ this.$refs.previewFrame.srcdoc =
+ previewDocument.documentElement.outerHTML;
+ this.$refs.previewFrame.setAttribute("data-previewing-url", this.url);
+ }
}
- }
- },
- setRouteQueryState() {
- const flat = key => (this[key] !== "" ? `${key}=${this[key]}&` : "");
- const deep = key => {
- const haveItems = [...this[key]].length;
- if (haveItems && this[key]["value"] !== "") {
- return `${key}=${JSON.stringify(this[key])}&`;
- } else return "";
- };
- let flats = [
- "method",
- "url",
- "path",
- !this.urlExcludes.auth ? "auth" : null,
- !this.urlExcludes.httpUser ? "httpUser" : null,
- !this.urlExcludes.httpPassword ? "httpPassword" : null,
- !this.urlExcludes.bearerToken ? "bearerToken" : null,
- "contentType"
- ]
- .filter(item => item !== null)
- .map(item => flat(item));
- let deeps = ["headers", "params"].map(item => deep(item));
- let bodyParams = this.rawInput
- ? [flat("rawParams")]
- : [deep("bodyParams")];
+ },
+ setRouteQueryState() {
+ const flat = key => (this[key] !== "" ? `${key}=${this[key]}&` : "");
+ const deep = key => {
+ const haveItems = [...this[key]].length;
+ if (haveItems && this[key]["value"] !== "") {
+ return `${key}=${JSON.stringify(this[key])}&`;
+ } else return "";
+ };
+ let flats = [
+ "method",
+ "url",
+ "path",
+ !this.urlExcludes.auth ? "auth" : null,
+ !this.urlExcludes.httpUser ? "httpUser" : null,
+ !this.urlExcludes.httpPassword ? "httpPassword" : null,
+ !this.urlExcludes.bearerToken ? "bearerToken" : null,
+ "contentType"
+ ]
+ .filter(item => item !== null)
+ .map(item => flat(item));
+ let deeps = ["headers", "params"].map(item => deep(item));
+ let bodyParams = this.rawInput
+ ? [flat("rawParams")]
+ : [deep("bodyParams")];
- history.replaceState(
- window.location.href,
- "",
- "/?" +
+ history.replaceState(
+ window.location.href,
+ "",
+ "/?" +
encodeURI(
flats
.concat(deeps, bodyParams)
.join("")
.slice(0, -1)
)
- );
- },
- setRouteQueries(queries) {
- if (typeof queries !== "object")
- throw new Error("Route query parameters must be a Object");
- for (const key in queries) {
- if (["headers", "params", "bodyParams"].includes(key))
- this[key] = JSON.parse(decodeURI(queries[key]));
- if (key === "rawParams") {
- this.rawInput = true;
- this.rawParams = queries["rawParams"];
- } else if (typeof this[key] === "string") this[key] = queries[key];
- }
- },
- observeRequestButton() {
- const requestElement = this.$refs.request.$el;
- const sendButtonElement = this.$refs.sendButton;
- const observer = new IntersectionObserver(
- (entries, observer) => {
- entries.forEach(entry => {
- if (entry.isIntersecting)
- sendButtonElement.classList.remove("show");
- // The button should float when it is no longer visible on screen.
- // This is done by adding the show class to the button.
- else sendButtonElement.classList.add("show");
- });
- },
- {
- rootMargin: "0px",
- threshold: [0]
+ );
+ },
+ setRouteQueries(queries) {
+ if (typeof queries !== "object")
+ throw new Error("Route query parameters must be a Object");
+ for (const key in queries) {
+ if (["headers", "params", "bodyParams"].includes(key))
+ this[key] = JSON.parse(decodeURI(queries[key]));
+ if (key === "rawParams") {
+ this.rawInput = true;
+ this.rawParams = queries["rawParams"];
+ } else if (typeof this[key] === "string") this[key] = queries[key];
}
- );
- observer.observe(requestElement);
- },
- handleImport() {
- let textarea = document.getElementById("import-text");
- let text = textarea.value;
- try {
- let parsedCurl = parseCurlCommand(text);
- let url = new URL(parsedCurl.url.replace(/"/g, "").replace(/'/g, ""));
- this.url = url.origin;
- this.path = url.pathname;
- this.headers = [];
- if (parsedCurl.headers) {
- for (const key of Object.keys(parsedCurl.headers)) {
- this.$store.commit("addHeaders", {
- key: key,
- value: parsedCurl.headers[key]
+ },
+ observeRequestButton() {
+ const requestElement = this.$refs.request.$el;
+ const sendButtonElement = this.$refs.sendButton;
+ const observer = new IntersectionObserver(
+ (entries, observer) => {
+ entries.forEach(entry => {
+ if (entry.isIntersecting)
+ sendButtonElement.classList.remove("show");
+ // The button should float when it is no longer visible on screen.
+ // This is done by adding the show class to the button.
+ else sendButtonElement.classList.add("show");
});
+ },
+ {
+ rootMargin: "0px",
+ threshold: [0]
+ }
+ );
+ observer.observe(requestElement);
+ },
+ handleImport() {
+ let textarea = document.getElementById("import-text");
+ let text = textarea.value;
+ try {
+ let parsedCurl = parseCurlCommand(text);
+ let url = new URL(parsedCurl.url.replace(/"/g, "").replace(/'/g, ""));
+ this.url = url.origin;
+ this.path = url.pathname;
+ this.headers = [];
+ if (parsedCurl.headers) {
+ for (const key of Object.keys(parsedCurl.headers)) {
+ this.$store.commit("addHeaders", {
+ key: key,
+ value: parsedCurl.headers[key]
+ });
+ }
+ }
+ this.method = parsedCurl.method.toUpperCase();
+ if (parsedCurl["data"]) {
+ this.rawInput = true;
+ this.rawParams = parsedCurl["data"];
}
+ this.showModal = false;
+ } catch (error) {
+ this.showModal = false;
+ this.$toast.error(this.$t("curl_invalid_format"), {
+ icon: "error"
+ });
}
- this.method = parsedCurl.method.toUpperCase();
- if (parsedCurl["data"]) {
- this.rawInput = true;
- this.rawParams = parsedCurl["data"];
+ },
+ switchVisibility() {
+ this.passwordFieldType =
+ this.passwordFieldType === "password" ? "text" : "password";
+ },
+ clearContent(name, e) {
+ switch (name) {
+ case "auth":
+ this.auth = "None";
+ this.httpUser = "";
+ this.httpPassword = "";
+ this.bearerToken = "";
+ this.showTokenRequest = false;
+ this.tokens = [];
+ this.tokenReqs = [];
+ break;
+ case "headers":
+ this.headers = [];
+ break;
+ case "parameters":
+ this.params = [];
+ break;
+ case "access_token":
+ this.accessTokenName = "";
+ this.oidcDiscoveryUrl = "";
+ this.authUrl = "";
+ this.accessTokenUrl = "";
+ this.clientId = "";
+ this.scope = "";
+ break;
+ case "tokens":
+ this.tokens = [];
+ break;
+ case "tokenReqs":
+ this.tokenReqs = [];
+ default:
+ (this.label = ""),
+ (this.method = "GET"),
+ (this.url = "https://reqres.in"),
+ (this.auth = "None"),
+ (this.path = "/api/users"),
+ (this.auth = "None");
+ this.httpUser = "";
+ this.httpPassword = "";
+ this.bearerToken = "";
+ this.headers = [];
+ this.params = [];
+ this.bodyParams = [];
+ this.rawParams = "";
+ this.showTokenRequest = false;
+ this.tokens = [];
+ this.tokenReqs = [];
+ this.accessTokenName = "";
+ this.oidcDiscoveryUrl = "";
+ this.authUrl = "";
+ this.accessTokenUrl = "";
+ this.clientId = "";
+ this.scope = "";
}
- this.showModal = false;
- } catch (error) {
- this.showModal = false;
- this.$toast.error(this.$t("curl_invalid_format"), {
- icon: "error"
+ e.target.innerHTML = this.doneButton;
+ this.$toast.info(this.$t("cleared"), {
+ icon: "clear_all"
});
- }
- },
- switchVisibility() {
- this.passwordFieldType =
- this.passwordFieldType === "password" ? "text" : "password";
- },
- clearContent(name, e) {
- switch (name) {
- case "auth":
- this.auth = "None";
- this.httpUser = "";
- this.httpPassword = "";
- this.bearerToken = "";
- this.showTokenRequest = false;
- this.tokens = [];
- this.tokenReqs = [];
- break;
- case "headers":
- this.headers = [];
- break;
- case "parameters":
- this.params = [];
- break;
- case "access_token":
- this.accessTokenName = "";
- this.oidcDiscoveryUrl = "";
- this.authUrl = "";
- this.accessTokenUrl = "";
- this.clientId = "";
- this.scope = "";
- break;
- case "tokens":
- this.tokens = [];
- break;
- case "tokenReqs":
- this.tokenReqs = [];
- default:
- (this.label = ""),
- (this.method = "GET"),
- (this.url = "https://reqres.in"),
- (this.auth = "None"),
- (this.path = "/api/users"),
- (this.auth = "None");
- this.httpUser = "";
- this.httpPassword = "";
- this.bearerToken = "";
- this.headers = [];
- this.params = [];
- this.bodyParams = [];
- this.rawParams = "";
- this.showTokenRequest = false;
- this.tokens = [];
- this.tokenReqs = [];
- this.accessTokenName = "";
- this.oidcDiscoveryUrl = "";
- this.authUrl = "";
- this.accessTokenUrl = "";
- this.clientId = "";
- this.scope = "";
- }
- e.target.innerHTML = this.doneButton;
- this.$toast.info(this.$t("cleared"), {
- icon: "clear_all"
- });
- setTimeout(
- () => (e.target.innerHTML = '<i class="material-icons">clear_all</i>'),
- 1000
- );
- },
- saveRequest() {
- if (!this.checkCollections()) {
- this.$toast.error(this.$t("create_collection"), {
- icon: "error"
- });
- return;
- }
-
- this.editRequest = {
- url: this.url,
- path: this.path,
- method: this.method,
- auth: this.auth,
- httpUser: this.httpUser,
- httpPassword: this.httpPassword,
- passwordFieldType: this.passwordFieldType,
- bearerToken: this.bearerToken,
- headers: this.headers,
- params: this.params,
- bodyParams: this.bodyParams,
- rawParams: this.rawParams,
- rawInput: this.rawInput,
- contentType: this.contentType,
- requestType: this.requestType
- };
-
- if (this.selectedRequest.url) {
- this.editRequest = Object.assign(
- {},
- this.selectedRequest,
- this.editRequest
+ setTimeout(
+ () => (e.target.innerHTML = '<i class="material-icons">clear_all</i>'),
+ 1000
);
- }
+ },
+ saveRequest() {
+ if (!this.checkCollections()) {
+ this.$toast.error(this.$t("create_collection"), {
+ icon: "error"
+ });
+ return;
+ }
- this.showRequestModal = true;
- },
- hideRequestModal() {
- this.showRequestModal = false;
- this.editRequest = {};
- },
- setExclude(excludedField, excluded) {
- if (excludedField === "auth") {
- this.urlExcludes.auth = excluded;
- this.urlExcludes.httpUser = excluded;
- this.urlExcludes.httpPassword = excluded;
- this.urlExcludes.bearerToken = excluded;
- } else {
- this.urlExcludes[excludedField] = excluded;
- }
- this.setRouteQueryState();
- },
- methodChange() {
- // this.$store.commit('setState', { 'value': ["POST", "PUT", "PATCH"].includes(this.method) ? 'application/json' : '', 'attribute': 'contentType' })
- this.contentType = ["POST", "PUT", "PATCH"].includes(this.method)
- ? "application/json"
- : "";
- },
- uploadPayload() {
- this.rawInput = true;
- let file = this.$refs.payload.files[0];
- if (file !== undefined && file !== null) {
- let reader = new FileReader();
- reader.onload = e => {
- this.rawParams = e.target.result;
+ this.editRequest = {
+ url: this.url,
+ path: this.path,
+ method: this.method,
+ auth: this.auth,
+ httpUser: this.httpUser,
+ httpPassword: this.httpPassword,
+ passwordFieldType: this.passwordFieldType,
+ bearerToken: this.bearerToken,
+ headers: this.headers,
+ params: this.params,
+ bodyParams: this.bodyParams,
+ rawParams: this.rawParams,
+ rawInput: this.rawInput,
+ contentType: this.contentType,
+ requestType: this.requestType
};
- reader.readAsText(file);
- this.$toast.info(this.$t("file_imported"), {
- icon: "attach_file"
- });
- } else {
- this.$toast.error(this.$t("choose_file"), {
- icon: "attach_file"
- });
- }
- },
- async handleAccessTokenRequest() {
- if (
- this.oidcDiscoveryUrl === "" &&
- (this.authUrl === "" || this.accessTokenUrl === "")
- ) {
- this.$toast.error(this.$t("complete_config_urls"), {
- icon: "error"
- });
- return;
- }
- try {
- const tokenReqParams = {
- grantType: "code",
- oidcDiscoveryUrl: this.oidcDiscoveryUrl,
- authUrl: this.authUrl,
- accessTokenUrl: this.accessTokenUrl,
- clientId: this.clientId,
- scope: this.scope
- };
- await tokenRequest(tokenReqParams);
- } catch (e) {
- this.$toast.error(e, {
- icon: "code"
- });
- }
- },
- async oauthRedirectReq() {
- let tokenInfo = await oauthRedirect();
- if (tokenInfo.hasOwnProperty("access_token")) {
- this.bearerToken = tokenInfo.access_token;
- this.addOAuthToken({
- name: this.accessTokenName,
- value: tokenInfo.access_token
- });
- }
- },
- addOAuthToken({ name, value }) {
- this.$store.commit("addOAuthToken", {
- name,
- value
- });
- return false;
- },
- removeOAuthToken(index) {
- const oldTokens = this.tokens.slice();
- this.$store.commit("removeOAuthToken", index);
- this.$toast.error(this.$t("deleted"), {
- icon: "delete",
- action: {
- text: this.$t("undo"),
- onClick: (e, toastObject) => {
- this.tokens = oldTokens;
- toastObject.remove();
- }
+
+ if (this.selectedRequest.url) {
+ this.editRequest = Object.assign(
+ {},
+ this.selectedRequest,
+ this.editRequest
+ );
}
- });
- },
- useOAuthToken(value) {
- this.bearerToken = value;
- this.showTokenList = false;
- },
- addOAuthTokenReq() {
- try {
- const name = this.tokenReqName;
- const details = JSON.parse(this.tokenReqDetails);
- this.$store.commit("addOAuthTokenReq", {
+
+ this.showRequestModal = true;
+ },
+ hideRequestModal() {
+ this.showRequestModal = false;
+ this.editRequest = {};
+ },
+ setExclude(excludedField, excluded) {
+ if (excludedField === "auth") {
+ this.urlExcludes.auth = excluded;
+ this.urlExcludes.httpUser = excluded;
+ this.urlExcludes.httpPassword = excluded;
+ this.urlExcludes.bearerToken = excluded;
+ } else {
+ this.urlExcludes[excludedField] = excluded;
+ }
+ this.setRouteQueryState();
+ },
+ methodChange() {
+ // this.$store.commit('setState', { 'value': ["POST", "PUT", "PATCH"].includes(this.method) ? 'application/json' : '', 'attribute': 'contentType' })
+ this.contentType = ["POST", "PUT", "PATCH"].includes(this.method)
+ ? "application/json"
+ : "";
+ },
+ uploadPayload() {
+ this.rawInput = true;
+ let file = this.$refs.payload.files[0];
+ if (file !== undefined && file !== null) {
+ let reader = new FileReader();
+ reader.onload = e => {
+ this.rawParams = e.target.result;
+ };
+ reader.readAsText(file);
+ this.$toast.info(this.$t("file_imported"), {
+ icon: "attach_file"
+ });
+ } else {
+ this.$toast.error(this.$t("choose_file"), {
+ icon: "attach_file"
+ });
+ }
+ },
+ async handleAccessTokenRequest() {
+ if (
+ this.oidcDiscoveryUrl === "" &&
+ (this.authUrl === "" || this.accessTokenUrl === "")
+ ) {
+ this.$toast.error(this.$t("complete_config_urls"), {
+ icon: "error"
+ });
+ return;
+ }
+ try {
+ const tokenReqParams = {
+ grantType: "code",
+ oidcDiscoveryUrl: this.oidcDiscoveryUrl,
+ authUrl: this.authUrl,
+ accessTokenUrl: this.accessTokenUrl,
+ clientId: this.clientId,
+ scope: this.scope
+ };
+ await tokenRequest(tokenReqParams);
+ } catch (e) {
+ this.$toast.error(e, {
+ icon: "code"
+ });
+ }
+ },
+ async oauthRedirectReq() {
+ let tokenInfo = await oauthRedirect();
+ if (tokenInfo.hasOwnProperty("access_token")) {
+ this.bearerToken = tokenInfo.access_token;
+ this.addOAuthToken({
+ name: this.accessTokenName,
+ value: tokenInfo.access_token
+ });
+ }
+ },
+ addOAuthToken({name, value}) {
+ this.$store.commit("addOAuthToken", {
name,
- details
+ value
+ });
+ return false;
+ },
+ removeOAuthToken(index) {
+ const oldTokens = this.tokens.slice();
+ this.$store.commit("removeOAuthToken", index);
+ this.$toast.error(this.$t("deleted"), {
+ icon: "delete",
+ action: {
+ text: this.$t("undo"),
+ onClick: (e, toastObject) => {
+ this.tokens = oldTokens;
+ toastObject.remove();
+ }
+ }
});
- this.$toast.info(this.$t("token_request_saved"));
- this.showTokenRequestList = false;
- } catch (e) {
- this.$toast.error(e, {
- icon: "code"
+ },
+ useOAuthToken(value) {
+ this.bearerToken = value;
+ this.showTokenList = false;
+ },
+ addOAuthTokenReq() {
+ try {
+ const name = this.tokenReqName;
+ const details = JSON.parse(this.tokenReqDetails);
+ this.$store.commit("addOAuthTokenReq", {
+ name,
+ details
+ });
+ this.$toast.info(this.$t("token_request_saved"));
+ this.showTokenRequestList = false;
+ } catch (e) {
+ this.$toast.error(e, {
+ icon: "code"
+ });
+ }
+ },
+ removeOAuthTokenReq(index) {
+ const oldTokenReqs = this.tokenReqs.slice();
+ let targetReqIndex = this.tokenReqs.findIndex(
+ tokenReq => tokenReq.name === this.tokenReqName
+ );
+ if (targetReqIndex < 0) return;
+ this.$store.commit("removeOAuthTokenReq", targetReqIndex);
+ this.$toast.error(this.$t("deleted"), {
+ icon: "delete",
+ action: {
+ text: this.$t("undo"),
+ onClick: (e, toastObject) => {
+ this.tokenReqs = oldTokenReqs;
+ toastObject.remove();
+ }
+ }
});
+ },
+ tokenReqChange(event) {
+ let targetReq = this.tokenReqs.find(
+ tokenReq => tokenReq.name === event.target.value
+ );
+ let {
+ oidcDiscoveryUrl,
+ authUrl,
+ accessTokenUrl,
+ clientId,
+ scope
+ } = targetReq.details;
+ this.tokenReqName = targetReq.name;
+ this.oidcDiscoveryUrl = oidcDiscoveryUrl;
+ this.authUrl = authUrl;
+ this.accessTokenUrl = accessTokenUrl;
+ this.clientId = clientId;
+ this.scope = scope;
}
},
- removeOAuthTokenReq(index) {
- const oldTokenReqs = this.tokenReqs.slice();
- let targetReqIndex = this.tokenReqs.findIndex(
- tokenReq => tokenReq.name === this.tokenReqName
- );
- if (targetReqIndex < 0) return;
- this.$store.commit("removeOAuthTokenReq", targetReqIndex);
- this.$toast.error(this.$t("deleted"), {
- icon: "delete",
- action: {
- text: this.$t("undo"),
- onClick: (e, toastObject) => {
- this.tokenReqs = oldTokenReqs;
- toastObject.remove();
- }
+ async mounted() {
+ this.observeRequestButton();
+ this._keyListener = function (e) {
+ if (e.key === "g" && (e.ctrlKey || e.metaKey)) {
+ e.preventDefault();
+ this.sendRequest();
+ } else if (e.key === "s" && (e.ctrlKey || e.metaKey)) {
+ e.preventDefault();
+ this.saveRequest();
+ } else if (e.key === "k" && (e.ctrlKey || e.metaKey)) {
+ e.preventDefault();
+ this.copyRequest();
+ } else if (e.key === "j" && (e.ctrlKey || e.metaKey)) {
+ e.preventDefault();
+ this.$refs.clearAll.click();
+ }
+ };
+ document.addEventListener("keydown", this._keyListener.bind(this));
+ await this.oauthRedirectReq();
+ },
+ created() {
+ this.urlExcludes = this.$store.state.postwoman.settings.URL_EXCLUDES || {
+ // Exclude authentication by default for security reasons.
+ auth: true,
+ httpUser: true,
+ httpPassword: true,
+ bearerToken: true
+ };
+
+ if (Object.keys(this.$route.query).length)
+ this.setRouteQueries(this.$route.query);
+ this.$watch(
+ vm => [
+ vm.label,
+ vm.method,
+ vm.url,
+ vm.auth,
+ vm.path,
+ vm.httpUser,
+ vm.httpPassword,
+ vm.bearerToken,
+ vm.headers,
+ vm.params,
+ vm.bodyParams,
+ vm.contentType,
+ vm.rawParams
+ ],
+ val => {
+ this.setRouteQueryState();
}
- });
- },
- tokenReqChange(event) {
- let targetReq = this.tokenReqs.find(
- tokenReq => tokenReq.name === event.target.value
);
- let {
- oidcDiscoveryUrl,
- authUrl,
- accessTokenUrl,
- clientId,
- scope
- } = targetReq.details;
- this.tokenReqName = targetReq.name;
- this.oidcDiscoveryUrl = oidcDiscoveryUrl;
- this.authUrl = authUrl;
- this.accessTokenUrl = accessTokenUrl;
- this.clientId = clientId;
- this.scope = scope;
+ },
+ beforeDestroy() {
+ document.removeEventListener("keydown", this._keyListener);
}
- },
- async mounted() {
- this.observeRequestButton();
- this._keyListener = function(e) {
- if (e.key === "g" && (e.ctrlKey || e.metaKey)) {
- e.preventDefault();
- this.sendRequest();
- } else if (e.key === "s" && (e.ctrlKey || e.metaKey)) {
- e.preventDefault();
- this.saveRequest();
- } else if (e.key === "k" && (e.ctrlKey || e.metaKey)) {
- e.preventDefault();
- this.copyRequest();
- } else if (e.key === "j" && (e.ctrlKey || e.metaKey)) {
- e.preventDefault();
- this.$refs.clearAll.click();
- }
- };
- document.addEventListener("keydown", this._keyListener.bind(this));
- await this.oauthRedirectReq();
- },
- created() {
- this.urlExcludes = this.$store.state.postwoman.settings.URL_EXCLUDES || {
- // Exclude authentication by default for security reasons.
- auth: true,
- httpUser: true,
- httpPassword: true,
- bearerToken: true
- };
-
- if (Object.keys(this.$route.query).length)
- this.setRouteQueries(this.$route.query);
- this.$watch(
- vm => [
- vm.label,
- vm.method,
- vm.url,
- vm.auth,
- vm.path,
- vm.httpUser,
- vm.httpPassword,
- vm.bearerToken,
- vm.headers,
- vm.params,
- vm.bodyParams,
- vm.contentType,
- vm.rawParams
- ],
- val => {
- this.setRouteQueryState();
- }
- );
- },
- beforeDestroy() {
- document.removeEventListener("keydown", this._keyListener);
- }
-};
+ };
</script>