url api and updated test

This commit is contained in:
Jacob Anavisca
2020-02-25 22:36:14 -05:00
parent 8cc7b525d9
commit 492d1cfa8f
3 changed files with 22 additions and 68 deletions

View File

@@ -185,24 +185,6 @@
v-model="uri" v-model="uri"
/> />
</li> </li>
<div>
<li>
<label class="hide-on-small-screen" for="send">&nbsp;</label>
<button
:disabled="!isValidURL"
@click="sendRequest"
id="send"
ref="sendButton"
>
{{ $t("send") }}
<span>
<i class="material-icons">send</i>
</span>
</button>
</li>
</div>
</ul>
<ul>
<li> <li>
<label for="label">{{ $t("label") }}</label> <label for="label">{{ $t("label") }}</label>
<input <input
@@ -1320,7 +1302,6 @@ import { tokenRequest, oauthRedirect } from "../assets/js/oauth"
import { sendNetworkRequest } from "../functions/network" import { sendNetworkRequest } from "../functions/network"
import { fb } from "../functions/fb" import { fb } from "../functions/fb"
import { getEditorLangForMimeType } from "~/functions/editorutils" import { getEditorLangForMimeType } from "~/functions/editorutils"
const statusCategories = [ const statusCategories = [
{ {
name: "informational", name: "informational",
@@ -1370,12 +1351,10 @@ const parseHeaders = xhr => {
} }
export const findStatusGroup = responseStatus => export const findStatusGroup = responseStatus =>
statusCategories.find(status => status.statusCodeRegex.test(responseStatus)) statusCategories.find(status => status.statusCodeRegex.test(responseStatus))
export default { export default {
directives: { directives: {
textareaAutoHeight, textareaAutoHeight,
}, },
components: { components: {
"pw-section": section, "pw-section": section,
"pw-toggle": () => import("../components/toggle"), "pw-toggle": () => import("../components/toggle"),
@@ -1412,13 +1391,11 @@ export default {
showTokenList: false, showTokenList: false,
showTokenRequest: false, showTokenRequest: false,
showTokenRequestList: false, showTokenRequestList: false,
/** /**
* These are content types that can be automatically * These are content types that can be automatically
* serialized by postwoman. * serialized by postwoman.
*/ */
knownContentTypes: ["application/json", "application/x-www-form-urlencoded"], knownContentTypes: ["application/json", "application/x-www-form-urlencoded"],
/** /**
* These are a list of Content Types known to Postwoman. * These are a list of Content Types known to Postwoman.
*/ */
@@ -1430,9 +1407,7 @@ export default {
"text/html", "text/html",
"text/plain", "text/plain",
], ],
commonHeaders, commonHeaders,
showRequestModal: false, showRequestModal: false,
editRequest: {}, editRequest: {},
urlExcludes: {}, urlExcludes: {},
@@ -1507,7 +1482,6 @@ export default {
} else { } else {
path = path + queryString path = path + queryString
} }
this.path = path this.path = path
}, },
deep: true, deep: true,
@@ -1543,16 +1517,29 @@ export default {
computed: { computed: {
uri: { uri: {
get() { get() {
return this.url + this.path; return this.$store.state.request.uri ?
this.$store.state.request.uri
: this.url + this.path;
}, },
set(value) { set(value) {
let uriRegex = value.match( this.$store.commit("setState", { value, attribute: "uri" })
/^((http[s]?:\/\/)?(<<[^\/]+>>)?[^\/]*|)(\/?.*)$/ let url;
); if (this.preRequestScript && this.showPreRequestScript) {
let url = uriRegex[1]; const environmentVariables = getEnvironmentVariablesFromScript(this.preRequestScript);
let path = uriRegex[4]; url = parseTemplateString(value, environmentVariables);
this.url = url; }
this.path = path; try {
url = new URL(url);
this.url = url.origin;
this.path = url.pathname;
} catch(error) {
console.log(error)
let uriRegex = value.match(
/^((http[s]?:\/\/)?(<<[^\/]+>>)?[^\/]*|)(\/?.*)$/
);
this.url = uriRegex[1];
this.path = uriRegex[4];
}
} }
}, },
url: { url: {
@@ -1783,7 +1770,6 @@ export default {
}) })
}, },
}, },
selectedRequest() { selectedRequest() {
return this.$store.state.postwoman.selectedRequest return this.$store.state.postwoman.selectedRequest
}, },
@@ -2019,31 +2005,26 @@ export default {
if (typeof requestOptions.data === "string") { if (typeof requestOptions.data === "string") {
requestOptions.data = parseTemplateString(requestOptions.data) requestOptions.data = parseTemplateString(requestOptions.data)
} }
return await sendNetworkRequest(requestOptions, this.$store) return await sendNetworkRequest(requestOptions, this.$store)
}, },
async sendRequest() { async sendRequest() {
this.$toast.clear() this.$toast.clear()
this.$store.state.postwoman.settings.SCROLL_INTO_ENABLED && this.scrollInto("response") this.$store.state.postwoman.settings.SCROLL_INTO_ENABLED && this.scrollInto("response")
if (!this.isValidURL) { if (!this.isValidURL) {
this.$toast.error(this.$t("url_invalid_format"), { this.$toast.error(this.$t("url_invalid_format"), {
icon: "error", icon: "error",
}) })
return return
} }
// Start showing the loading bar as soon as possible. // Start showing the loading bar as soon as possible.
// The nuxt axios module will hide it when the request is made. // The nuxt axios module will hide it when the request is made.
this.$nuxt.$loading.start() this.$nuxt.$loading.start()
if (this.$refs.response.$el.classList.contains("hidden")) { if (this.$refs.response.$el.classList.contains("hidden")) {
this.$refs.response.$el.classList.toggle("hidden") this.$refs.response.$el.classList.toggle("hidden")
} }
this.previewEnabled = false this.previewEnabled = false
this.response.status = this.$t("fetching") this.response.status = this.$t("fetching")
this.response.body = this.$t("loading") this.response.body = this.$t("loading")
const auth = const auth =
this.auth === "Basic Auth" this.auth === "Basic Auth"
? { ? {
@@ -2051,29 +2032,23 @@ export default {
password: this.httpPassword, password: this.httpPassword,
} }
: null : null
let headers = {} let headers = {}
let headersObject = {} let headersObject = {}
Object.keys(headers).forEach(id => { Object.keys(headers).forEach(id => {
headersObject[headers[id].key] = headers[id].value headersObject[headers[id].key] = headers[id].value
}) })
headers = headersObject headers = headersObject
// If the request has a body, we want to ensure Content-Length and // If the request has a body, we want to ensure Content-Length and
// Content-Type are sent. // Content-Type are sent.
let requestBody let requestBody
if (this.hasRequestBody) { if (this.hasRequestBody) {
requestBody = this.rawInput ? this.rawParams : this.rawRequestBody requestBody = this.rawInput ? this.rawParams : this.rawRequestBody
Object.assign(headers, { Object.assign(headers, {
//'Content-Length': requestBody.length, //'Content-Length': requestBody.length,
"Content-Type": `${this.contentType}; charset=utf-8`, "Content-Type": `${this.contentType}; charset=utf-8`,
}) })
} }
requestBody = requestBody ? requestBody.toString() : null requestBody = requestBody ? requestBody.toString() : null
if (this.files.length !== 0) { if (this.files.length !== 0) {
const formData = new FormData() const formData = new FormData()
for (let i = 0; i < this.files.length; i++) { for (let i = 0; i < this.files.length; i++) {
@@ -2083,37 +2058,30 @@ export default {
formData.append("data", requestBody) formData.append("data", requestBody)
requestBody = formData requestBody = formData
} }
// If the request uses a token for auth, we want to make sure it's sent here. // 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") if (this.auth === "Bearer Token" || this.auth === "OAuth 2.0")
headers["Authorization"] = `Bearer ${this.bearerToken}` headers["Authorization"] = `Bearer ${this.bearerToken}`
headers = Object.assign( headers = Object.assign(
// Clone the app headers object first, we don't want to // Clone the app headers object first, we don't want to
// mutate it with the request headers added by default. // mutate it with the request headers added by default.
Object.assign({}, this.headers) Object.assign({}, this.headers)
// We make our temporary headers object the source so // We make our temporary headers object the source so
// that you can override the added headers if you // that you can override the added headers if you
// specify them. // specify them.
// headers // headers
) )
Object.keys(headers).forEach(id => { Object.keys(headers).forEach(id => {
headersObject[headers[id].key] = headers[id].value headersObject[headers[id].key] = headers[id].value
}) })
headers = headersObject headers = headersObject
try { try {
const startTime = Date.now() const startTime = Date.now()
const payload = await this.makeRequest( const payload = await this.makeRequest(
auth, auth,
headers, headers,
requestBody, requestBody,
this.showPreRequestScript && this.preRequestScript this.showPreRequestScript && this.preRequestScript
) )
const duration = Date.now() - startTime const duration = Date.now() - startTime
this.$toast.info(this.$t("finished_in", { duration }), { this.$toast.info(this.$t("finished_in", { duration }), {
icon: "done", icon: "done",
@@ -2121,13 +2089,10 @@ export default {
;(() => { ;(() => {
const status = (this.response.status = payload.status) const status = (this.response.status = payload.status)
const headers = (this.response.headers = payload.headers) const headers = (this.response.headers = payload.headers)
// We don't need to bother parsing JSON, axios already handles it for us! // We don't need to bother parsing JSON, axios already handles it for us!
const body = (this.response.body = payload.data) const body = (this.response.body = payload.data)
const date = new Date().toLocaleDateString() const date = new Date().toLocaleDateString()
const time = new Date().toLocaleTimeString() const time = new Date().toLocaleTimeString()
// Addition of an entry to the history component. // Addition of an entry to the history component.
const entry = { const entry = {
label: this.requestName, label: this.requestName,
@@ -2149,7 +2114,6 @@ export default {
} }
} }
})() })()
// tests // tests
const syntheticResponse = { const syntheticResponse = {
status: this.response.status, status: this.response.status,
@@ -2166,7 +2130,6 @@ export default {
this.response.headers = error.response.headers this.response.headers = error.response.headers
this.response.status = error.response.status this.response.status = error.response.status
this.response.body = error.response.data this.response.body = error.response.data
// Addition of an entry to the history component. // Addition of an entry to the history component.
const entry = { const entry = {
label: this.requestName, label: this.requestName,
@@ -2235,7 +2198,6 @@ export default {
removeRequestHeader(index) { removeRequestHeader(index) {
// .slice() gives us an entirely new array rather than giving us just the reference // .slice() gives us an entirely new array rather than giving us just the reference
const oldHeaders = this.headers.slice() const oldHeaders = this.headers.slice()
this.$store.commit("removeHeaders", index) this.$store.commit("removeHeaders", index)
this.$toast.error(this.$t("deleted"), { this.$toast.error(this.$t("deleted"), {
icon: "delete", icon: "delete",
@@ -2255,7 +2217,6 @@ export default {
removeRequestParam(index) { removeRequestParam(index) {
// .slice() gives us an entirely new array rather than giving us just the reference // .slice() gives us an entirely new array rather than giving us just the reference
const oldParams = this.params.slice() const oldParams = this.params.slice()
this.$store.commit("removeParams", index) this.$store.commit("removeParams", index)
this.$toast.error(this.$t("deleted"), { this.$toast.error(this.$t("deleted"), {
icon: "delete", icon: "delete",
@@ -2275,7 +2236,6 @@ export default {
removeRequestBodyParam(index) { removeRequestBodyParam(index) {
// .slice() gives us an entirely new array rather than giving us just the reference // .slice() gives us an entirely new array rather than giving us just the reference
const oldBodyParams = this.bodyParams.slice() const oldBodyParams = this.bodyParams.slice()
this.$store.commit("removeBodyParams", index) this.$store.commit("removeBodyParams", index)
this.$toast.error(this.$t("deleted"), { this.$toast.error(this.$t("deleted"), {
icon: "delete", icon: "delete",
@@ -2408,7 +2368,6 @@ export default {
.map(item => flat(item)) .map(item => flat(item))
const deeps = ["headers", "params"].map(item => deep(item)) const deeps = ["headers", "params"].map(item => deep(item))
const bodyParams = this.rawInput ? [flat("rawParams")] : [deep("bodyParams")] const bodyParams = this.rawInput ? [flat("rawParams")] : [deep("bodyParams")]
history.replaceState( history.replaceState(
window.location.href, window.location.href,
"", "",
@@ -2555,7 +2514,6 @@ export default {
}) })
return return
} }
this.editRequest = { this.editRequest = {
url: this.url, url: this.url,
path: this.path, path: this.path,
@@ -2573,11 +2531,9 @@ export default {
contentType: this.contentType, contentType: this.contentType,
requestType: this.requestType, requestType: this.requestType,
} }
if (this.selectedRequest.url) { if (this.selectedRequest.url) {
this.editRequest = Object.assign({}, this.selectedRequest, this.editRequest) this.editRequest = Object.assign({}, this.selectedRequest, this.editRequest)
} }
this.showRequestModal = true this.showRequestModal = true
}, },
hideRequestModal() { hideRequestModal() {
@@ -2762,7 +2718,6 @@ export default {
httpPassword: true, httpPassword: true,
bearerToken: true, bearerToken: true,
} }
if (Object.keys(this.$route.query).length) this.setRouteQueries(this.$route.query) if (Object.keys(this.$route.query).length) this.setRouteQueries(this.$route.query)
this.$watch( this.$watch(
vm => [ vm => [

View File

@@ -1,6 +1,7 @@
export default () => ({ export default () => ({
request: { request: {
method: "GET", method: "GET",
uri: "",
url: "https://httpbin.org", url: "https://httpbin.org",
path: "/get", path: "/get",
label: "", label: "",

View File

@@ -3,8 +3,6 @@ describe("Proxy disabled - local request", () => {
cy.seedAndVisit("catapi", "/?url=https://api.thecatapi.com&path=") cy.seedAndVisit("catapi", "/?url=https://api.thecatapi.com&path=")
.get("#url") .get("#url")
.then(el => expect(el.val() === "https://api.thecatapi.com").to.equal(true)) .then(el => expect(el.val() === "https://api.thecatapi.com").to.equal(true))
.get("#path")
.then(el => expect(el.val() === "").to.equal(true))
.get("#response-details-wrapper") .get("#response-details-wrapper")
.should($wrapper => { .should($wrapper => {
expect($wrapper).to.contain("FAKE Cat API") expect($wrapper).to.contain("FAKE Cat API")