consolidated xhttp request code

This commit is contained in:
bill bittner 2017-09-28 15:47:55 -07:00
parent 65b5384330
commit bf17f5a6ec
6 changed files with 103 additions and 89 deletions

View file

@ -192,7 +192,7 @@ db['getShortClaimIdFromLongClaimId'] = (claimId, claimName) => {
db['getShortChannelIdFromLongChannelId'] = (longChannelId, channelName) => { db['getShortChannelIdFromLongChannelId'] = (longChannelId, channelName) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
logger.debug('finding short channel id'); logger.debug(`finding short channel id for ${longChannelId} ${channelName}`);
db db
.sequelize.query(`SELECT claimId, height FROM Certificate WHERE name = '${channelName}' ORDER BY height;`, { type: db.sequelize.QueryTypes.SELECT }) .sequelize.query(`SELECT claimId, height FROM Certificate WHERE name = '${channelName}' ORDER BY height;`, { type: db.sequelize.QueryTypes.SELECT })
.then(result => { .then(result => {

View file

@ -1,28 +1,4 @@
function sendAuthRequest (channelName, password, url) { // url === /signup or /login function sendAuthRequest (channelName, password, url) {
return new Promise(function(resolve, reject) {
// make sure the claim name is still available
let xhttp;
const params = `username=${channelName}&password=${password}`; const params = `username=${channelName}&password=${password}`;
console.log(params, url); return postRequest(url, params);
xhttp = new XMLHttpRequest();
xhttp.open('POST', url, true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.responseType = 'json';
xhttp.onreadystatechange = function() {
if (this.readyState == 4 ) {
if ( this.status == 200) {
if (this.response == true) {
resolve();
} else {
reject(new NameError('Your request succedded but could not be completed'));
}
} else if (this.status == 401) {
reject('Incorrect username or password')
} else {
reject('Auth request failed with status:' + this.status);
};
}
};
xhttp.send(params);
});
} }

View file

@ -1,3 +1,46 @@
function getRequest (url) {
console.log('making GET request to', url)
return new Promise((resolve, reject) => {
let xhttp = new XMLHttpRequest();
xhttp.open('GET', url, true);
xhttp.responseType = 'json';
xhttp.onreadystatechange = () => {
if (xhttp.readyState == 4 ) {
console.log(xhttp);
if ( xhttp.status == 200) {
console.log('response:', xhttp.response);
resolve(xhttp.response);
} else {
reject('request failed with status:' + xhttp.status);
};
}
};
xhttp.send();
})
}
function postRequest (url, params) {
console.log('making POST request to', url)
return new Promise((resolve, reject) => {
let xhttp = new XMLHttpRequest();
xhttp.open('POST', url, true);
xhttp.responseType = 'json';
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.onreadystatechange = () => {
if (xhttp.readyState == 4 ) {
console.log(xhttp);
if ( xhttp.status == 200) {
console.log('response:', xhttp.response);
resolve(xhttp.response);
} else {
reject('request failed with status:' + xhttp.status);
};
}
};
xhttp.send(params);
})
}
function toggleSection(event){ function toggleSection(event){
event.preventDefault(); event.preventDefault();

View file

@ -42,7 +42,6 @@ function validateClaimName (name) {
function validateChannelName (name) { function validateChannelName (name) {
name = name.substring(name.indexOf('@') + 1); name = name.substring(name.indexOf('@') + 1);
console.log(name);
// ensure a name was entered // ensure a name was entered
if (name.length < 1) { if (name.length < 1) {
throw new ChannelNameError("You must enter a name for your channel"); throw new ChannelNameError("You must enter a name for your channel");
@ -69,27 +68,8 @@ function cleanseClaimName(name) {
// validation functions to check claim & channel name eligibility as the inputs change // validation functions to check claim & channel name eligibility as the inputs change
function isNameAvailable (name, apiUrl) { function isNameAvailable (name, apiUrl) {
return new Promise(function(resolve, reject) { const url = apiUrl + name;
// make sure the claim name is still available return getRequest(url)
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.open('GET', apiUrl + name, true);
xhttp.responseType = 'json';
xhttp.onreadystatechange = function() {
if (this.readyState == 4 ) {
if ( this.status == 200) {
if (this.response == true) {
resolve();
} else {
reject( new NameError("That name has already been claimed by someone else."));
}
} else {
reject("request to check claim name failed with status:" + this.status);
};
}
};
xhttp.send();
});
} }
function showError(errorDisplay, errorMsg) { function showError(errorDisplay, errorMsg) {
@ -112,17 +92,23 @@ function hideSuccess (successElement) {
successElement.innerHTML = ""; successElement.innerHTML = "";
} }
function checkAvailability(name, successDisplayElement, errorDisplayElement, validateName, isNameAvailable, apiUrl) { function checkAvailability(name, successDisplayElement, errorDisplayElement, validateName, isNameAvailable, errorMessage, apiUrl) {
try { try {
// check to make sure the characters are valid // check to make sure the characters are valid
validateName(name); validateName(name);
// check to make sure it is available // check to make sure it is available
isNameAvailable(name, apiUrl) isNameAvailable(name, apiUrl)
.then(function() { .then(result => {
console.log('result:', result)
if (result === true) {
hideError(errorDisplayElement); hideError(errorDisplayElement);
showSuccess(successDisplayElement) showSuccess(successDisplayElement)
} else {
hideSuccess(successDisplayElement);
showError(errorDisplayElement, errorMessage);
}
}) })
.catch(function(error) { .catch(error => {
hideSuccess(successDisplayElement); hideSuccess(successDisplayElement);
showError(errorDisplayElement, error.message); showError(errorDisplayElement, error.message);
}); });
@ -135,14 +121,14 @@ function checkAvailability(name, successDisplayElement, errorDisplayElement, val
function checkClaimName(name){ function checkClaimName(name){
const successDisplayElement = document.getElementById('input-success-claim-name'); const successDisplayElement = document.getElementById('input-success-claim-name');
const errorDisplayElement = document.getElementById('input-error-claim-name'); const errorDisplayElement = document.getElementById('input-error-claim-name');
checkAvailability(name, successDisplayElement, errorDisplayElement, validateClaimName, isNameAvailable, '/api/isClaimAvailable/'); checkAvailability(name, successDisplayElement, errorDisplayElement, validateClaimName, isNameAvailable, 'Sorry, that url ending has been taken by another user', '/api/isClaimAvailable/');
} }
function checkChannelName(name){ function checkChannelName(name){
const successDisplayElement = document.getElementById('input-success-channel-name'); const successDisplayElement = document.getElementById('input-success-channel-name');
const errorDisplayElement = document.getElementById('input-error-channel-name'); const errorDisplayElement = document.getElementById('input-error-channel-name');
name = `@${name}`; name = `@${name}`;
checkAvailability(name, successDisplayElement, errorDisplayElement, validateChannelName, isNameAvailable, '/api/isChannelAvailable/'); checkAvailability(name, successDisplayElement, errorDisplayElement, validateChannelName, isNameAvailable, 'Sorry, that Channel has been taken by another user', '/api/isChannelAvailable/');
} }
// validation function which checks all aspects of the publish submission // validation function which checks all aspects of the publish submission

View file

@ -134,6 +134,7 @@ module.exports = (app) => {
// serve content // serve content
db.getShortChannelIdFromLongChannelId(params.longId, params.name) db.getShortChannelIdFromLongChannelId(params.longId, params.name)
.then(shortId => { .then(shortId => {
console.log('sending back short channel id', shortId);
res.status(200).json(shortId); res.status(200).json(shortId);
}) })
.catch(error => { .catch(error => {

View file

@ -7,7 +7,7 @@
<select type="text" id="channel-name-select" class="select select--primary" value="channel" onchange="toggleChannel(event)"> <select type="text" id="channel-name-select" class="select select--primary" value="channel" onchange="toggleChannel(event)">
<optgroup> <optgroup>
{{#if user}} {{#if user}}
<option value="@{{user.userName}}" >@{{user.userName}}</option> <option value="{{user.channelName}}" >@{{user.userName}}</option>
{{/if}} {{/if}}
<option value="none" >None</option> <option value="none" >None</option>
</optgroup> </optgroup>
@ -34,6 +34,7 @@
const loginToChannelTool = document.getElementById('channel-login-details'); const loginToChannelTool = document.getElementById('channel-login-details');
const selectedOption = event.target.selectedOptions[0].value; const selectedOption = event.target.selectedOptions[0].value;
const urlChannel = document.getElementById('url-channel'); const urlChannel = document.getElementById('url-channel');
console.log('toggle event triggered');
if (selectedOption === 'new') { if (selectedOption === 'new') {
// show/hide the login and new channel forms // show/hide the login and new channel forms
createChannelTool.hidden = false; createChannelTool.hidden = false;
@ -53,14 +54,21 @@
hideError(document.getElementById('input-error-channel-select')); hideError(document.getElementById('input-error-channel-select'));
// update URL // update URL
if (selectedOption === 'none'){ if (selectedOption === 'none'){
console.log('selected option: none');
urlChannel.innerText = ''; urlChannel.innerText = '';
} else { } else {
console.log('selected option:', selectedOption);
// retrieve short url from db // retrieve short url from db
getRequest(`/api/shortChannelId/{{{user.channelClaimId}}}/{{{user.channelName}}}`)
.then(result => {
console.log('result', result)
// update url text // update url text
urlChannel.innerText = `${selectedOption}/`; urlChannel.innerText = `{{user.channelName}}:${result}/`;
})
.catch(error => {
console.log('error retrieving short channel id', error);
})
} }
} }
} }
</script> </script>