This commit is contained in:
Pratik
2019-08-28 13:22:32 +02:00
2 changed files with 133 additions and 125 deletions

View File

@@ -13,6 +13,7 @@
"dependencies": { "dependencies": {
"@nuxtjs/pwa": "^3.0.0-0", "@nuxtjs/pwa": "^3.0.0-0",
"nuxt": "^2.0.0", "nuxt": "^2.0.0",
"vue-virtual-scroll-list": "^1.4.2",
"vuex-persist": "^2.0.1" "vuex-persist": "^2.0.1"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -191,62 +191,68 @@
<button v-bind:class="{ disabled: noHistoryToClear }" v-on:click="clearHistory">Clear History</button> <button v-bind:class="{ disabled: noHistoryToClear }" v-on:click="clearHistory">Clear History</button>
</li> </li>
</ul> </ul>
<ul v-for="entry in history"> <virtual-list class="virtual-list" :size="88" :remain="Math.min(5, history.length)">
<li> <ul v-for="entry in history" :key="entry.millis" class="entry">
<label for="time">Time</label> <li>
<input name="time" type="text" readonly :value="entry.time"> <label for="time">Time</label>
</li> <input name="time" type="text" readonly :value="entry.time">
<li class="method-list-item"> </li>
<label for="method">Method</label> <li class="method-list-item">
<input name="method" type="text" readonly :value="entry.method" :class="findEntryStatus(entry).className" :style="{'--status-code': entry.status}"> <label for="method">Method</label>
<span class="entry-status-code">{{entry.status}}</span> <input name="method" type="text" readonly
</li> :value="entry.method" :class="findEntryStatus(entry).className" :style="{'--status-code': entry.status}">
<li> <span class="entry-status-code">{{entry.status}}</span>
<label for="url">URL</label> </li>
<input name="url" type="text" readonly :value="entry.url"> <li>
</li> <label for="url">URL</label>
<li> <input name="url" type="text" readonly :value="entry.url">
<label for="path">Path</label> </li>
<input name="path" type="text" readonly :value="entry.path"> <li>
</li> <label for="path">Path</label>
<li> <input name="path" type="text" readonly :value="entry.path">
<label for="delete" class="hide-on-small-screen">&nbsp;</label> </li>
<button name="delete" @click="deleteHistory(entry)">Delete</button> <li>
</li> <label for="delete"class="hide-on-small-screen">&nbsp;</label>
<li> <button name="delete" @click="deleteHistory(entry)">Delete</button>
<label for="use" class="hide-on-small-screen">&nbsp;</label> </li>
<button name="use" @click="useHistory(entry)">Use</button> <li>
</li> <label for="use"class="hide-on-small-screen">&nbsp;</label>
</ul> <button name="use" @click="useHistory(entry)">Use</button>
</li>
</ul>
</virtual-list>
</pw-section> </pw-section>
</div> </div>
</template> </template>
<script> <script>
import VirtualList from 'vue-virtual-scroll-list'
import section from "../components/section";
const statusCategories = [{ const statusCategories = [{
name: 'informational', name: 'informational',
statusCodeRegex: new RegExp(/[1][0-9]+/), statusCodeRegex: new RegExp(/[1][0-9]+/),
className: 'info-response' className: 'info-response'
}, },
{ {
name: 'successful', name: 'successful',
statusCodeRegex: new RegExp(/[2][0-9]+/), statusCodeRegex: new RegExp(/[2][0-9]+/),
className: 'success-response' className: 'success-response'
}, },
{ {
name: 'redirection', name: 'redirection',
statusCodeRegex: new RegExp(/[3][0-9]+/), statusCodeRegex: new RegExp(/[3][0-9]+/),
className: 'redir-response' className: 'redir-response'
}, },
{ {
name: 'client error', name: 'client error',
statusCodeRegex: new RegExp(/[4][0-9]+/), statusCodeRegex: new RegExp(/[4][0-9]+/),
className: 'cl-error-response' className: 'cl-error-response'
}, },
{ {
name: 'server error', name: 'server error',
statusCodeRegex: new RegExp(/[5][0-9]+/), statusCodeRegex: new RegExp(/[5][0-9]+/),
className: 'sv-error-response' className: 'sv-error-response'
}, },
{ {
// this object is a catch-all for when no other objects match and should always be last // this object is a catch-all for when no other objects match and should always be last
name: 'unknown', name: 'unknown',
@@ -255,32 +261,33 @@
} }
]; ];
const parseHeaders = xhr => { const parseHeaders = xhr => {
const headers = xhr.getAllResponseHeaders().trim().split(/[\r\n]+/); const headers = xhr.getAllResponseHeaders().trim().split(/[\r\n]+/);
const headerMap = {}; const headerMap = {};
headers.forEach(line => { headers.forEach(line => {
const parts = line.split(': '); const parts = line.split(': ');
const header = parts.shift().toLowerCase(); const header = parts.shift().toLowerCase();
const value = parts.join(': '); const value = parts.join(': ');
headerMap[header] = value headerMap[header] = value
}); });
return headerMap return headerMap
}; };
const findStatusGroup = responseStatus => statusCategories.find(status => status.statusCodeRegex.test(responseStatus)); const findStatusGroup = responseStatus => statusCategories.find(status => status.statusCodeRegex.test(responseStatus));
import section from "../components/section";
export default { export default {
components: { components: {
'pw-section': section 'pw-section': section,
VirtualList
}, },
data() { data () {
return { return {
method: 'GET', method: 'GET',
url: 'https://reqres.in', url: 'https://reqres.in',
auth: 'None', auth: 'None',
path: '/api/users', path: '/api/users',
httpUser: '', httpUser: '',
httpPassword: '', httpPassword: '',
bearerToken: '', bearerToken: '',headers: [],
headers: [],
params: [], params: [],
bodyParams: [], bodyParams: [],
rawParams: '', rawParams: '',
@@ -352,7 +359,7 @@
key, key,
value value
}) => `${key}=${encodeURIComponent(value)}`).join('&') }) => `${key}=${encodeURIComponent(value)}`).join('&')
return result == '' ? '' : `?${result}` return result === '' ? '' : `?${result}`
}, },
responseType() { responseType() {
return (this.response.headers['content-type'] || '').split(';')[0].toLowerCase(); return (this.response.headers['content-type'] || '').split(';')[0].toLowerCase();
@@ -360,85 +367,85 @@
}, },
methods: { methods: {
findEntryStatus(entry) { findEntryStatus(entry) {
return findStatusGroup(entry.status); let foundStatusGroup = findStatusGroup(entry.status);
}, return foundStatusGroup || {className: ''};
deleteHistory(entry) { },
this.history.splice(this.history.indexOf(entry), 1) deleteHistory(entry) {
window.localStorage.setItem('history', JSON.stringify(this.history)) this.history.splice(this.history.indexOf(entry), 1)
}, window.localStorage.setItem('history', JSON.stringify(this.history))
clearHistory() { },
this.history = [] clearHistory() {
window.localStorage.setItem('history', JSON.stringify(this.history)) this.history = []
}, window.localStorage.setItem('history', JSON.stringify(this.history))
useHistory({ },
method, useHistory({
url, method,
path url,
}) { path
this.method = method }) {
this.url = url this.method = method
this.path = path this.url = url
this.$refs.request.$el.scrollIntoView({ this.path = path
behavior: 'smooth' this.$refs.request.$el.scrollIntoView({
}) behavior: 'smooth'
}, })
sendRequest() { },
sendRequest() {
if (!this.isValidURL) { if (!this.isValidURL) {
alert('Please check the formatting of the URL'); alert('Please check the formatting of the URL');
return return
} } 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.$refs.response.$el.scrollIntoView({
this.$refs.response.$el.scrollIntoView({ behavior: 'smooth'
behavior: 'smooth' });
});
this.previewEnabled = false; this.previewEnabled = false;
this.response.status = 'Fetching...'; this.response.status = 'Fetching...';
this.response.body = 'Loading...'; this.response.body = 'Loading...';
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
const user = this.auth === 'Basic' ? this.httpUser : null; const user = this.auth === 'Basic' ? this.httpUser : null;
const password = this.auth === 'Basic' ? this.httpPassword : null; const password = this.auth === 'Basic' ? this.httpPassword : null;
xhr.open(this.method, this.url + this.path + this.queryString, true, user, password); xhr.open(this.method, this.url + this.path + this.queryString, true, user, password);
if (this.auth === 'Bearer Token') xhr.setRequestHeader( if (this.auth === 'Bearer Token')
'Authorization', xhr.setRequestHeader('Authorization', 'Bearer ' + this.bearerToken
'Bearer ' + this.bearerToken );
); if (this.headers) {
if (this.headers) {
this.headers.forEach(function(element) { this.headers.forEach(function(element) {
xhr.setRequestHeader(element.key, element.value) xhr.setRequestHeader(element.key, element.value)
}) })
} }
if (this.method === 'POST' || this.method === 'PUT') { if (this.method === 'POST' || this.method === 'PUT') {
const requestBody = this.rawInput ? this.rawParams : this.rawRequestBody; const requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;
xhr.setRequestHeader('Content-Length', requestBody.length); xhr.setRequestHeader('Content-Length', requestBody.length);
xhr.setRequestHeader('Content-Type', `${this.contentType}; charset=utf-8`); xhr.setRequestHeader('Content-Type', `${this.contentType}; charset=utf-8`);
xhr.send(requestBody); xhr.send(requestBody);
} else { } else {
xhr.send(); xhr.send();
} }
xhr.onload = e => { xhr.onload = e => {
this.response.status = xhr.status; this.response.status = xhr.status;
const headers = this.response.headers = parseHeaders(xhr); const headers = this.response.headers = parseHeaders(xhr);
this.response.body = xhr.responseText; this.response.body = xhr.responseText;
if ((headers['content-type'] || '').startsWith('application/json')) { if ((headers['content-type'] || '').startsWith('application/json')) {
this.response.body = JSON.stringify(JSON.parse(this.response.body), null, 2); this.response.body = JSON.stringify(JSON.parse(
} this.response.body ), null, 2);
const n = new Date().toLocaleTimeString(); }
this.history = [{ const n = new Date().toLocaleTimeString();
status: xhr.status, this.history = [{
time: n, status: xhr.status,
method: this.method, time: n,
url: this.url, method: this.method,
path: this.path url: this.url,
}, ...this.history]; path: this.path
window.localStorage.setItem('history', JSON.stringify(this.history)); }, ...this.history];
}; window.localStorage.setItem('history', JSON.stringify(this.history));
xhr.onerror = e => { };
this.response.status = xhr.status; xhr.onerror = e => {
this.response.body = xhr.statusText; this.response.status = xhr.status;
} this.response.body = xhr.statusText;
}, }
},
addRequestHeader() { addRequestHeader() {
this.headers.push({ this.headers.push({
key: '', key: '',