Git Product home page Git Product logo

angular-resource-tastypie's Introduction

#Angular Resource Tastypie RESTful AngularJs client for Django-Tastypie or equivalent schema.

Features:
1. Pagination 2. Complete CRUD 3. Abstract AJAX(J) providing operations which are similar to the [Django Model API](https://docs.djangoproject.com/en/dev/topics/db/queries/)

##Context RESTful architecture with AngularJs and Django. Architecture

IMPORTANT:
- Backend: Security rules for data persistence and access. - Frontend: [Usability](https://en.wikipedia.org/wiki/Usability) rules, only!
BENEFITS:
- Asynchronous development between frontend and backend developers. - Reuse of web developers team to create mobile applications. - The frontend is isolated, we can distribute it as an application by using [Apache Cordova](https://cordova.apache.org/). - Independent layers between business rules and usability rules of user interface. - Business rules are the same for different types of [UI](https://en.wikipedia.org/wiki/User_interface). We can create different [UIs](https://en.wikipedia.org/wiki/User_interface) with any other programming language, passing through the same business rules on the backend. - And more ...

##Requirements

Note
Requirements for the backend: - [django-cors-headers](https://github.com/ottoyiu/django-cors-headers) - [always_return_data](http://django-tastypie.readthedocs.org/en/latest/resources.html#always-return-data)

See how to use.

##Usage

angular.module('myApp', ['ngResourceTastypie'])

.config(function($tastypieProvider){
    $tastypieProvider.setResourceUrl('http://127.0.0.1:8001/api/v1/');
    $tastypieProvider.setAuth('admin','320c4e7da6ed93946f97f51e6f4c8354a098bb6e');
})

.controller('MyCtrl', ['$scope', '$tastypieResource', function($scope, $tastypieResource){

    $scope.Service = new $tastypieResource('service', {limit:5});
    $scope.Service.objects.$find();
    
}]);
  • Add the module dependency:
angular.module('myApp', ['ngResourceTastypie'])
  • Add your web services provider configuration:
.config(function($tastypieProvider){
    $tastypieProvider.setResourceUrl('http://127.0.0.1:8001/api/v1/');
    $tastypieProvider.setAuth('admin','320c4e7da6ed93946f97f51e6f4c8354a098bb6e');
})
  • Add dependency in the scope:
.controller('MyCtrl', ['$scope', '$tastypieResource', function($scope, $tastypieResource){
    ...
}]);
IMPORTANT:
```javascript $tastypieProvider.setAuth('username','api_key'); ```

This api_key was fixed only for demo purposes.
You must generate a dynamic api_key after the user login, on backend authorization system, and then configure this attribute.
With django-tastypie this task is quite simple:
http://django-tastypie.readthedocs.org/en/latest/authentication.html

//Access $tastypieProvider in the controller
//Login sample:
.controller('LoginCtrl', ['$scope', '$tastypie', '$http', function($scope, $tastypie, $http){
    $scope.login = function(){
        var data = {
            userName: $scope.userName,
            password: $scope.password
        }
        $http.post('/loginUrl', data).success(response){
            $tastypie.setAuth(response.username, response.api_key);
        }
    }
}]);

##Making queries The $tastypieResource class is held responsible for connecting on the specific "list endpoint".

Consider the following example:
We have a service called "song", which is responsible for providing the "TOP 100 SONGS CLASSIC ROCK": ``` http://127.0.0.1:8001/api/v1/song/ ``` Then: ```javascript $scope.Song = new $tastypieResource('song');

//or with default filters $scope.Song = new $tastypieResource('song',{limit:5});


- <h5>Creating objects</h5>
The "$create()" method will return a "$tastypieObjects" object.<br>
The $tastypieObjects class is held responsible for providing the "(C)reate, (R)ead, (U)pdate, (D)elete" methods.

```javascript
$scope.song = $scope.Song.objects.$create();
$scope.song.rank = 1
$scope.song.song = "Sweet Emotion"
$scope.song.artist = "Aerosmith"
$scope.song.$save();
//or
$scope.Song.objects.$create({
    rank: 1,
    song: "Sweet Emotion",
    artist: "Aerosmith"
}).$save();
//or with callback
$scope.Song.objects.$create({
    rank: 1,
    song: "Sweet Emotion",
    artist: "Aerosmith"
}).$save().then(
    function(result){
        console.log(result);
    },
    function(error){
        console.log(error);
    }
);

After saving, your obj will be updated. For example, your obj now has an "id".. wow!!

  • Updating objects
$scope.Song.objects.$update({
    id:100,
    song:'Sweet Emotion ...'
});
//or with callback
$scope.Song.objects.$update({
    id:100,
    song:'Sweet Emotion'
}).then(
    function(result){
        console.log(result);
    },
    function(error){
        console.log(error);
    }
);
//or from get
$scope.Song.objects.$get({id:100}).then(
    function(result){
        result.rank += 1;
        result.$save();
    }
);
//or from local object 
//creating
var song = $scope.Song.objects.$create();
song.rank = 1;
song.song = "Sweet Emotion";
song.artist = "Aerosmith";
song.$save();

//updating
song.rank = 2
song.$save();
  • Deleting objects
$scope.Song.objects.$delete({id:100});
//or with callback
$scope.Song.objects.$delete({id:100}).then(
    function(result){
        console.log(result);
    },
    function(error){
        console.log(error);
    }
);
//or from local object 
//creating
var song = $scope.Song.objects.$create();
song.rank = 1
song.song = "Sweet Emotion"
song.artist = "Aerosmith"
song.$save();

//deleting
song.$delete()
  • Retrieving objects

The "$find()" method will return a "$tastypiePaginator" object.
The $tastypiePaginator class is responsible for providing the "pagination control" methods, and the objects list.

//all objects
$scope.Song.objects.$find();
//or with filters
$scope.Song.objects.$find({rank__lte:10});
//or with callback
$scope.Song.objects.$find({rank__lte:10}).then(
    function(result){
        console.log(result); //The "result" is a "$tastypiePaginator" object.
    },
    function(error){
        console.log(error);
    }
);
NOTE

1. After running the "$find" method for the first time, you have inside your instance "$tastypieResource" ($scope.Song), a "$tastypiePaginator" object ($scope.Song.page).

2. For each item of "$scope.Song.page.objects" you retrieve a "$tastypieObjects" object. ;)

//All page attributes:
$scope.Song.page.meta.previous;     // URL of previous page
$scope.Song.page.meta.next;         // URL of next page
$scope.Song.page.meta.limit;        // Limit of records by page
$scope.Song.page.meta.offset;       // Current displacement records
$scope.Song.page.meta.total_count;  // Total count of found records.
$scope.Song.page.objects;           // Objects ($tastypieObjects) list of current page
$scope.Song.page.index;             // Current number page
$scope.Song.page.length;            // Pages quantity
$scope.Song.page.range;             // Numbers list of pages
        
//All page methods:
$scope.Song.page.change(index);
$scope.Song.page.next();
$scope.Song.page.previous();
$scope.Song.page.refresh();
$scope.Song.page.first();
$scope.Song.page.last();

//All methods has promise. EX:
$scope.Song.page.next().then(
    function(result){
        console.log(result); //The "result" is a "$tastypiePaginator" object.
    },
    function(error){
        console.log(error);
    }
);
//get object from resource_uri
//In this case, there is no paging. An "$tastypieObjects" is returned.
$scope.Song.objects.$get({id:100}).then(
    function(result){
        console.log(result);
    },
    function(error){
        console.log(error);
    }
);

##Class Diagram Class Diagram

##Contribute

If you found it useful, please consider paying me a coffee ;)
[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RGQ8NSYPA59FL)

##License angular-resource-tastypie is released under the MIT License.

angular-resource-tastypie's People

Contributors

mw-ferretti avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.