Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
Merge branch 'master' of https://github.com/liyasthomas/postwoman
NBTX32218cff9fc7
diff --cc package.jsonindex 504627fc6,e92bc606d..38aa43656--- a/package.json+++ b/package.json@@@ -18,8 -20,7 +18,8 @@@"@nuxtjs/pwa": "^3.0.0-0","nuxt": "^2.9.2","vue-virtual-scroll-list": "^1.4.2",+ "vuejs-auto-complete": "^0.9.0",- "vuex-persist": "^2.0.1"+ "vuex-persist": "^2.1.0"},"devDependencies": {"node-sass": "^4.12.0",diff --cc pages/index.vueindex bcaabfbb1,6fc6c8b0b..3863711a3--- a/pages/index.vue+++ b/pages/index.vue@@@ -190,400 -192,399 +190,430 @@@</template><script>- import history from "../components/history";- import section from "../components/section";- import textareaAutoHeight from "../directives/textareaAutoHeight";+ import autocomplete from '../components/autocomplete';+ import history from "../components/history";+ import section from "../components/section";+ import textareaAutoHeight from "../directives/textareaAutoHeight";+ import toggle from "../components/toggle";- 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'+ const statusCategories = [{+ name: 'informational',+ statusCodeRegex: new RegExp(/[1][0-9]+/),+ className: 'info-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+ {+ 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 const findStatusGroup = responseStatus => statusCategories.find(status => status.statusCodeRegex.test(responseStatus));- export default {- directives: {- textareaAutoHeight- },- components: {- 'pw-section': section,- history- },- data() {- return {- method: 'GET',- url: 'https://reqres.in',- auth: 'None',- path: '/api/users',- httpUser: '',- httpPassword: '',- bearerToken: '',- headers: [],- params: [],- bodyParams: [],- rawParams: '',- rawInput: false,- contentType: 'application/json',- response: {- status: '',- headers: '',- body: ''+ export default {+ directives: {+ textareaAutoHeight},- previewEnabled: false- }- },- computed: {- statusCategory() {- return findStatusGroup(this.response.status);- },- isValidURL() {- 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 + "(([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);- },- rawRequestBody() {- const {- bodyParams- } = this- if (this.contentType === 'application/json') {- try {- const obj = JSON.parse(`{${bodyParams.filter(({ key }) => !!key).map(({ key, value }) => `+ components: {+ 'pw-section': section,+ 'pw-toggle': toggle,+ history,+ autocomplete+ },+ data() {+ return {++ method: 'GET',+ url: 'https://reqres.in',+ auth: 'None',+ path: '/api/users',+ httpUser: '',+ httpPassword: '',+ bearerToken: '',+ headers: [],+ params: [],+ bodyParams: [],+ rawParams: '',+ rawInput: false,+ contentType: 'application/json',+ response: {+ status: '',+ headers: '',+ body: ''+ },+ previewEnabled: 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'+ ]+ }+ },+ watch: {- contentType (val) {- this.rawInput = !this.knownContentTypes.includes(val);++ contentType(val) {++ this.rawInput = !this.knownContentTypes.includes(val);+ }+ },+ computed: {+ statusCategory() {+ return findStatusGroup(this.response.status);+ },+ isValidURL() {+ 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 + "(([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);+ },+ rawRequestBody() {+ const {+ bodyParams+ } = this+ if (this.contentType === 'application/json') {+ try {- const obj = JSON.parse(`{${bodyParams.filter(({ key }) => !!key).map(({ key, value }) => `++ const obj = JSON.parse(`{${bodyParams.filter(({key}) => !!key).map(({key, value}) => `"${key}": "${value}"`).join()}}`)- return JSON.stringify(obj)- } catch (ex) {- return 'invalid'- }- } else {- return bodyParams- .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();- }- },- methods: {- handleUseHistory({- method,- url,- path- }) {- this.method = method;- this.url = url;- this.path = path;- this.$refs.request.$el.scrollIntoView({- behavior: 'smooth'- });- },- async sendRequest() {- if (!this.isValidURL) {- alert('Please check the formatting of the URL.');- return;- }+ return JSON.stringify(obj)+ } catch (ex) {+ return 'invalid'+ }+ } else {+ return bodyParams+ .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();+ }+ },+ methods: {+ handleUseHistory({+ method,+ url,+ path+ }) {+ this.method = method;+ this.url = url;+ this.path = path;+ this.$refs.request.$el.scrollIntoView({+ behavior: 'smooth'+ });+ },+ async sendRequest() {+ if (!this.isValidURL) {+ alert('Please check the formatting of the URL.');+ 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.$refs.response.$el.scrollIntoView({- behavior: 'smooth'- });- this.previewEnabled = false;- this.response.status = 'Fetching...';- this.response.body = 'Loading...';+ if (this.$refs.response.$el.classList.contains('hidden')) {+ this.$refs.response.$el.classList.toggle('hidden')+ }+ this.$refs.response.$el.scrollIntoView({+ behavior: 'smooth'+ });+ this.previewEnabled = false;+ this.response.status = 'Fetching...';+ this.response.body = 'Loading...';- const auth = this.auth === 'Basic' ? {- username: this.httpUser,- password: this.httpPassword- } : null;+ const auth = this.auth === 'Basic' ? {+ username: this.httpUser,+ password: this.httpPassword+ } : null;- let headers = {};+ let headers = {};- // If the request has a request body, we want to ensure Content-Length and- // Content-Type are sent.- let requestBody;- if (this.hasRequestBody) {- requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;+ // If the request has a request body, we want to ensure Content-Length and+ // Content-Type are sent.+ let requestBody;+ if (this.hasRequestBody) {+ requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;- Object.assign(headers, {- 'Content-Length': requestBody.length,- 'Content-Type': `${this.contentType}; charset=utf-8`- });- }+ Object.assign(headers, {+ //'Content-Length': requestBody.length,+ 'Content-Type': `${this.contentType}; charset=utf-8`+ });+ }- // If the request uses a token for auth, we want to make sure it's sent here.- if (this.auth === 'Bearer Token') headers['Authorization'] = `Bearer ${this.bearerToken}`;+ // If the request uses a token for auth, we want to make sure it's sent here.+ if (this.auth === 'Bearer Token') headers['Authorization'] = `Bearer ${this.bearerToken}`;- 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),+ 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),- // We make our temporary headers object the source so- // that you can override the added headers if you- // specify them.- headers- );+ // We make our temporary headers object the source so+ // that you can override the added headers if you+ // specify them.+ headers+ );- try {- const payload = await this.$axios({- method: this.method,- url: this.url + this.path + this.queryString,- auth,- headers,- data: requestBody- });+ try {+ const payload = await this.$axios({+ method: this.method,+ url: this.url + this.path + this.queryString,+ auth,+ headers,+ data: requestBody.toString()+ });- (() => {- const status = this.response.status = payload.status;- const headers = this.response.headers = payload.headers;+ (() => {+ const status = this.response.status = payload.status;+ const headers = this.response.headers = payload.headers;- // We don't need to bother parsing JSON, axios already handles it for us!- const body = this.response.body = payload.data;+ // 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();+ const date = new Date().toLocaleDateString();+ const time = new Date().toLocaleTimeString();- // Addition of an entry to the history component.- const entry = {- status,- date,- time,- method: this.method,- url: this.url,- path: this.path- };- this.$refs.historyComponent.addEntry(entry);- })();- } catch (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 = {+ status,+ date,+ time,+ method: this.method,+ url: this.url,+ path: this.path+ };+ this.$refs.historyComponent.addEntry(entry);+ })();+ } catch (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 = {- status: this.response.status,- date: new Date().toLocaleDateString(),- time: new Date().toLocaleTimeString(),- method: this.method,- url: this.url,- path: this.path- };- this.$refs.historyComponent.addEntry(entry);- return;- }+ // Addition of an entry to the history component.+ const entry = {+ status: this.response.status,+ date: new Date().toLocaleDateString(),+ time: new Date().toLocaleTimeString(),+ method: this.method,+ url: this.url,+ path: this.path+ };+ this.$refs.historyComponent.addEntry(entry);+ return;+ }- this.response.status = error.message;- this.response.body = "See JavaScript console (F12) for details.";- }- },+ this.response.status = error.message;+ this.response.body = "See JavaScript console (F12) for details.";+ }+ },- addRequestHeader() {- this.headers.push({- key: '',- value: ''- });- return false- },- removeRequestHeader(index) {- this.headers.splice(index, 1)- },- addRequestParam() {- this.params.push({- key: '',- value: ''- })- return false- },- removeRequestParam(index) {- this.params.splice(index, 1)- },- addRequestBodyParam() {- this.bodyParams.push({- key: '',- value: ''- })- return false- },- removeRequestBodyParam(index) {- this.bodyParams.splice(index, 1)- },- formatRawParams(event) {- if ((event.which !== 13 && event.which !== 9)) {- return;- }- const textBody = event.target.value;- const textBeforeCursor = textBody.substring(0, event.target.selectionStart);- const textAfterCursor = textBody.substring(event.target.selectionEnd);- if (event.which === 13) {- event.preventDefault();- const oldSelectionStart = event.target.selectionStart;- const lastLine = textBeforeCursor.split('\n').slice(-1)[0];- const rightPadding = lastLine.match(/([\s\t]*).*/)[1] || "";- event.target.value = textBeforeCursor + '\n' + rightPadding + textAfterCursor;- setTimeout(() => event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + rightPadding.length + 1, 1);- } else if (event.which === 9) {- event.preventDefault();- const oldSelectionStart = event.target.selectionStart;- event.target.value = textBeforeCursor + '\xa0\xa0' + textAfterCursor;- event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + 2;- return false;- }- },- copyResponse() {- var copyText = document.getElementById("response-details");- copyText.select();- document.execCommand("copy");- },- 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', 'auth', 'httpUser', 'httpPassword', 'bearerToken','contentType'].map(item => flat(item))- let deeps = ['headers', 'params', 'bodyParams'].map(item => deep(item))- this.$router.replace('/?'+ flats.concat(deeps).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(key === 'headers' || key === 'params' || key ==='bodyParams') this[key] = JSON.parse(queries[key])- 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 => {- sendButtonElement.classList.toggle('show');- });- }, { threshold: 1 });+ addRequestHeader() {+ this.headers.push({+ key: '',+ value: ''+ });+ return false+ },+ removeRequestHeader(index) {+ this.headers.splice(index, 1)+ },+ addRequestParam() {+ this.params.push({+ key: '',+ value: ''+ })+ return false+ },+ removeRequestParam(index) {+ this.params.splice(index, 1)+ },+ addRequestBodyParam() {+ this.bodyParams.push({+ key: '',+ value: ''+ })+ return false+ },+ removeRequestBodyParam(index) {+ this.bodyParams.splice(index, 1)+ },+ formatRawParams(event) {+ if ((event.which !== 13 && event.which !== 9)) {+ return;+ }+ const textBody = event.target.value;+ const textBeforeCursor = textBody.substring(0, event.target.selectionStart);+ const textAfterCursor = textBody.substring(event.target.selectionEnd);+ if (event.which === 13) {+ event.preventDefault();+ const oldSelectionStart = event.target.selectionStart;+ const lastLine = textBeforeCursor.split('\n').slice(-1)[0];+ const rightPadding = lastLine.match(/([\s\t]*).*/)[1] || "";+ event.target.value = textBeforeCursor + '\n' + rightPadding + textAfterCursor;+ setTimeout(() => event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + rightPadding.length + 1, 1);+ } else if (event.which === 9) {+ event.preventDefault();+ const oldSelectionStart = event.target.selectionStart;+ event.target.value = textBeforeCursor + '\xa0\xa0' + textAfterCursor;+ event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + 2;+ return false;+ }+ },+ copyResponse() {+ var copyText = document.getElementById("response-details");+ copyText.select();+ document.execCommand("copy");+ },+ 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', 'auth', 'httpUser', 'httpPassword', 'bearerToken', 'contentType'].map(item => flat(item))++ let deeps = ['headers', 'params', 'bodyParams'].map(item => deep(item))++ this.$router.replace('/?' + flats.concat(deeps).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 (this[key]) this[key] = queries[key];++ if (key === 'headers' || key === 'params' || key === 'bodyParams') this[key] = JSON.parse(queries[key])++ 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 => {+ sendButtonElement.classList.toggle('show');+ });- }, { threshold: 1 });++ }, {threshold: 1});- observer.observe(requestElement);- }- },- mounted() {- this.observeRequestButton();- },- created() {- if (Object.keys(this.$route.query).length) this.setRouteQueries(this.$route.query);- this.$watch(vm => [- vm.method,- vm.url,- vm.auth,- vm.path,- vm.httpUser,- vm.httpPassword,- vm.bearerToken,- vm.headers,- vm.params,- vm.bodyParams,- vm.contentType- ], val => {- this.setRouteQueryState()- })+ observer.observe(requestElement);+ }+ },- created() {- if (Object.keys(this.$route.query).length) this.setRouteQueries(this.$route.query);- },+ mounted() {+ this.observeRequestButton();++ },++ created() {++ if (Object.keys(this.$route.query).length) this.setRouteQueries(this.$route.query);++ this.$watch(vm => [++ vm.method,++ vm.url,++ vm.auth,++ vm.path,++ vm.httpUser,++ vm.httpPassword,++ vm.bearerToken,++ vm.headers,++ vm.params,++ vm.bodyParams,++ vm.contentType++ ], val => {++ this.setRouteQueryState()++ })+++ }}- }</script>