DRY up Promise creation in api.js

Since calls to ajax() are always wrapped in promises, we can internalize
that pattern in the ajax function itself.

// FREEBIE
This commit is contained in:
lilia 2015-07-13 11:52:49 -07:00
parent 3711e0a6cd
commit b40a8696b7
2 changed files with 166 additions and 212 deletions

View file

@ -38998,39 +38998,41 @@ TextSecureServer = function () {
* jsonData: JSON data sent in the request body * jsonData: JSON data sent in the request body
*/ */
function ajax(url, options) { function ajax(url, options) {
var error = new Error(); // just in case, save stack here. return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest(); var error = new Error(); // just in case, save stack here.
xhr.open(options.type, url, true /*async*/); var xhr = new XMLHttpRequest();
xhr.open(options.type, url, true /*async*/);
if ( options.responseType ) { if ( options.responseType ) {
xhr[ 'responseType' ] = options.responseType; xhr[ 'responseType' ] = options.responseType;
} }
if (options.user && options.password) { if (options.user && options.password) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(getString(options.user) + ":" + getString(options.password))); xhr.setRequestHeader("Authorization", "Basic " + btoa(getString(options.user) + ":" + getString(options.password)));
} }
if (options.contentType) { if (options.contentType) {
xhr.setRequestHeader( "Content-Type", options.contentType ); xhr.setRequestHeader( "Content-Type", options.contentType );
} }
xhr.onload = function() { xhr.onload = function() {
var result = xhr.response; var result = xhr.response;
if ( (!xhr.responseType || xhr.responseType === "text") && if ( (!xhr.responseType || xhr.responseType === "text") &&
typeof xhr.responseText === "string" ) { typeof xhr.responseText === "string" ) {
result = xhr.responseText; result = xhr.responseText;
} }
if (options.dataType === 'json') { if (options.dataType === 'json') {
try { result = JSON.parse(xhr.responseText + ''); } catch(e) {} try { result = JSON.parse(xhr.responseText + ''); } catch(e) {}
} }
if ( 0 <= xhr.status && xhr.status < 400) { if ( 0 <= xhr.status && xhr.status < 400) {
options.success(result, xhr.status); resolve(result, xhr.status);
} else { } else {
options.error(HTTPError(xhr.status, result, error.stack)); reject(HTTPError(xhr.status, result, error.stack));
} }
}; };
xhr.onerror = function() { xhr.onerror = function() {
options.error(HTTPError(xhr.status, null, error.stack)); reject(HTTPError(xhr.status, null, error.stack));
}; };
xhr.send( options.data || null ); xhr.send( options.data || null );
});
} }
function HTTPError(code, response, stack) { function HTTPError(code, response, stack) {
@ -39040,7 +39042,7 @@ TextSecureServer = function () {
var e = new Error(message); var e = new Error(message);
e.name = 'HTTPError'; e.name = 'HTTPError';
e.code = code; e.code = code;
e.stack = stack; e.stack = stack;
if (response) { if (response) {
e.response = response; e.response = response;
} }
@ -39057,52 +39059,47 @@ TextSecureServer = function () {
param.password = textsecure.storage.get("password"); param.password = textsecure.storage.get("password");
} }
return new Promise(function (resolve, reject) { return ajax(URL_BASE + URL_CALLS[param.call] + param.urlParameters, {
ajax(URL_BASE + URL_CALLS[param.call] + param.urlParameters, {
type : param.httpType, type : param.httpType,
data : param.jsonData && textsecure.utils.jsonThing(param.jsonData), data : param.jsonData && textsecure.utils.jsonThing(param.jsonData),
contentType : 'application/json; charset=utf-8', contentType : 'application/json; charset=utf-8',
dataType : 'json', dataType : 'json',
user : param.user, user : param.user,
password : param.password, password : param.password
success : resolve, }).catch(function(e) {
error : function(e) { var code = e.code;
var code = e.code; if (code === 200) {
if (code === 200) { // happens sometimes when we get no response
// happens sometimes when we get no response // (TODO: Fix server to return 204? instead)
// (TODO: Fix server to return 204? instead) return null;
resolve(null); }
return; var message;
} switch (code) {
var message; case -1:
switch (code) { message = "Failed to connect to the server, please check your network connection.";
case -1: break;
message = "Failed to connect to the server, please check your network connection."; case 413:
break; message = "Rate limit exceeded, please try again later.";
case 413: break;
message = "Rate limit exceeded, please try again later."; case 403:
break; message = "Invalid code, please try again.";
case 403: break;
message = "Invalid code, please try again."; case 417:
break; // TODO: This shouldn't be a thing?, but its in the API doc?
case 417: message = "Number already registered.";
// TODO: This shouldn't be a thing?, but its in the API doc? break;
message = "Number already registered."; case 401:
break; case 403:
case 401: message = "Invalid authentication, most likely someone re-registered and invalidated our registration.";
case 403: break;
message = "Invalid authentication, most likely someone re-registered and invalidated our registration."; case 404:
break; message = "Number is not registered with TextSecure.";
case 404: break;
message = "Number is not registered with TextSecure."; default:
break; message = "The server rejected our query, please file a bug report.";
default: }
message = "The server rejected our query, please file a bug report."; e.message = message
} throw e;
e.message = message
reject(e);
}
});
}); });
}; };
@ -39239,18 +39236,10 @@ TextSecureServer = function () {
urlParameters : '/' + id, urlParameters : '/' + id,
do_auth : true, do_auth : true,
}).then(function(response) { }).then(function(response) {
return new Promise(function(resolve, reject) { return ajax(response.location, {
ajax(response.location, { type : "GET",
type : "GET", responseType: "arraybuffer",
responseType: "arraybuffer", contentType : "application/octet-stream"
contentType: "application/octet-stream",
success : resolve,
error : function(e) {
e.message = 'Failed to download attachment';
reject(e);
}
});
}); });
}); });
}; };
@ -39262,27 +39251,15 @@ TextSecureServer = function () {
httpType : 'GET', httpType : 'GET',
do_auth : true, do_auth : true,
}).then(function(response) { }).then(function(response) {
return new Promise(function(resolve, reject) { return ajax(response.location, {
ajax(response.location, { type : "PUT",
type : "PUT", contentType : "application/octet-stream",
contentType : "application/octet-stream", data : encryptedBin,
data : encryptedBin, processData : false,
processData : false, }).then(function() {
success : function() { // Parse the id as a string from the location url
try { // (workaround for ids too large for Javascript numbers)
// Parse the id as a string from the location url return response.location.match(id_regex)[1];
// (workaround for ids too large for Javascript numbers)
var id = response.location.match(id_regex)[1];
resolve(id);
} catch(e) {
reject(e);
}
},
error : function(e) {
e.message = 'Failed to upload attachment';
reject(e);
}
});
}); });
}); });
}; };

View file

@ -53,39 +53,41 @@ TextSecureServer = function () {
* jsonData: JSON data sent in the request body * jsonData: JSON data sent in the request body
*/ */
function ajax(url, options) { function ajax(url, options) {
var error = new Error(); // just in case, save stack here. return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest(); var error = new Error(); // just in case, save stack here.
xhr.open(options.type, url, true /*async*/); var xhr = new XMLHttpRequest();
xhr.open(options.type, url, true /*async*/);
if ( options.responseType ) { if ( options.responseType ) {
xhr[ 'responseType' ] = options.responseType; xhr[ 'responseType' ] = options.responseType;
} }
if (options.user && options.password) { if (options.user && options.password) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(getString(options.user) + ":" + getString(options.password))); xhr.setRequestHeader("Authorization", "Basic " + btoa(getString(options.user) + ":" + getString(options.password)));
} }
if (options.contentType) { if (options.contentType) {
xhr.setRequestHeader( "Content-Type", options.contentType ); xhr.setRequestHeader( "Content-Type", options.contentType );
} }
xhr.onload = function() { xhr.onload = function() {
var result = xhr.response; var result = xhr.response;
if ( (!xhr.responseType || xhr.responseType === "text") && if ( (!xhr.responseType || xhr.responseType === "text") &&
typeof xhr.responseText === "string" ) { typeof xhr.responseText === "string" ) {
result = xhr.responseText; result = xhr.responseText;
} }
if (options.dataType === 'json') { if (options.dataType === 'json') {
try { result = JSON.parse(xhr.responseText + ''); } catch(e) {} try { result = JSON.parse(xhr.responseText + ''); } catch(e) {}
} }
if ( 0 <= xhr.status && xhr.status < 400) { if ( 0 <= xhr.status && xhr.status < 400) {
options.success(result, xhr.status); resolve(result, xhr.status);
} else { } else {
options.error(HTTPError(xhr.status, result, error.stack)); reject(HTTPError(xhr.status, result, error.stack));
} }
}; };
xhr.onerror = function() { xhr.onerror = function() {
options.error(HTTPError(xhr.status, null, error.stack)); reject(HTTPError(xhr.status, null, error.stack));
}; };
xhr.send( options.data || null ); xhr.send( options.data || null );
});
} }
function HTTPError(code, response, stack) { function HTTPError(code, response, stack) {
@ -95,7 +97,7 @@ TextSecureServer = function () {
var e = new Error(message); var e = new Error(message);
e.name = 'HTTPError'; e.name = 'HTTPError';
e.code = code; e.code = code;
e.stack = stack; e.stack = stack;
if (response) { if (response) {
e.response = response; e.response = response;
} }
@ -112,52 +114,47 @@ TextSecureServer = function () {
param.password = textsecure.storage.get("password"); param.password = textsecure.storage.get("password");
} }
return new Promise(function (resolve, reject) { return ajax(URL_BASE + URL_CALLS[param.call] + param.urlParameters, {
ajax(URL_BASE + URL_CALLS[param.call] + param.urlParameters, {
type : param.httpType, type : param.httpType,
data : param.jsonData && textsecure.utils.jsonThing(param.jsonData), data : param.jsonData && textsecure.utils.jsonThing(param.jsonData),
contentType : 'application/json; charset=utf-8', contentType : 'application/json; charset=utf-8',
dataType : 'json', dataType : 'json',
user : param.user, user : param.user,
password : param.password, password : param.password
success : resolve, }).catch(function(e) {
error : function(e) { var code = e.code;
var code = e.code; if (code === 200) {
if (code === 200) { // happens sometimes when we get no response
// happens sometimes when we get no response // (TODO: Fix server to return 204? instead)
// (TODO: Fix server to return 204? instead) return null;
resolve(null); }
return; var message;
} switch (code) {
var message; case -1:
switch (code) { message = "Failed to connect to the server, please check your network connection.";
case -1: break;
message = "Failed to connect to the server, please check your network connection."; case 413:
break; message = "Rate limit exceeded, please try again later.";
case 413: break;
message = "Rate limit exceeded, please try again later."; case 403:
break; message = "Invalid code, please try again.";
case 403: break;
message = "Invalid code, please try again."; case 417:
break; // TODO: This shouldn't be a thing?, but its in the API doc?
case 417: message = "Number already registered.";
// TODO: This shouldn't be a thing?, but its in the API doc? break;
message = "Number already registered."; case 401:
break; case 403:
case 401: message = "Invalid authentication, most likely someone re-registered and invalidated our registration.";
case 403: break;
message = "Invalid authentication, most likely someone re-registered and invalidated our registration."; case 404:
break; message = "Number is not registered with TextSecure.";
case 404: break;
message = "Number is not registered with TextSecure."; default:
break; message = "The server rejected our query, please file a bug report.";
default: }
message = "The server rejected our query, please file a bug report."; e.message = message
} throw e;
e.message = message
reject(e);
}
});
}); });
}; };
@ -294,18 +291,10 @@ TextSecureServer = function () {
urlParameters : '/' + id, urlParameters : '/' + id,
do_auth : true, do_auth : true,
}).then(function(response) { }).then(function(response) {
return new Promise(function(resolve, reject) { return ajax(response.location, {
ajax(response.location, { type : "GET",
type : "GET", responseType: "arraybuffer",
responseType: "arraybuffer", contentType : "application/octet-stream"
contentType: "application/octet-stream",
success : resolve,
error : function(e) {
e.message = 'Failed to download attachment';
reject(e);
}
});
}); });
}); });
}; };
@ -317,27 +306,15 @@ TextSecureServer = function () {
httpType : 'GET', httpType : 'GET',
do_auth : true, do_auth : true,
}).then(function(response) { }).then(function(response) {
return new Promise(function(resolve, reject) { return ajax(response.location, {
ajax(response.location, { type : "PUT",
type : "PUT", contentType : "application/octet-stream",
contentType : "application/octet-stream", data : encryptedBin,
data : encryptedBin, processData : false,
processData : false, }).then(function() {
success : function() { // Parse the id as a string from the location url
try { // (workaround for ids too large for Javascript numbers)
// Parse the id as a string from the location url return response.location.match(id_regex)[1];
// (workaround for ids too large for Javascript numbers)
var id = response.location.match(id_regex)[1];
resolve(id);
} catch(e) {
reject(e);
}
},
error : function(e) {
e.message = 'Failed to upload attachment';
reject(e);
}
});
}); });
}); });
}; };