Merge pull request #543 from liyasthomas/refactor

Refactor
This commit is contained in:
James George
2020-02-01 23:44:54 +05:30
committed by GitHub
6 changed files with 118 additions and 158 deletions

View File

@@ -55,8 +55,8 @@ export default {
mounted() {
const editor = ace.edit(this.$refs.editor, {
theme: "ace/theme/" + this.defineTheme(),
mode: "ace/mode/" + this.lang,
theme: `ace/theme/${this.defineTheme()}`,
mode: `ace/mode/${this.lang}`,
...this.options
});
@@ -76,11 +76,10 @@ export default {
defineTheme() {
if (this.theme) {
return this.theme;
} else {
return (
this.$store.state.postwoman.settings.THEME_ACE_EDITOR || DEFAULT_THEME
);
}
return (
this.$store.state.postwoman.settings.THEME_ACE_EDITOR || DEFAULT_THEME
);
}
},

View File

@@ -363,8 +363,8 @@ export default {
let file = this.$refs.collectionUpload.files[0];
if (file !== undefined && file !== null) {
let reader = new FileReader();
reader.onload = e => {
this.collectionJSON = e.target.result;
reader.onload = ({ target }) => {
this.collectionJSON = target.result;
};
reader.readAsText(file);
this.$toast.info(this.$t("file_imported"), {

View File

@@ -531,7 +531,10 @@ export default {
return this.$store.state.gql.variablesJSONString;
},
set(value) {
this.$store.commit("setGQLState", { value, attribute: "variablesJSONString" });
this.$store.commit("setGQLState", {
value,
attribute: "variablesJSONString"
});
}
},
headerString() {
@@ -620,7 +623,7 @@ export default {
this.headers.forEach(header => {
headers[header.key] = header.value;
});
let variables = JSON.parse(this.variableString);
const gqlQueryString = this.gqlQueryString;
@@ -780,13 +783,10 @@ export default {
downloadResponse() {
const dataToWrite = JSON.stringify(this.schemaString, null, 2);
const file = new Blob([dataToWrite], { type: "application/json" });
const a = document.createElement("a"),
url = URL.createObjectURL(file);
const a = document.createElement("a");
const url = URL.createObjectURL(file);
a.href = url;
a.download = (this.url + " on " + Date() + ".graphql").replace(
/\./g,
"[dot]"
);
a.download = `${this.url} on ${Date()}.graphql`.replace(/\./g, "[dot]");
document.body.appendChild(a);
a.click();
this.$refs.downloadResponse.innerHTML = this.doneButton;

View File

@@ -1504,8 +1504,11 @@ export default {
this.rawInput = !this.knownContentTypes.includes(val);
},
rawInput(status) {
if (status && this.rawParams === "") this.rawParams = "{}";
else this.setRouteQueryState();
if (status && this.rawParams === "") {
this.rawParams = "{}";
} else {
this.setRouteQueryState();
}
},
"response.body": function(val) {
if (
@@ -1822,12 +1825,10 @@ export default {
}
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])$"
`${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 +
"(([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/])$"
`${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);
},
@@ -1838,8 +1839,8 @@ export default {
return this.path.match(/^([^?]*)\??/)[1];
},
rawRequestBody() {
const { bodyParams } = this;
if (this.contentType === "application/json") {
const { bodyParams, contentType } = this;
if (contentType === "application/json") {
try {
const obj = JSON.parse(
`{${bodyParams
@@ -1851,7 +1852,7 @@ export default {
)
.join()}}`
);
return JSON.stringify(obj);
return JSON.stringify(obj, null, 2);
} catch (ex) {
return "invalid";
}
@@ -1885,39 +1886,20 @@ export default {
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;
const user = this.auth === "Basic Auth" ? `'${this.httpUser}'` : null;
const password =
this.auth === "Basic Auth" ? `'${this.httpPassword}'` : null;
requestString.push(
"xhr.open('" +
this.method +
"', '" +
this.url +
this.pathName +
this.queryString +
"', true, " +
user +
", " +
pswd +
")"
`xhr.open('${this.method}', '${this.url}${this.pathName}${this.queryString}', true, ${user}, ${password})`
);
if (this.auth === "Bearer Token" || this.auth === "OAuth 2.0") {
requestString.push(
"xhr.setRequestHeader('Authorization', 'Bearer " +
this.bearerToken +
"')"
`xhr.setRequestHeader('Authorization', 'Bearer ${this.bearerToken}')`
);
}
if (this.headers) {
this.headers.forEach(element => {
requestString.push(
"xhr.setRequestHeader('" +
element.key +
"', '" +
element.value +
"')"
);
this.headers.forEach(({ key, value }) => {
requestString.push(`xhr.setRequestHeader('${key}', '${value}')`);
});
}
if (["POST", "PUT", "PATCH"].includes(this.method)) {
@@ -1925,14 +1907,12 @@ export default {
? this.rawParams
: this.rawRequestBody;
requestString.push(
"xhr.setRequestHeader('Content-Length', " + requestBody.length + ")"
`xhr.setRequestHeader('Content-Length', ${requestBody.length})`
);
requestString.push(
"xhr.setRequestHeader('Content-Type', '" +
this.contentType +
"; charset=utf-8')"
`xhr.setRequestHeader('Content-Type', '${this.contentType}; charset=utf-8')`
);
requestString.push("xhr.send(" + requestBody + ")");
requestString.push(`xhr.send(${requestBody})`);
} else {
requestString.push("xhr.send()");
}
@@ -1941,40 +1921,36 @@ export default {
const requestString = [];
let headers = [];
requestString.push(
'fetch("' + this.url + this.pathName + this.queryString + '", {\n'
`fetch("${this.url}${this.pathName}${this.queryString}", {\n`
);
requestString.push(' method: "' + this.method + '",\n');
requestString.push(` method: "${this.method}",\n`);
if (this.auth === "Basic Auth") {
const basic = this.httpUser + ":" + this.httpPassword;
const basic = `${this.httpUser}:${this.httpPassword}`;
headers.push(
' "Authorization": "Basic ' +
window.btoa(unescape(encodeURIComponent(basic))) +
'",\n'
` "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'
);
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");
requestString.push(` body: ${requestBody},\n`);
headers.push(` "Content-Length": ${requestBody.length},\n`);
headers.push(
' "Content-Type": "' + this.contentType + '; charset=utf-8",\n'
` "Content-Type": "${this.contentType}; charset=utf-8",\n`
);
}
if (this.headers) {
this.headers.forEach(element => {
headers.push(
' "' + element.key + '": "' + element.value + '",\n'
);
this.headers.forEach(({ key, value }) => {
headers.push(` "${key}": "${value}",\n`);
});
}
headers = headers.join("").slice(0, -2);
requestString.push(" headers: {\n" + headers + "\n },\n");
requestString.push(` headers: {\n${headers}\n },\n`);
requestString.push(' credentials: "same-origin"\n');
requestString.push("}).then(function(response) {\n");
requestString.push(" response.status\n");
@@ -1988,40 +1964,36 @@ export default {
return requestString.join("");
} else if (this.requestType === "cURL") {
const requestString = [];
requestString.push("curl -X " + this.method + " \n");
requestString.push(`curl -X ${this.method} \n`);
requestString.push(
" '" + this.url + this.pathName + this.queryString + "' \n"
` '${this.url}${this.pathName}${this.queryString}' \n`
);
if (this.auth === "Basic Auth") {
const basic = this.httpUser + ":" + this.httpPassword;
const basic = `${this.httpUser}:${this.httpPassword}`;
requestString.push(
" -H 'Authorization: Basic " +
window.btoa(unescape(encodeURIComponent(basic))) +
"' \n"
` -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"
` -H 'Authorization: Bearer ${this.bearerToken}' \n`
);
}
if (this.headers) {
this.headers.forEach(element => {
requestString.push(
" -H '" + element.key + ": " + element.value + "' \n"
);
this.headers.forEach(({ key, value }) => {
requestString.push(` -H '${key}: ${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-Length: " + requestBody.length + "' \n"
` -H 'Content-Type: ${this.contentType}; charset=utf-8' \n`
);
requestString.push(
" -H 'Content-Type: " + this.contentType + "; charset=utf-8' \n"
);
requestString.push(" -d '" + requestBody + "' \n");
requestString.push(` -d '${requestBody}' \n`);
}
return requestString.join("").slice(0, -2);
}
@@ -2283,21 +2255,20 @@ export default {
}
},
getQueryStringFromPath() {
let queryString,
pathParsed = url.parse(this.path);
let queryString;
const pathParsed = url.parse(this.path);
return (queryString = pathParsed.query ? pathParsed.query : "");
},
queryStringToArray(queryString) {
let queryParsed = querystring.parse(queryString);
const queryParsed = querystring.parse(queryString);
return Object.keys(queryParsed).map(key => ({
key: key,
key,
value: queryParsed[key]
}));
},
pathInputHandler() {
let queryString = this.getQueryStringFromPath(),
params = this.queryStringToArray(queryString);
const queryString = this.getQueryStringFromPath();
const params = this.queryStringToArray(queryString);
this.paramsWatchEnabled = false;
this.params = params;
},
@@ -2366,8 +2337,8 @@ export default {
},
copyRequest() {
if (navigator.share) {
let time = new Date().toLocaleTimeString();
let date = new Date().toLocaleDateString();
const time = new Date().toLocaleTimeString();
const date = new Date().toLocaleDateString();
navigator
.share({
title: `Postwoman`,
@@ -2418,7 +2389,7 @@ export default {
const aux = document.createElement("textarea");
const copy =
this.responseType === "application/json"
? JSON.stringify(this.response.body)
? JSON.stringify(this.response.body, null, 2)
: this.response.body;
aux.innerText = copy;
document.body.appendChild(aux);
@@ -2433,17 +2404,12 @@ export default {
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);
const a = document.createElement("a");
const url = URL.createObjectURL(file);
a.href = url;
a.download = (
this.url +
this.path +
" [" +
this.method +
"] on " +
Date()
).replace(/\./g, "[dot]");
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;
@@ -2489,7 +2455,8 @@ export default {
const haveItems = [...this[key]].length;
if (haveItems && this[key]["value"] !== "") {
return `${key}=${JSON.stringify(this[key])}&`;
} else return "";
}
return "";
};
let flats = [
"method",
@@ -2503,21 +2470,20 @@ export default {
]
.filter(item => item !== null)
.map(item => flat(item));
let deeps = ["headers", "params"].map(item => deep(item));
let bodyParams = this.rawInput
const deeps = ["headers", "params"].map(item => deep(item));
const bodyParams = this.rawInput
? [flat("rawParams")]
: [deep("bodyParams")];
history.replaceState(
window.location.href,
"",
"/?" +
encodeURI(
flats
.concat(deeps, bodyParams)
.join("")
.slice(0, -1)
)
`/?${encodeURI(
flats
.concat(deeps, bodyParams)
.join("")
.slice(0, -1)
)}`
);
},
setRouteQueries(queries) {
@@ -2529,7 +2495,9 @@ export default {
if (key === "rawParams") {
this.rawInput = true;
this.rawParams = queries["rawParams"];
} else if (typeof this[key] === "string") this[key] = queries[key];
} else if (typeof this[key] === "string") {
this[key] = queries[key];
}
}
},
observeRequestButton() {
@@ -2553,18 +2521,17 @@ export default {
observer.observe(requestElement);
},
handleImport() {
let textarea = document.getElementById("import-text");
let text = textarea.value;
const { value: text } = document.getElementById("import-text");
try {
let parsedCurl = parseCurlCommand(text);
let url = new URL(parsedCurl.url.replace(/"/g, "").replace(/'/g, ""));
this.url = url.origin;
this.path = url.pathname;
const parsedCurl = parseCurlCommand(text);
const { origin, pathname } = new URL(parsedCurl.url.replace(/"/g, "").replace(/'/g, ""));
this.url = origin;
this.path = pathname;
this.headers = [];
if (parsedCurl.headers) {
for (const key of Object.keys(parsedCurl.headers)) {
this.$store.commit("addHeaders", {
key: key,
key,
value: parsedCurl.headers[key]
});
}
@@ -2711,11 +2678,11 @@ export default {
},
uploadPayload() {
this.rawInput = true;
let file = this.$refs.payload.files[0];
const file = this.$refs.payload.files[0];
if (file !== undefined && file !== null) {
let reader = new FileReader();
reader.onload = e => {
this.rawParams = e.target.result;
const reader = new FileReader();
reader.onload = ({ target }) => {
this.rawParams = target.result;
};
reader.readAsText(file);
this.$toast.info(this.$t("file_imported"), {
@@ -2754,7 +2721,7 @@ export default {
}
},
async oauthRedirectReq() {
let tokenInfo = await oauthRedirect();
const tokenInfo = await oauthRedirect();
if (tokenInfo.hasOwnProperty("access_token")) {
this.bearerToken = tokenInfo.access_token;
this.addOAuthToken({
@@ -2806,8 +2773,8 @@ export default {
},
removeOAuthTokenReq(index) {
const oldTokenReqs = this.tokenReqs.slice();
let targetReqIndex = this.tokenReqs.findIndex(
tokenReq => tokenReq.name === this.tokenReqName
const targetReqIndex = this.tokenReqs.findIndex(
({ name }) => name === this.tokenReqName
);
if (targetReqIndex < 0) return;
this.$store.commit("removeOAuthTokenReq", targetReqIndex);
@@ -2822,18 +2789,16 @@ export default {
}
});
},
tokenReqChange(event) {
let targetReq = this.tokenReqs.find(
tokenReq => tokenReq.name === event.target.value
);
let {
tokenReqChange({ target }) {
const { details, name } = this.tokenReqs.find(({ name }) => name === target.value);
const {
oidcDiscoveryUrl,
authUrl,
accessTokenUrl,
clientId,
scope
} = targetReq.details;
this.tokenReqName = targetReq.name;
} = details;
this.tokenReqName = name;
this.oidcDiscoveryUrl = oidcDiscoveryUrl;
this.authUrl = authUrl;
this.accessTokenUrl = accessTokenUrl;

View File

@@ -211,24 +211,20 @@ export default {
urlValid() {
const protocol = "^(wss?:\\/\\/)?";
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])$"
`${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 +
"(([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/])$"
`${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);
},
serverValid() {
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])$"
`${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 +
"(([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/])$"
`${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.server) || validHostname.test(this.server);
}

View File

@@ -398,9 +398,9 @@ export default {
firebase
.auth()
.signInWithPopup(provider)
.then(res => {
if (res.additionalUserInfo.isNewUser) {
this.$toast.info(this.$t("turn_on") + " " + this.$t("sync"), {
.then(({ additionalUserInfo }) => {
if (additionalUserInfo.isNewUser) {
this.$toast.info(`${this.$t("turn_on")} ${this.$t("sync")}`, {
icon: "sync",
duration: null,
closeOnSwipe: false,
@@ -427,9 +427,9 @@ export default {
firebase
.auth()
.signInWithPopup(provider)
.then(res => {
if (res.additionalUserInfo.isNewUser) {
this.$toast.info(this.$t("turn_on") + " " + this.$t("sync"), {
.then(({ additionalUserInfo }) => {
if (additionalUserInfo.isNewUser) {
this.$toast.info(`${this.$t("turn_on")} ${this.$t("sync")}`, {
icon: "sync",
duration: null,
closeOnSwipe: false,
@@ -458,14 +458,14 @@ export default {
fb.writeSettings("syncHistory", true);
fb.writeSettings("syncCollections", false);
},
resetProxy(e) {
resetProxy({ target }) {
this.settings.PROXY_URL = `https://postwoman.apollotv.xyz/`;
e.target.innerHTML = this.doneButton;
target.innerHTML = this.doneButton;
this.$toast.info(this.$t("cleared"), {
icon: "clear_all"
});
setTimeout(
() => (e.target.innerHTML = '<i class="material-icons">clear_all</i>'),
() => (target.innerHTML = '<i class="material-icons">clear_all</i>'),
1000
);
}