Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
amccloud committed May 11, 2012
0 parents commit 919a80b
Show file tree
Hide file tree
Showing 8 changed files with 331 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -0,0 +1 @@
.DS_Store
9 changes: 9 additions & 0 deletions .travis.yml
@@ -0,0 +1,9 @@
language: "node_js"
node_js:
- "0.7"
before_script:
- "export PHANTOMJS_EXECUTABLE='phantomjs --local-to-remote-url-access=yes --ignore-ssl-errors=yes'"
- "export DISPLAY=:99.0"
- "sh -e /etc/init.d/xvfb start"
script:
- "phantomjs test/runner.js"
22 changes: 22 additions & 0 deletions LICENSE
@@ -0,0 +1,22 @@
Copyright (c) 2012 Andrew McCloud

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
34 changes: 34 additions & 0 deletions README.md
@@ -0,0 +1,34 @@
# Backbone Tastypie #
Modifications to Backbone's Model an Collection so that they play nice with django-tastypie. Includes a way to easily paginate over a resource list and a way to access the associated meta information.

## Download ##
https://raw.github.com/amccloud/backbone-tastypie/master/backbone-tastypie.js

[![Build Status](https://secure.travis-ci.org/amccloud/backbone-tastypie.png)](http://travis-ci.org/amccloud/backbone-tastypie])

## Example ##
```javascript
var User = Backbone.Model.extend({
urlRoot: '/api/v1/user/'
});

var Users = Backbone.Collection.extend({
urlRoot: '/api/v1/user/'
});

// /api/v1/user/?active=true
var activeUsers = new Users({
filters: {
active: true,
}
});

// Fetch first 20 users.
activeUsers.fetch();

// Fetch and add next 20 users.
activeUsers.fetchNext();

// Total number of users.
activeUsers.meta.total_count
```
93 changes: 93 additions & 0 deletions backbone-tastypie.js
@@ -0,0 +1,93 @@
(function($, _, Backbone) {
_.extend(Backbone.Model.prototype, {
idAttribute: 'resource_uri',

url: function() {
var url = getValue(this, 'urlRoot') || getValue(this.collection, 'urlRoot') || urlError();

if (this.isNew())
return url;

return this.get('resource_uri');
},
_getId: function() {
if (this.has('id'))
return this.get('id');

return _.chain(this.get('resource_uri').split('/')).compact().last().value();
}
});

_.extend(Backbone.Collection.prototype, {
meta: {},

initialize: function(collections, options) {
_.bindAll(this, 'fetchNext', 'fetchPrevious');

this.filters = (options && options.filters) || {
limit: 20,
offset: 0
};
},
url: function(models) {
var url = this.urlRoot;

if (models) {
var ids = _.map(models, function(model) {
return model._getId();
});

url += 'set/' + ids.join(';') + '/';
}

return url + this._getQueryString();
},
parse: function(response) {
if (response && response.meta)
this.meta = response.meta;

return response && response.objects;
},
fetchNext: function(options) {
options.add = true;

this.filters.limit = this.meta.limit;
this.filters.offset = this.meta.offset + this.meta.limit;

if (this.filters.offset > this.meta.total_count)
this.filters.offset = this.meta.total_count;

return this.fetch.call(this, options);
},
fetchPrevious: function(options) {
options.add = true;

this.filters.limit = this.meta.limit;
this.filters.offset = this.meta.offset - this.meta.limit;

if (this.filters.offset < 0)
this.filters.offset = 0;

return this.fetch.call(this, options);
},
_getQueryString: function() {
if (!this.filters)
return '';

return '?' + $.param(this.filters);
}
});

// Helper function from Backbone to get a value from a Backbone
// object as a property or as a function.
var getValue = function(object, prop) {
if ((object && object[prop]))
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
};

// Helper function from Backbone that raises error when a model's
// url cannot be determined.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
})(window.$, window._, window.Backbone);
19 changes: 19 additions & 0 deletions test/index.html
@@ -0,0 +1,19 @@
<!doctype html>
<html>
<head>
<meta charset="utf8">
<title>Backbone Tastypie Test Suite</title>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.5.0.css" type="text/css">
<script src="http://code.jquery.com/qunit/qunit-git.js"></script>
<script src="https://raw.github.com/keithamus/qunit-logging/master/qunit-logging.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="http://ibjhb.github.com/mockjaxExample/src/js/lib/jquery.mockjax-1.5.0.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>
<script src="../backbone-tastypie.js"></script>
<script src="tests.js"></script>
</head>
<body>
<div id="qunit"></div>
</body>
</html>
22 changes: 22 additions & 0 deletions test/runner.js
@@ -0,0 +1,22 @@
var fs = require('fs'),
page = new WebPage(),
file = fs.absolute('test/index.html');

page.onConsoleMessage = function(message) {
console.log(message);

if (/^Tests completed in/.test(message))
phantom.exit(page.evaluate(function () {
if (window.QUnit && QUnit.config && QUnit.config.stats)
return QUnit.config.stats.bad || 0;

return 1;
}));
};

page.open('file://' + file, function(status) {
if (status !== 'success') {
console.log('FAIL to load the address');
phantom.exit(1);
}
});
131 changes: 131 additions & 0 deletions test/tests.js
@@ -0,0 +1,131 @@
var test_users = _([
{id:1, username:"andrew", resource_uri:'/api/v1/user/1/'},
{id:2, username:"jackie", resource_uri:'/api/v1/user/2/'},
{id:3, username:"genie", resource_uri:'/api/v1/user/3/'},
{id:4, username:"kirt", resource_uri:'/api/v1/user/4/'},
{id:5, username:"kory", resource_uri:'/api/v1/user/5/'},
{id:6, username:"anton", resource_uri:'/api/v1/user/6/'},
{id:7, username:"azat", resource_uri:'/api/v1/user/7/'}
]);

$.mockjax(function(request){
var userDetail = request.url.match(/\/api\/v1\/user\/(\d+)\/$/i);

if (userDetail) {
var userId = userDetail[1];

return {
success: true,
responseText: test_users.find(function(user) {
return user.id == userDetail[1];
})
};
}

var qs = {};

_.each(request.url.split('?')[1].split('&'), function(arg) {
arg = arg.split('=');
qs[arg[0]] = arg[1];
});

var limit = Number(qs.limit || 0),
offset = Number(qs.offset || 0),
objects = [];

if (limit)
objects = test_users.slice(offset, offset + limit);
else
objects = test_users.slice(offset);

return {
success: true,
responseText: {
objects: objects,
meta: {
limit: limit,
offset: offset,
total_count: test_users.value().length
}
}
};
});

var User = Backbone.Model.extend({
urlRoot: '/api/v1/user/'
});

var Users = Backbone.Collection.extend({
urlRoot: '/api/v1/user/'
});

asyncTest("parsing tastypie response", 3, function() {
var limit = 3;

var users = new Users([], {
filters: {
limit: limit,
active: true
}
});

users.fetch({
success: function(users) {
equal(users.models.length, limit);
equal(users.meta.limit, limit);
equal(users.meta.offset, 0);
start();

test("model url", 1, function() {
var user = users.first(),
compare = test_users.first();

equal(user.url(), compare.resource_uri);
});

asyncTest("fetching next page", 3, function() {
users.fetchNext({
success: function(users) {
equal(users.models.length, limit * 2);
equal(users.meta.limit, limit);
equal(users.meta.offset, limit);
start();
}
});
});
}
});
});

asyncTest("limit greater than total", 6, function() {
var limit = 100,
total = test_users.value().length;

var users = new Users([], {
filters: {
limit: limit
}
});

users.fetch({
success: function(users) {
equal(users.models.length, total);
equal(users.meta.limit, limit);
equal(users.meta.offset, 0);

users.fetchNext({
success: function(users) {
equal(users.models.length, total);
equal(users.meta.limit, limit);
equal(users.meta.offset, total);
start();
}
});
}
});
});

test("new model url", 1, function() {
var user = new User();
equal(user.url(), '/api/v1/user/');
});

0 comments on commit 919a80b

Please sign in to comment.