From 806ffee3049eb2a418bf26230538769ac70d7b21 Mon Sep 17 00:00:00 2001 From: Max Ogden Date: Thu, 30 Jun 2011 19:56:15 -0700 Subject: [PATCH] switch to jquery.couch2 for deffereds --- attachments/pages/index.html | 2 +- attachments/script/jquery.couch2.js | 63 ++++++++ attachments/script/jquery.request.js | 215 --------------------------- attachments/script/removalist.js | 29 ++-- attachments/script/site.js | 47 ++++-- 5 files changed, 112 insertions(+), 244 deletions(-) create mode 100644 attachments/script/jquery.couch2.js delete mode 100644 attachments/script/jquery.request.js diff --git a/attachments/pages/index.html b/attachments/pages/index.html index 2669f228..0c2dc40d 100644 --- a/attachments/pages/index.html +++ b/attachments/pages/index.html @@ -9,7 +9,7 @@ - + diff --git a/attachments/script/jquery.couch2.js b/attachments/script/jquery.couch2.js new file mode 100644 index 00000000..49683af6 --- /dev/null +++ b/attachments/script/jquery.couch2.js @@ -0,0 +1,63 @@ +(function($) { + + window.couch = {}; + + var cache = {}; + + var defaults = { + headers: {"Accept":"application/json"}, + dataType:"json", + contentType: "application/json", + type: "GET", + url: "/" + }; + + couch.request = function(opts) { + var key = JSON.stringify(opts); + if (cache[key]) { + var dfd = $.Deferred(); + dfd.resolve(jQuery.extend(true, {}, cache[key])); + return dfd.promise(); + } else { + var ajaxOpts = $.extend({}, defaults, opts); + ajaxOpts.dataFilter = function (data) { + cache[key] = JSON.parse(data); + return data; + }; + return $.ajax(ajaxOpts).promise(); + } + } + + couch.clearCache = function() { + cache = {}; + }; + + couch.get = function(url) { + return couch.request({url:url, type:'GET'}); + }; + + couch.db = function(name, couchRoot) { + if(!couchRoot) couchRoot = ""; + return { + name: name, + uri: couchRoot + "/" + encodeURIComponent(name) + "/", + + get: function(id) { + return couch.request({url:this.uri + id, type:"GET"}); + }, + + put: function(id, data) { + return couch.request({url:this.uri + id, type:"PUT", data:data}); + }, + + designDocs: function(opts) { + return couch.request($.extend(defaults, { + url: this.uri + "_all_docs", + data: {startkey:'"_design/"', endkey:'"_design0"', include_docs:true} + })); + } + + }; + }; + +})(jQuery); \ No newline at end of file diff --git a/attachments/script/jquery.request.js b/attachments/script/jquery.request.js deleted file mode 100644 index 1dd4a83b..00000000 --- a/attachments/script/jquery.request.js +++ /dev/null @@ -1,215 +0,0 @@ -(function() { -var define = window.define -if(!define) define = function(deps, definer) { - if(!window.jQuery) - throw new Error("Can't find jQuery"); - return definer(window.jQuery); -} - -define(['jquery'], function(jQuery) { - -// -// request.jquery -// - -var DEFAULT_TIMEOUT = 3 * 60 * 1000; // 3 minutes - -function request(options, callback) { - if(typeof options === 'string') - options = {'uri':options}; - else - options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating. - - if (!options.uri) - throw new Error("options.uri is a required argument"); - else if(typeof options.uri != "string") - throw new Error("options.uri must be a string"); - - ; $.each(['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect'], function(i, opt) { - if(options[opt]) - throw new Error("options." + opt + " is not supported"); - }) - - options.method = options.method || 'GET'; - options.headers = options.headers || {}; - - if(options.headers.host) - throw new Error("Options.headers.host is not supported"); - - /* - // Browsers do not like this. - if(options.body) - options.headers['content-length'] = options.body.length; - */ - - var headers = {}; - var beforeSend = function(xhr, settings) { - if(!options.headers.authorization && options.auth) { - debugger - options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password); - } - - for (var key in options.headers) - xhr.setRequestHeader(key, options.headers[key]); - } - - // Establish a place where the callback arguments will go. - var result = []; - - var onSuccess = function(data, reason, xhr) { - result = [null, xhr, data]; - } - - var onError = function (xhr, reason, er) { - var body = undefined; - - if(!er) { - if(reason == 'timeout') { - er = new Error("Request timeout"); - } else if(reason == 'error') { - if(xhr.status > 299 && xhr.responseText.length > 0) { - // Looks like HTTP worked, so there is no error as far as request is concerned. Simulate a success scenario. - er = null; - body = xhr.responseText; - } - } else { - er = new Error("Unknown error; reason = " + reason); - } - } - - result = [er, xhr, body]; - } - - var onComplete = function(xhr, reason) { - if(result.length === 0) - result = [new Error("Result does not exist at completion time")]; - return callback && callback.apply(this, result); - } - - - var cors_creds = !!( options.creds || options.withCredentials ); - - return jQuery.ajax({ 'async' : true - , 'cache' : (options.cache || false) - , 'contentType': (options.headers['content-type'] || 'application/x-www-form-urlencoded') - , 'type' : options.method - , 'url' : options.uri - , 'data' : (options.body || undefined) - , 'timeout' : (options.timeout || request.DEFAULT_TIMEOUT) - , 'dataType' : 'text' - , 'processData': false - , 'beforeSend' : beforeSend - , 'success' : onSuccess - , 'error' : onError - , 'complete' : onComplete - , 'xhrFields' : { 'withCredentials': cors_creds - } - }); - -}; - -request.withCredentials = false; -request.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; - -var shortcuts = [ 'get', 'put', 'post', 'head' ]; -$.each(shortcuts, function(i, shortcut) { - var method = shortcut.toUpperCase(); - var func = shortcut.toLowerCase(); - - request[func] = function(opts) { - if(typeof opts === 'string') - opts = {'method':method, 'uri':opts}; - else { - opts = JSON.parse(JSON.stringify(opts)); - opts.method = method; - } - - var args = [opts].concat(Array.prototype.slice.apply(arguments, [1])); - return request.apply(this, args); - } -}) - -request.json = function(options, callback) { - options = JSON.parse(JSON.stringify(options)); - options.headers = options.headers || {}; - options.headers['accept'] = options.headers['accept'] || 'application/json'; - - if(options.method !== 'GET') - options.headers['content-type'] = 'application/json'; - - return request(options, function(er, resp, body) { - if(!er) - body = JSON.parse(body) - return callback && callback(er, resp, body); - }) -} - -request.couch = function(options, callback) { - return request.json(options, function(er, resp, body) { - if(er) - return callback && callback(er, resp, body); - - if((resp.status < 200 || resp.status > 299) && body.error) - // The body is a Couch JSON object indicating the error. - return callback && callback(body, resp); - - return callback && callback(er, resp, body); - }) -} - -jQuery(document).ready(function() { - jQuery.request = request; -}) - -return request; - -}); - -// -// Utility -// - -// MIT License from http://phpjs.org/functions/base64_encode:358 -function b64_enc (data) { - // Encodes string using MIME base64 algorithm - var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = []; - - if (!data) { - return data; - } - - // assume utf8 data - // data = this.utf8_encode(data+''); - - do { // pack three octets into four hexets - o1 = data.charCodeAt(i++); - o2 = data.charCodeAt(i++); - o3 = data.charCodeAt(i++); - - bits = o1<<16 | o2<<8 | o3; - - h1 = bits>>18 & 0x3f; - h2 = bits>>12 & 0x3f; - h3 = bits>>6 & 0x3f; - h4 = bits & 0x3f; - - // use hexets to index into b64, and append result to encoded string - tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); - } while (i < data.length); - - enc = tmp_arr.join(''); - - switch (data.length % 3) { - case 1: - enc = enc.slice(0, -2) + '=='; - break; - case 2: - enc = enc.slice(0, -1) + '='; - break; - } - - return enc; -} - -})(); \ No newline at end of file diff --git a/attachments/script/removalist.js b/attachments/script/removalist.js index 4f7e8804..42cbb7ae 100644 --- a/attachments/script/removalist.js +++ b/attachments/script/removalist.js @@ -4,10 +4,9 @@ var removalist = function() { return (parseFloat(bytes)/1024/1024).toString().substr(0,4) + "MB" } - function renderRows(err, resp, body) { - var response = JSON.parse(body); - var rows = []; - response.rows.map(function(row) { + function renderRows(rows) { + var tableRows = []; + rows.map(function(row) { var cells = []; app.headers.map(function(header) { var value = ""; @@ -17,25 +16,24 @@ var removalist = function() { } cells.push(value); }) - rows.push({cells: cells}); + tableRows.push({cells: cells}); }) util.render('dataTable', 'dataTableContainer', { - rows: rows, + rows: tableRows, headers: app.headers }) } - function gotHeaders( err, resp, body ) { - app.csvUrl = app.baseURL + 'api/csv?headers=' + escape(body); + function gotHeaders( headers ) { + app.headers = headers; + app.csvUrl = app.baseURL + 'api/csv?headers=' + escape(JSON.stringify(headers)); util.render( 'actions', 'project-controls', $.extend({}, app.dbInfo, {url: app.csvUrl}) ); - app.headers = JSON.parse(body); - $.request($.extend({}, app.reqOpts, {uri: app.baseURL + 'api/rows?limit=10'}), renderRows); } - function gotDb( err, resp, body ) { - - app.dbInfo = JSON.parse(body); + function gotDb( dbInfo ) { + + app.dbInfo = dbInfo; $.extend(app.dbInfo, { "host": window.location.host, @@ -46,10 +44,7 @@ var removalist = function() { util.render('tableContainer', app.container, app.dbInfo); util.render('title', 'project-title', app.dbInfo); - util.render( 'generating', 'project-controls' ); - - $.request($.extend({}, app.reqOpts, {uri: app.baseURL + 'api/headers'}), gotHeaders); - + util.render( 'generating', 'project-controls' ); } return { diff --git a/attachments/script/site.js b/attachments/script/site.js index 5ca4a299..e1ebba3f 100644 --- a/attachments/script/site.js +++ b/attachments/script/site.js @@ -3,13 +3,6 @@ var app = { container: 'main_content' }; -app.reqOpts = { - uri: app.baseURL + "api", - method: "GET", - headers: {"Content-type": "application/json"}, - cache: true -} - app.handler = function(route) { route = route.path.slice(1, route.path.length); if (route.length < 1) route = "home"; @@ -17,11 +10,43 @@ app.handler = function(route) { window.scrollTo(0, 0); }; +// var query = { +// "descending" : true, +// "limit" : 20, +// success: function( data ) { +// if( data.rows.length === 0 ) { +// monocles.oldestDoc = false; +// monocles.hideLoader(); +// posts = []; +// } else { +// monocles.oldestDoc = data.rows[ data.rows.length - 1 ]; +// posts = data.rows; +// } +// renderStream(); +// } +// } +// +// if ( opts.offsetDoc ) { +// $.extend( query, { +// "startkey": opts.offsetDoc.key, +// "startkey_docid": opts.offsetDoc.id, +// "skip": 1 +// }) +// } + app.after = { home: function() { - $.request(app.reqOpts, removalist.gotDb); - + couch.request({url: app.baseURL + "api"}).then(function(db) { + removalist.gotDb(db); + couch.request({url: app.baseURL + 'api/headers'}).then(function(headers) { + removalist.gotHeaders(headers); + couch.request({url: app.baseURL + 'api/rows?limit=10'}).then(function(response) { + removalist.renderRows(response.rows); + }); + }); + }); + $( '.csv' ).live('click', ( function( e ) { window.location.href = app.csvUrl; e.preventDefault(); @@ -29,12 +54,12 @@ app.after = { } } -app.s = $.sammy(function () { +app.sammy = $.sammy(function () { this.get('', app.handler); this.get("#/", app.handler); this.get("#:route", app.handler); }); $(function() { - app.s.run(); + app.sammy.run(); }) \ No newline at end of file