feat: Remove VueJS and rewrite in vanilla JS

pull/16/head
Karan Sharma 2021-03-04 18:23:04 +05:30
parent 022c1267b7
commit d985ecd1b4
3 changed files with 185 additions and 154 deletions

View File

@ -1,95 +1,167 @@
var app = new Vue({
el: '#app',
data: {
apiURL: "/api/lookup/",
results: [],
noRecordsFound: false,
emptyNameError: false,
apiErrorMessage: "",
queryName: "",
queryType: "A",
nameserverName: "cloudflare",
customNSAddr: "",
nsAddrMap: {
"google": "8.8.8.8",
"cloudflare": "1.1.1.1",
"cloudflare-doh": "https://cloudflare-dns.com/dns-query",
"quad9": "9.9.9.9",
}
},
created: function () {
},
computed: {
getNSAddrValue() {
return this.nsAddrMap[this.nameserverName]
},
isCustomNS() {
if (this.nameserverName == "custom") {
return true
const $ = document.querySelector.bind(document);
const $new = document.createElement.bind(document);
const apiURL = "/api/lookup/";
const isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;
const nsAddrMap = {
"google": "8.8.8.8",
"cloudflare": "1.1.1.1",
"cloudflare-doh": "https://cloudflare-dns.com/dns-query",
"quad9": "9.9.9.9",
}
function handleNSChange() {
if ($('select[name=ns]').value == "custom") {
$('div[id=custom_ns]').classList.remove("hidden");
$('div[id=ns]').classList.add("hidden");
} else {
$('div[id=custom_ns]').classList.add("hidden");
$('div[id=ns]').classList.remove("hidden");
$('input[name=ns]').placeholder = nsAddrMap[$('select[name=ns]').value];
}
}
// Source: https://stackoverflow.com/a/1026087.
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
window.addEventListener('DOMContentLoaded', (event) => {
handleNSChange();
});
(function () {
const fields = ['name', 'address', 'type', 'ttl', 'rtt', 'nameserver'];
// createRow creates a table row with the given cell values.
function createRow(item) {
const tr = $new('tr');
fields.forEach((f) => {
const td = $new('td');
td.classList.add("px-6", "py-4", "whitespace-nowrap", "text-sm");
if (f == "ttl" || f == "rtt" || f == "nameserver") {
td.classList.add("text-gray-500");
} else {
td.classList.add("text-gray-900");
}
return false
}
},
methods: {
prepareNS() {
switch (this.nameserverName) {
case "google":
return "tcp://8.8.8.8:53"
case "cloudflare":
return "tcp://1.1.1.1:53"
case "cloudflare-doh":
return "https://cloudflare-dns.com/dns-query"
case "quad9":
return "tcp://9.9.9.9:53"
case "custom":
return this.customNSAddr
default:
return ""
if (f == "name") {
td.classList.add("font-semibold");
}
},
lookupRecords() {
// reset variables.
this.results = []
this.noRecordsFound = false
this.emptyNameError = false
this.apiErrorMessage = ""
if (this.queryName == "") {
this.emptyNameError = true
return
if (f == "type") {
td.innerHTML = '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">' + item[f] + '</span>';
} else {
td.innerText = item[f];
}
tr.appendChild(td);
});
return tr;
}
// GET request using fetch with error handling
fetch(this.apiURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
query: [this.queryName,],
type: [this.queryType,],
nameservers: [this.prepareNS(),],
}),
}).then(async response => {
const res = await response.json();
// check for error response
if (!response.ok) {
// get error message from body or default to response statusText
const error = (res && res.message) || response.statusText;
return Promise.reject(error);
}
// createList creates a table row with the given cell values.
function createList(item) {
const ul = $new('ul');
ul.classList.add("m-4", "block", "bg-indigo-100");
fields.forEach((f) => {
const li = $new('li');
const span = $new('span');
span.classList.add("p-2", "text-gray-500", "font-semibold");
span.innerText = capitalizeFirstLetter(f) + ': ' + item[f]
li.appendChild(span);
ul.appendChild(li);
});
return ul;
}
if (res.data[0].answers == null) {
this.noRecordsFound = true
} else {
// Set the answers in the results list.
this.results = res.data[0].answers
}
}).catch(error => {
this.apiErrorMessage = error
});
function prepareNSAddr(ns) {
switch (ns) {
case "google":
return "tcp://8.8.8.8:53"
case "cloudflare":
return "tcp://1.1.1.1:53"
case "cloudflare-doh":
return "https://cloudflare-dns.com/dns-query"
case "quad9":
return "tcp://9.9.9.9:53"
case "custom":
return $('input[name=custom_ns]').value.trim()
default:
return ""
}
}
})
const postForm = body => {
return fetch(apiURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body
});
};
const handleSubmit = async (e) => {
e.preventDefault();
const tbl = $('table tbody');
const list = $('div[id=mobile-answers-sec]');
tbl.innerHTML = '';
list.innerHTML = '';
$('p[id=empty-name-sec]').classList.add("hidden");
const errSec = $('div[id=api-error-sec]');
errSec.classList.add("hidden");
const q = $('input[name=q]').value.trim(), typ = $('select[name=type]').value;
const ns = $('select[name=ns]').value;
if (!q) {
$('p[id=empty-name-sec]').classList.remove("hidden");
throw ('Invalid query name.');
}
if (!q || !typ || !ns) {
throw ('Invalid or empty query params.');
}
const nsAddr = prepareNSAddr(ns);
const body = JSON.stringify({ query: [q,], type: [typ,], nameservers: [nsAddr,] });
const response = await postForm(body);
const res = await response.json();
if (res.status != "success") {
// get error message from body or default to response statusText
const error = (res && res.message) || response.statusText;
errSec.classList.remove("hidden");
errSec.innerHTML = '<p class="text-xl text-red-500">' + error + '</p>'
throw (error);
}
if (res.data[0].answers == null) {
const errSec = $('div[id=api-error-sec]');
errSec.classList.remove("hidden");
errSec.innerHTML = '<p class="text-xl text-red-500">' + 'No records found!' + '</p>'
return null;
}
$('div[id=answer_sec]').classList.remove("hidden");
if (isMobile === true) {
list.classList.remove("hidden");
res.data[0].answers.forEach((item) => {
console.log("appending", item)
list.appendChild(createList(item));
});
} else {
res.data[0].answers.forEach((item) => {
tbl.appendChild(createRow(item));
});
}
};
document.querySelector('form').addEventListener('submit', handleSubmit);
})();

View File

@ -70,7 +70,7 @@ func handleLookup(w http.ResponseWriter, r *http.Request) {
err = app.LoadNameservers()
if err != nil {
app.Logger.WithError(err).Error("error loading nameservers")
sendErrorResponse(w, fmt.Sprintf("Error lookuping up for records."), http.StatusInternalServerError, nil)
sendErrorResponse(w, fmt.Sprintf("Error looking up for records."), http.StatusInternalServerError, nil)
return
}
@ -86,7 +86,7 @@ func handleLookup(w http.ResponseWriter, r *http.Request) {
})
if err != nil {
app.Logger.WithError(err).Error("error loading resolver")
sendErrorResponse(w, fmt.Sprintf("Error lookuping up for records."), http.StatusInternalServerError, nil)
sendErrorResponse(w, fmt.Sprintf("Error looking up for records."), http.StatusInternalServerError, nil)
return
}
app.Resolvers = rslvrs
@ -97,7 +97,7 @@ func handleLookup(w http.ResponseWriter, r *http.Request) {
resp, err := rslv.Lookup(q)
if err != nil {
app.Logger.WithError(err).Error("error looking up DNS records")
sendErrorResponse(w, fmt.Sprintf("Error lookuping up for records."), http.StatusInternalServerError, nil)
sendErrorResponse(w, fmt.Sprintf("Error looking up for records."), http.StatusInternalServerError, nil)
return
}
responses = append(responses, resp)

View File

@ -10,17 +10,8 @@
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<style>
[v-cloak]>* {
display: none;
}
/* [v-cloak]::before {
content: "loading...";
} */
body {
font-family: 'Poppins', sans-serif;
}
@ -39,18 +30,18 @@
<header class="mt-10">
<h1 class="text-5xl font-black text-center"><span class="text-indigo-700">Doggo</span> DNS</h1>
</header>
<main id="app" v-cloak class="main flex flex-col flex-grow">
<form @submit.prevent="lookupRecords">
<main id="app" class="main flex flex-col flex-grow">
<form>
<div class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4 flex flex-col my-2">
<div class="-mx-3 md:flex mb-6">
<div class="md:w-1/2 px-3 mb-6 md:mb-0">
<label class="block tracking-wide text-grey-darker text-xs font-bold mb-2">
Domain Name
</label>
<input v-model="queryName"
<input name="q"
class="appearance-none block w-full bg-grey-lighter text-grey-darker border border-red rounded py-3 px-4 mb-3"
type="text" placeholder="domain.tld">
<p v-if="emptyNameError" class="text-red-500 text-xs">Please enter a domain name to
<p id="empty-name-sec" class="hidden text-red-500 text-xs">Please enter a domain name to
query.
</p>
</div>
@ -60,8 +51,8 @@
</label>
<select
class="block appearance-none w-full bg-grey-lighter border border-grey-lighter text-grey-darker py-3 px-4 pr-8 rounded"
v-model="queryType">
<option>A</option>
name="type">
<option default>A</option>
<option>AAAA</option>
<option>CAA</option>
<option>CNAME</option>
@ -77,13 +68,13 @@
</div>
<div class="-mx-3 md:flex">
<div class="md:w-1/2 px-3 mb-6 md:mb-0">
<label class="block tracking-wide text-grey-darker text-xs font-bold mb-2" for="grid-state">
<label class="block tracking-wide text-grey-darker text-xs font-bold mb-2">
Nameserver
</label>
<select v-model="nameserverName"
<select name="ns"
class="block appearance-none w-full bg-grey-lighter border border-grey-lighter text-grey-darker py-3 px-4 pr-8 rounded"
id="grid-state">
<option value="cloudflare">Cloudflare</option>
onchange="handleNSChange()">>
<option default value="cloudflare">Cloudflare</option>
<option value="cloudflare-doh">Cloudflare (DOH)</option>
<option value="google">Google</option>
<option value="quad9">Quad9</option>
@ -94,30 +85,29 @@
<label class="block tracking-wide text-grey-darker text-xs font-bold mb-2" for="grid-zip">
Address
</label>
<div v-if="isCustomNS">
<input v-model="customNSAddr" class="appearance-none block w-full bg-grey-lighter text-grey-darker border
border-grey-lighter rounded py-3 px-4" id="grid-zip" type="text"
placeholder="Enter Nameserver address">
<div id="custom_ns" class="hidden">
<input name="custom_ns" class="appearance-none block w-full bg-grey-lighter text-grey-darker border
border-grey-lighter rounded py-3 px-4" type="text" placeholder="Enter Nameserver address">
<p class="mt-2 text-grey-darker text-xs">To use different protocols like DOH, DOT etc. refer
to the
instructions <a class="font-semibold"
href="https://github.com/mr-karan/doggo#transport-options">here</a>.</p>
</div>
<div v-else>
<input readonly
<div id="ns">
<input readonly name="ns"
class="appearance-none block w-full bg-grey-lighter text-grey-darker border border-grey-lighter rounded py-3 px-4"
id="grid-zip" type="text" :placeholder="getNSAddrValue">
type="text">
</div>
</div>
</div>
<div class="mt-8 text-right">
<button type="submit" class="py-2 px-10 text-white rounded-xl bg-indigo-800">Submit</button>
<button class="py-2 px-10 text-white rounded-xl bg-indigo-800">Submit</button>
</div>
</div>
</form>
<!--Responses-->
<div v-if="Object.keys(results).length > 0" class="mt-12 flex flex-col">
<div id="answer_sec" class="hidden mt-12 flex flex-col">
<div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8 sm:block hidden">
<div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
@ -151,55 +141,24 @@
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr v-for="answer in results">
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">
{{answer.name}}
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{{answer.address}}
</td>
<td class="px-6 py-4 whitespace-nowrap">
<span
class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
{{answer.type}}
</span>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{{answer.ttl}}
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{{answer.rtt}}
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{{answer.nameserver}}
</td>
</tr>
<!--tr is added by JS-->
</tbody>
</table>
</div>
</div>
</div>
<!--On Mobile-->
<ul v-for="answer in results" class="m-4 sm:hidden block bg-indigo-100">
<li><span class="p-2 text-gray-500 font-semibold">Name:</span> {{answer.name}}</li>
<li><span class="p-2 text-gray-500 font-semibold">Address:</span> {{answer.address}}</li>
<li><span class="p-2 text-gray-500 font-semibold">Type:</span> {{answer.type}}</li>
<li><span class="p-2 text-gray-500 font-semibold">Nameserver:</span> {{answer.nameserver}}</li>
<li><span class="p-2 text-gray-500 font-semibold">TTL:</span> {{answer.ttl}}</li>
<li><span class="p-2 text-gray-500 font-semibold">RTT:</span> {{answer.rtt}}</li>
</ul>
<div id="mobile-answers-sec" class="hidden">
</div>
</div>
<!--No Answers-->
<div v-if="noRecordsFound" class="mt-12 text-center">
<div id="no-answers-sec" class="hidden mt-12 text-center">
<p class="text-xl text-gray-900">Oops! Found no records for this query.</p>
</div>
<!--Show Error-->
<div v-if="apiErrorMessage" class="mt-12 text-center">
<p class="text-xl text-red-500">{{apiErrorMessage}}</p>
<div id="api-error-sec" class="hidden mt-12 text-center">
</div>
</main>