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) => {
return new Promise((resolve, reject) => {
logger.debug('finding short channel id');
logger.debug(`finding short channel id for ${longChannelId} ${channelName}`);
db
.sequelize.query(`SELECT claimId, height FROM Certificate WHERE name = '${channelName}' ORDER BY height;`, { type: db.sequelize.QueryTypes.SELECT })
.then(result => {

View file

@ -1,28 +1,4 @@
function sendAuthRequest (channelName, password, url) { // url === /signup or /login
return new Promise(function(resolve, reject) {
// make sure the claim name is still available
let xhttp;
const params = `username=${channelName}&password=${password}`;
console.log(params, url);
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);
});
function sendAuthRequest (channelName, password, url) {
const params = `username=${channelName}&password=${password}`;
return postRequest(url, 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){
event.preventDefault();

View file

@ -42,7 +42,6 @@ function validateClaimName (name) {
function validateChannelName (name) {
name = name.substring(name.indexOf('@') + 1);
console.log(name);
// ensure a name was entered
if (name.length < 1) {
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
function isNameAvailable (name, apiUrl) {
return new Promise(function(resolve, reject) {
// make sure the claim name is still available
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();
});
const url = apiUrl + name;
return getRequest(url)
}
function showError(errorDisplay, errorMsg) {
@ -112,17 +92,23 @@ function hideSuccess (successElement) {
successElement.innerHTML = "";
}
function checkAvailability(name, successDisplayElement, errorDisplayElement, validateName, isNameAvailable, apiUrl) {
function checkAvailability(name, successDisplayElement, errorDisplayElement, validateName, isNameAvailable, errorMessage, apiUrl) {
try {
// check to make sure the characters are valid
validateName(name);
// check to make sure it is available
isNameAvailable(name, apiUrl)
.then(function() {
hideError(errorDisplayElement);
showSuccess(successDisplayElement)
.then(result => {
console.log('result:', result)
if (result === true) {
hideError(errorDisplayElement);
showSuccess(successDisplayElement)
} else {
hideSuccess(successDisplayElement);
showError(errorDisplayElement, errorMessage);
}
})
.catch(function(error) {
.catch(error => {
hideSuccess(successDisplayElement);
showError(errorDisplayElement, error.message);
});
@ -135,14 +121,14 @@ function checkAvailability(name, successDisplayElement, errorDisplayElement, val
function checkClaimName(name){
const successDisplayElement = document.getElementById('input-success-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){
const successDisplayElement = document.getElementById('input-success-channel-name');
const errorDisplayElement = document.getElementById('input-error-channel-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

View file

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

View file

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