diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 00000000..0f099897
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,10 @@
+# editorconfig.org
+root = true
+
+[*]
+indent_style = space
+indent_size = 2
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 00000000..044bad5c
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,24 @@
+*Switch to the Preview tab to read this message in the Github issue form.*
+
+The project lacks resources to answer questions regarding general usage and problems occurring from misconfiguration and or improper use. That's why we kindly ask you to following the following guidelines when considering opening an issue.
+
+**Before opening an issue:**
+
+* Please **carefully read the README** and make sure that your question isn't already answered in the documentation.
+* Please **review [the configuration methods](https://github.com/mgonto/restangular#configuring-restangular) and [methods description](https://github.com/mgonto/restangular#methods-description)** once more.
+* Please **search the existing issue list** to see if there's already an issue **open or closed** that solves your problem.
+* Please **search for and/or ask your question on [StackOverflow](http://stackoverflow.com/search?q=restangular)**. You will get answers more quickly there than here.
+* Please **debug your problem long and hard** enough to make sure the issue is in Restangular and not in your code and/or backend.
+
+**When opening an issue:**
+
+* Please **create a live Plunker** (fork [this Plunker](http://plnkr.co/edit/26Heuv5F6hUgxpNWNTee?p=info)) demonstrating the problem, use [httpbin](https://httpbin.org/) or [JSONPlaceholder](https://jsonplaceholder.typicode.com/) or similar as backend if needed.
+* Please **write your issue in a clear and succint manner**, so that all the details of your issue are easy to understand and fully explained.
+* Please **enclose your code in [fenced blocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/)** for readability.
+
+The maintainers may opt to close issues that don't follow these guidelines.
+
+**Also remember:**
+
+* Pull requests fixing problems are highly appreciated ;)
+
diff --git a/.gitignore b/.gitignore
index 01304908..e8a68eb0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,5 +13,7 @@ results
lib
node_modules
components
+coverage
bower_components
npm-debug.log
+.idea
diff --git a/.jshintrc b/.jshintrc
new file mode 100644
index 00000000..3589dc31
--- /dev/null
+++ b/.jshintrc
@@ -0,0 +1,23 @@
+{
+ "boss": true,
+ "curly": true,
+ "eqeqeq": true,
+ "eqnull": true,
+ "expr": true,
+ "immed": true,
+ "indent": 2,
+ "maxlen": 140,
+ "noarg": true,
+ "onevar": true,
+ "quotmark": "single",
+ "smarttabs": true,
+ "trailing": true,
+ "undef": true,
+ "unused": true,
+ "browser": true,
+ "globals": {
+ "module": true,
+ "angular": true,
+ "_": true
+ }
+}
diff --git a/.travis.yml b/.travis.yml
index 1426a7a2..20b0f596 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,11 @@
language: node_js
node_js:
- - "0.10"
+ - "7.0"
before_script:
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
+ - 'npm install -g bower grunt-cli'
+ - 'bower install --config.interactive=false'
+
+script: grunt travis
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d0eeab4..b768c53e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,151 +1,77 @@
-#1.0.9
-* **BREAKING CHANGE**: Restangular methods created with `addRestangularMethod` will change its signature depending on the opreation. If the operation is safe (GET, OPTIONS, etc.), the signature is methodName(params, headers, elemForBody). If it's not safe (POST, PUT, etc.), the signature is methodName(elemForBody, params, headers). This is to facilitate using them as when it's not safe, you're usually going to set a body
-* Now you can configure default request parameters per method and for everything as well
-* Added the ability to use Cannonical IDs. They're used if you need to change Primary Key (ID) of the element (Really weird case).
-* If response is null or undefined, the element sent in the request ISN'T used anymore. This is to have clarity of what's returned by the server and also to fix one bug.
-* Added tests
-* Fixed bug with ID when it was an empty string
-* Added missing ';'.
-
-
-#1.0.7
-* `baseUrl` can now be set either with or without ending `/` and it'll work
-
-#1.0.5
-* Several bug fixes
-* Added `parentless` configuration to ignore nested restful URLs
-
-#1.0.2
-* First final release
-* Added `one` and `all` to all collection methods
-* Added `fullResponse` for getting the full `$http` response in every call
-* Improved documentation on `addElemTransformer`
-* Configuration can be set globally on either `RestangularProvider` or `Restangular`
-
-#0.8.9
-* Fix call to `isOverridenMethod` in `setMethodOverriders`.
-
-#0.8.8
-* Removed extra trailling slash for elements without ID. Thanks @cboden
-
-#0.8.7
-* Bugfix for Refactor
-
-#0.8.6
-* Ditched the buggy `$resource` and using `$http` inside :D
-
-#0.8.4
-* Fixed bug with defaultHttpFields for scoped configuration
-* Added `defaultHeaders`
-
-#0.8.3
-* Fixed bug with URLHandler. Now it uses local configuration as well
-* Added error interceptor
-* Fixed minor bugs
-
-
-#0.8.0
-* Big refactor to use scoped configurations
-
-#0.7.3
-* All configuration can be done via either `Restangular` or `RestangularProvider`
-* url field now is called getRestangularUrl
-* `id` configuration from `restangularFields` now accepts nested (dotted) properties
-
-#0.7.1
-* Added `defaultRequestParams` to set default request query parameters
-
-#0.7.0
-* RequestInterceptor wasn't being called in getList
-* Removed extra `/` when no restangularWhat is provided. This is fixed by Angular's team since version 1.1.5 but this fixes it for all versions including 1.0.X
-* Added documentation for supported AngularJS versions
-* Added url method to elements which returns the URL of the current object
-
-# 0.6.9
-* Wrapping everything in an anonymous self executed function to not expose anything
-
-# 0.6.7
-* Bug fix for a regresion error using _.omit
-* Added element transformers to transform any Restangularized element.
-* Added putElement method to collection to put a certain element at an index and return a promise of the updated array.
-
-# 0.6.5
-* Added `Restangular.copy` for copying objects
-
-# 0.6.4
-* added methodOverriders to override any HTTP Method
-* Added requestInterceptor
-
-# 0.6.3
-* Added `defaultHttpFields` configuration property
-
-# 0.6.2
-* URL suffix is unescaped now
-
-# 0.6.1
-* Elements are striped from Restangular fields before being sent to the server
-
-# 0.6.0
-* Fixed bug when adding metadata to response in ResopnseExtractor. It wasn't being added
-* Added enhanced promises. [Check the section in README](https://github.com/mgonto/restangular/blob/master/README.md#enhanced-promises).
-
-# 0.5.5
-* Changed by default from Underscore to Lodash. They both can be used anyway. (thanks @pauldijou)
-* Added tests for both Underscore and Lodash to check it's working. (thanks @pauldijou)
-
-# 0.5.4
-* Added onElemRestangularized hook
-* Added posibility to add your own Restangular methods
-
-# 0.5.3
-* Added the posibility to do URL Building and RequestLess tree navigations
-* Added alias to `do[method]`. For example, Now you can do `customPOST` as well as `doPOST`
-
-# 0.5.2
-* responseExtractor renamed to responseInterceptor. Added alias from responseExtractor to responseInterceptor to mantain backwards compatibility
-* responseExtractor now receives 4 parameters. Response, operation, what (path of current element) and URL
-* Error function for any Restangular action now receives a response to get StatusCode and other interesting stuff
-
-# 0.5.1
-* Added listTypeIsArray property to set getList as not an array.
-
-# 0.5.0
-* Added `requestSuffix`configuration for requests ending en .json
-* `what` field is now configurable and not hardcoded anymore
-* All instance variables from `RestangularProvider` are now local variables to reduce visibility
-* Fully functional version with all desired features
-
-# 0.4.6
-* Added Custom methods to all Restangular objects. Check it out in the README
-
-# 0.4.5
-* Fixed but that didn't let ID to be 0.
-* Added different Collection methods and Element methods
-* Added posibility po do a post in a collection to post an element to itself
-* Added Travis CI for build
-* Fixed bug with parentResource after a post of a new element
-* When doing a post, if no element is returned, we enhance the object received as a parameter
-
-# 0.3.4
-* Added new HTTP methods to use: Patch, Head, Trace and Options (thanks @pauldijou)
-* Added tests with Karma for all functionality.
-
-# 0.3.3
-* Restangular fields can now be configured. You can set the id, route and parentResource fields. They're not hardcoded anymore
-
-# 0.3.2
-* Added ResponseExtractor for when the real data is wrapped in an envelope in the WebServer response.
-
-# 0.3.1
-
-* Now all methods accept Headers. You can query `account.getList('buildings', {query: 'param'}, {'header': 'mine'})`
-
-# 0.2.1
-
-* Added query params to all methods. getList, post, put, get and delete accept query params now.
-
-# 0.2.0
-* Added post method to all elements. Now you can also create new elements by calling `account.post('buildings', {name: "gonto"})`.
-
-# 0.1.1
-* Changed `elem.delete()` to `elem.remove()` due to errors with Closure Compiler in Play 2
+
+## 1.6.1 (2017-01-06)
+
+### Bug fixes
+
+* fix(copy) Collections are now copied/cloned properly ([c92b138](https://github.com/mgonto/restangular/commit/c92b138))
+* fix(copy) Copying collections now correctly sets route, fromServer and parent on the copy ([7fd668b](https://github.com/mgonto/restangular/commit/7fd668b))
+* fix(elementTransformer) matchTransformer now doesn't throw if route is undefined ([fb242ae](https://github.com/mgonto/restangular/commit/fb242ae))
+
+### Docs
+
+* chore(docs): update contribution guidelines ([c49ca45](https://github.com/mgonto/restangular/commit/c49ca45))
+* fix(docs): add link to david-dm.org from badge ([2bfb745](https://github.com/mgonto/restangular/commit/2bfb745))
+* chore(docs) Add new example production site ([2596035](https://github.com/mgonto/restangular/commit/2596035))
+* chore(docs) Add note about pull requests and github preview tab ([6883075](https://github.com/mgonto/restangular/commit/6883075))
+* chore(docs) Apply automatic formatting to code and spec ([bc16122](https://github.com/mgonto/restangular/commit/bc16122))
+* chore(docs) Reformat changelog, add unreleased section ([8bfa685](https://github.com/mgonto/restangular/commit/8bfa685))
+* chore(docs) Update issue guidelines to include StackOverflow as source for solutions to problems ([34b0e9a](https://github.com/mgonto/restangular/commit/34b0e9a))
+* chore(docs) Update link to demo Plunker, rephrase ([7c30615](https://github.com/mgonto/restangular/commit/7c30615))
+* chore(test) fix jshint errors in spec file ([1a988cb](https://github.com/mgonto/restangular/commit/1a988cb))
+* feat(docs) Add FAQ about cancelling request ([8552c51](https://github.com/mgonto/restangular/commit/8552c51)), closes [#926](https://github.com/mgonto/restangular/issues/926) [#1145](https://github.com/mgonto/restangular/issues/1145) [#1377](https://github.com/mgonto/restangular/issues/1377) [#1391](https://github.com/mgonto/restangular/issues/1391)
+
+### Other
+
+* chore(changelog): upgrade package and config ([58caacd](https://github.com/mgonto/restangular/commit/58caacd))
+* chore(dependencies): Update lodash version to ~4.17.0 as in unit tests ([e0b68a0](https://github.com/mgonto/restangular/commit/e0b68a0))
+* chore(deps): upgrade dev dependencies, fix tests (#1450) ([b583197](https://github.com/mgonto/restangular/commit/b583197)), closes [#1450](https://github.com/mgonto/restangular/issues/1450)
+* chore(travis): change travis script and include coveralls ([ca9856a](https://github.com/mgonto/restangular/commit/ca9856a))
+* test(coverage): add coverage and coveralls.io integration ([fdd5de6](https://github.com/mgonto/restangular/commit/fdd5de6))
+* Update dist files ([7c245a2](https://github.com/mgonto/restangular/commit/7c245a2))
+
+
+## 1.6.0 (2016-12-25)
+
+* Url now supports unescaped suffix (0350bcd)
+* Added Restangular Plunkr example (c4ef002)
+* Now id can be a nested property (a94228b)
+* Add withHttpConfig to objects created with .service (e8f7295)
+* Add support for angularjs dependency injection using commonjs require syntax (f02db83)
+* Fix missing 'get' in decoupled service (8096ce1)
+* Avoid restangularizing an undefined element in restangularizeCollecti onAndElements. (0f8b562)
+* Fixes #1167: Extend condition to treat '0, which as a falsy value currently fails, as a valid ID (95ea231)
+* Add customPatch method (01297fe)
+* Added UMD snippet (caab5e6)
+* Support BaseUrl with athority without schema (5f3eacb)
+* Add ability to restangularize a collection with fromServer set (51066ec)
+* Add configuration option to use plain() by default (94ffaf0)
+* Fix fromServer param while copying (b53f4b6)
+* Rename CONTRIBUTE.md to CONTRIBUTING.md in accordance with GitHub's spec (c17df47)
+* Remove moot `version` property from bower.json (1a585f3)
+* Add more realistic POST response for accounts, with id (#943) (11fb475)
+* Added context/explanation of when to use JSONP. (fec9b27)
+* Add regexp matching for route to element transformers (#1430) (de8f561)
+
+
+## 1.5.2 (2016-02-15)
+
+* Change \_.contains to \_.includes for compatability with lodash >= 4.0
+
+
+## 1.5.1 (2015-04-03)
+
+* Release 1.5.0
+* Updated zip
+* Merge branch 'master' of github.com:mgonto/restangular
+* Merge pull request #1081 from rajeshwarpatlolla/develop
+* Merge pull request #1079 from wching/master
+* change in README file
+* url modified for 'Chain methods together to easily build complex requests'
+* Update README.md
+* Update README.md
+
+
+## 1.5.0 (2015-04-03)
+
+* Tons of bug fixes
+* Upgraded Lodash to 1.3.0
diff --git a/CONTRIBUTE.md b/CONTRIBUTE.md
deleted file mode 100644
index 73a2b43f..00000000
--- a/CONTRIBUTE.md
+++ /dev/null
@@ -1,17 +0,0 @@
-In order to Contribute just git clone the repository and then run:
-
-```
-npm install grunt-cli --global
-npm install
-grunt
-```
-
-Be sure to have PhantomJS installed as Karma tests use it. Otherwise, in mac just run
-
-```
-brew install phantomjs
-```
-
-All changes must be done in src/restangular.js and then after running grunt all changes will be submited to dist/
-
-Please submit a Pull Request or create issues for anything you want :).
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 00000000..59451f29
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,67 @@
+# Issues
+
+Read the [issue guidlines](.github/ISSUE_TEMPLATE.md) before opening an issue!
+
+# How to submit PRs
+
+## Install env
+
+In order to contribute just create your own [fork](https://help.github.com/articles/fork-a-repo/)
+of the repository and then run:
+
+```
+git clone git@github.com:/restangular.git
+cd restangular
+npm install grunt-cli --global
+npm install
+```
+
+## Create a branch
+
+Create a branch for your code changes
+
+`git checkout -b my_awesome_fix`
+
+## Write tests
+
+When making changes to the code, please always **write a test case** for
+your topic before making the change. Watch the test fail, then
+implement the change and watch the test succeed.
+
+Tests are run with `grunt test`.
+
+## Keep the style
+
+When you're done with your code, run `grunt jshint` to check
+if you code follow the same simple coding design as the rest of the project.
+Consider integrating `jshint` in your editor to get real time feedback on your
+style as you're coding.
+
+## Commit message format
+
+Please write your commit messages in the [angular conventional changelog](https://github.com/conventional-changelog/conventional-changelog-angular/blob/master/convention.md) format. This will help
+us to keep a decent [CHANGELOG](CHANGELOG.md) with minimum effort. Check previous commit
+messages for examples.
+
+## Update docs
+
+If your code change includes new features, please include an update to the [README.md](README.md)
+explaining your feature.
+
+**Don't**, however, generate distribution files (the files in [dist](dist)). This will be done
+on a regular basis by maintainers as PRs are merged.
+
+## Squash commits
+
+Please consider squasing the commits in your topic branch into a single commit including
+all changes needed. This will make the PR cleaner and the change history more easy to follow
+after the PR has been merged. Also, the CHANGELOG will make more sense.
+
+Look [here](https://ariejan.net/2011/07/05/git-squash-your-latests-commits-into-one/) and
+[here](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Squashing-Commits) for how to.
+
+## Sumbit the PR
+
+Now you're ready to [open a PR](https://help.github.com/articles/creating-a-pull-request-from-a-fork/).
+
+Thanks!
diff --git a/Gruntfile.js b/Gruntfile.js
index e6a5bc56..13420589 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -1,18 +1,19 @@
-'use strict';
-
module.exports = function(grunt) {
+ 'use strict';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
- banner: '/**\n' +
- ' * <%= pkg.description %>\n' +
- ' * @version v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' +
- ' * @link <%= pkg.homepage %>\n' +
- ' * @author <%= pkg.author %>\n' +
- ' * @license MIT License, http://www.opensource.org/licenses/MIT\n' +
- ' */\n'
+ banner: [
+ '/**',
+ ' * <%= pkg.description %>',
+ ' * @version v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>' +
+ ' * @link <%= pkg.homepage %>',
+ ' * @author <%= pkg.author %>',
+ ' * @license MIT License, http://www.opensource.org/licenses/MIT',
+ ' */'
+ ].join('\n')
},
dirs: {
dest: 'dist'
@@ -27,12 +28,10 @@ module.exports = function(grunt) {
}
},
zip: {
- '<%= dirs.dest %>/restangular.zip': ['<%= dirs.dest %>/<%= pkg.name %>.js', '<%= dirs.dest %>/<%= pkg.name %>.min.js']
- },
- bower: {
- dev: {
- dest: '<%= dirs.dest %>/dependencies'
- }
+ '<%= dirs.dest %>/restangular.zip': [
+ '<%= dirs.dest %>/<%= pkg.name %>.js',
+ '<%= dirs.dest %>/<%= pkg.name %>.min.js'
+ ]
},
bowerInstall: {
install: {
@@ -50,24 +49,7 @@ module.exports = function(grunt) {
jshint: {
files: ['Gruntfile.js', 'src/*.js'],
options: {
- curly: false,
- browser: true,
- eqeqeq: true,
- immed: true,
- latedef: true,
- newcap: true,
- noarg: true,
- sub: true,
- undef: true,
- boss: true,
- eqnull: true,
- expr: true,
- node: true,
- globals: {
- exports: true,
- angular: false,
- $: false
- }
+ jshintrc: true
}
},
karma: {
@@ -78,6 +60,11 @@ module.exports = function(grunt) {
singleRun: true,
autoWatch: false
},
+ debug: {
+ singleRun: false,
+ autoWatch: true,
+ browsers: ['Chrome']
+ },
travis: {
singleRun: true,
autoWatch: false,
@@ -98,9 +85,45 @@ module.exports = function(grunt) {
autoWatch: true
}
},
- changelog: {
+ coveralls: {
+ // Options relevant to all targets
options: {
- dest: 'CHANGELOG.md'
+ // When true, grunt-coveralls will only print a warning rather than
+ // an error, to prevent CI builds from failing unnecessarily (e.g. if
+ // coveralls.io is down). Optional, defaults to false.
+ force: false
+ },
+
+ restangular: {
+ // LCOV coverage file (can be string, glob or array)
+ src: 'coverage/**/lcov.info',
+ options: {
+ // Any options for just this target
+ }
+ },
+ },
+ conventionalChangelog: {
+ options: {
+ changelogOpts: {
+ // conventional-changelog options go here
+ outputUnreleased: true,
+ // preset: 'angular'
+ },
+ context: {
+ // context goes here
+ },
+ gitRawCommitsOpts: {
+ // git-raw-commits options go here
+ },
+ parserOpts: {
+ // conventional-commits-parser options go here
+ },
+ writerOpts: {
+ // conventional-changelog-writer options go here
+ }
+ },
+ release: {
+ src: 'CHANGELOG.md'
}
}
});
@@ -116,9 +139,7 @@ module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-bower-task');
- grunt.renameTask("bower", "bowerInstall");
-
- grunt.loadNpmTasks('grunt-bower');
+ grunt.renameTask('bower', 'bowerInstall');
grunt.loadNpmTasks('grunt-karma');
@@ -126,16 +147,22 @@ module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-zip');
+ grunt.loadNpmTasks('grunt-coveralls');
+
// Default task.
grunt.registerTask('default', ['build']);
// Build task.
- grunt.registerTask('build', ['bowerInstall', 'bower', 'karma:build', 'karma:buildUnderscore', 'concat', 'uglify', 'zip']);
+ grunt.registerTask('build', ['bowerInstall', 'karma:build', 'karma:buildUnderscore', 'concat', 'uglify', 'zip']);
grunt.registerTask('test', ['karma:build', 'karma:buildUnderscore']);
-
- grunt.registerTask('travis', ['karma:travis', 'karma:travisUnderscore']);
+
+ grunt.registerTask('test-debug', ['karma:debug']);
+
+ grunt.registerTask('travis', ['karma:travis', 'karma:travisUnderscore', 'coveralls']);
+
+ grunt.registerTask('changelog', ['conventionalChangelog']);
// Provides the "bump" task.
grunt.registerTask('bump', 'Increment version number', function() {
@@ -155,7 +182,6 @@ module.exports = function(grunt) {
grunt.file.write(file, JSON.stringify(json, null, ' '));
}
updateFile('package.json');
- updateFile('bower.json');
grunt.log.ok('Version bumped to ' + version);
});
diff --git a/MAINTENANCE.md b/MAINTENANCE.md
new file mode 100644
index 00000000..6d219897
--- /dev/null
+++ b/MAINTENANCE.md
@@ -0,0 +1,45 @@
+# Restangular maintenance policy
+
+Restangular follows the [Semantic Versioning](http://semver.org/) for its releases:
+`(Major).(Minor).(Patch)`.
+
+- **Patch number**: When backwards compatible bug fixes are introduced that fix
+ incorrect behavior.
+- **Minor version**: When new, backwards compatible functionality is introduced
+ to the public API or a minor feature is introduced, or when a set of smaller
+ features is rolled out.
+- **Major version**: Whenever there is something significant or any backwards
+ incompatible changes are introduced to the public API.
+
+The current stable release will receive security patches and bug fixes
+(eg. `1.6.0` -> `1.6.1`). Feature releases will mark the next supported stable
+release where the minor version is increased numerically by increments of one
+(eg. `1.6.3 -> 1.7.0`).
+
+We encourage everyone to run the latest stable release.
+
+# Notes for maintainers
+
+Following are a set of guidelines and checklists for maintaining the
+[main repository](https://github.com/mgonto/restangular).
+
+## Keeping master usable
+
+In order for developers to use the bleeding edge master version in their projects,
+we'll need to keep the dist files up to date. After merging PRs that include mentionable
+changes, please update the dist files `grunt build` and the CHANGELOG `grunt changelog`.
+The CHANGELOG will have a section called `Unreleased` for changes not yet included in
+any release. This is the place for
+
+## Releasing
+
+Follow this checklist for publishing a new release.
+
+- [ ] Bump version `grunt bump --type=patch/minor/major`
+- [ ] Create changelog `grunt changelog` (open it in editor and make sure its sensible)
+- [ ] Make dist files `grunt build`
+- [ ] Commit changes `git add dist package.json CHANGELOG.md` and `git commit -m "chore(release): release 1.6.1"`
+- [ ] Tag release `git tag -a -m "Version 1.6.1" 1.6.1`
+- [ ] Push everything `git push` and `git push --tags`
+- [ ] Publish to NPM `npm publish`
+- [ ] Create a [new release](https://github.com/mgonto/restangular/releases) on GitHub, entering the version changelog as body
diff --git a/README.md b/README.md
index 1b9263b6..aea15823 100644
--- a/README.md
+++ b/README.md
@@ -1,109 +1,205 @@
-#Restangular
-
-[](https://travis-ci.org/mgonto/restangular)
-
+# Restangular
+
+[](https://travis-ci.org/mgonto/restangular)
+[](https://coveralls.io/github/mgonto/restangular?branch=master)
+[](https://david-dm.org/mgonto/restangular/?type=dev)
+[](https://snyk.io/test/github/mgonto/restangular)
+[](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=martin%40gon%2eto&lc=US&item_name=Martin%20Gontovnikas¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted "Donate once-off to this project using Paypal")
+[](https://www.gittip.com/mgonto/)
+
-Restangular is an AngularJS service that will help you get, delete and update Restfull Resources with very few lines in the Client side.
-This service is a perfect fit for any WebApp that uses Restfull Resources as the API for your application.
-
-**If you want to check a live example, [please click this link to plunkr](http://plnkr.co/edit/d6yDka?p=preview).** It's the same example as [Angular's Javascript Projects](http://angularjs.org/#wire-up-a-backend) but Restangularized.
+Restangular is an AngularJS service that simplifies common GET, POST, DELETE, and UPDATE requests with a minimum of client code. It's a perfect fit for any WebApp that consumes data from a RESTful API.
+
+**Note This version of Restangular [only supports Angular 1](#supported-angular-versions). For an Angular 2+ version of Restangular, check out [ngx-restangular](https://github.com/2muchcoffeecom/ngx-restangular).** It's a separate project with different maintainers, so issues regarding ngx-restangular should be reported [over there](https://github.com/2muchcoffeecom/ngx-restangular/issues) :wink:
+
+Learn Restangular! Try the [live demo on plunkr](http://plnkr.co/edit/8qrGeE?p=preview). It uses the same example as the official [Angular Javascript Project](http://angularjs.org/#wire-up-a-backend), but with Restangular! Or watch [a video introduction of a talk I gave at Devoxx France](http://www.parleys.com/play/535a189ee4b0c5ba17d43455/chapter1/about) about Restangular.
+
+
+# Table of contents
+
+- [Restangular](#restangular)
+- [Differences with $resource](#differences-with-resource)
+- [How do I add this to my project?](#how-do-i-add-this-to-my-project)
+- [Dependencies](#dependencies)
+- [Production apps using Restangular](#production-apps-using-restangular)
+- [Starter Guide](#starter-guide)
+ - [Quick configuration for Lazy Readers](#quick-configuration-for-lazy-readers)
+ - [Adding dependency to Restangular module in your app](#adding-dependency-to-restangular-module-in-your-app)
+ - [Using Restangular](#using-restangular)
+ - [Creating Main Restangular object](#creating-main-restangular-object)
+ - [Let's code!](#lets-code)
+ - [Configuring Restangular](#configuring-restangular)
+ - [Properties](#properties)
+ - [setBaseUrl](#setbaseurl)
+ - [setExtraFields](#setextrafields)
+ - [setParentless](#setparentless)
+ - [setDefaultHttpFields](#setdefaulthttpfields)
+ - [addElementTransformer](#addelementtransformer)
+ - [setOnElemRestangularized](#setonelemrestangularized)
+ - [setResponseInterceptor](#setresponseinterceptor)
+ - [setResponseExtractor (alias of setResponseInterceptor)](#setresponseinterceptor)
+ - [addResponseInterceptor](#addresponseinterceptor)
+ - [setRequestInterceptor](#setrequestinterceptor)
+ - [addRequestInterceptor](#addrequestinterceptor)
+ - [setFullRequestInterceptor](#setfullrequestinterceptor)
+ - [addFullRequestInterceptor](#addfullrequestinterceptor)
+ - [setErrorInterceptor](#seterrorinterceptor)
+ - [setRestangularFields](#setrestangularfields)
+ - [setMethodOverriders](#setmethodoverriders)
+ - [setDefaultRequestParams](#setdefaultrequestparams)
+ - [setFullResponse](#setfullresponse)
+ - [setDefaultHeaders](#setdefaultheaders)
+ - [setRequestSuffix](#setrequestsuffix)
+ - [setUseCannonicalId](#setusecannonicalid)
+ - [setPlainByDefault](#setplainbydefault)
+ - [How to configure them globally](#how-to-configure-them-globally)
+ - [Configuring in the config](#configuring-in-the-config)
+ - [Configuring in the run](#configuring-in-the-run)
+ - [How to create a Restangular service with a different configuration from the global one](#how-to-create-a-restangular-service-with-a-different-configuration-from-the-global-one)
+ - [Decoupled Restangular Service](#decoupled-restangular-service)
+ - [Methods description](#methods-description)
+ - [Restangular methods](#restangular-methods)
+ - [Element methods](#element-methods)
+ - [Collection methods](#collection-methods)
+ - [Custom methods](#custom-methods)
+ - [Copying elements](#copying-elements)
+ - [Enhanced promises](#enhanced-promises)
+ - [Using values directly in templates](#using-values-directly-in-templates)
+ - [Using Self reference resources](#using-self-reference-resources)
+ - [URL Building](#url-building)
+ - [Creating new Restangular Methods](#creating-new-restangular-methods)
+ - [Adding Custom Methods to Collections](#adding-custom-methods-to-collections)
+ - [Example:](#example)
+ - [Adding Custom Methods to Models](#adding-custom-methods-to-models)
+ - [Example:](#example-1)
+- [FAQ](#faq)
+ - [How can I handle errors?](#how-can-i-handle-errors)
+ - [I need to send one header in EVERY Restangular request, how do I do this?](#i-need-to-send-one-header-in-every-restangular-request-how-do-i-do-this)
+ - [Can I cache requests?](#can-i-cache-requests)
+ - [Can it be used in $routeProvider.resolve?](#can-it-be-used-in-routeproviderresolve)
+ - [My response is actually wrapped with some metadata. How do I get the data in that case?](#my-response-is-actually-wrapped-with-some-metadata-how-do-i-get-the-data-in-that-case)
+ - [I use Mongo and the ID of the elements is _id not id as the default. Therefore requests are sent to undefined routes](#i-use-mongo-and-the-id-of-the-elements-is-_id-not-id-as-the-default-therefore-requests-are-sent-to-undefined-routes)
+ - [What if each of my models has a different ID name like CustomerID for Customer](#what-if-each-of-my-models-has-a-different-id-name-like-customerid-for-customer)
+ - [How do I handle CRUD operations in a List returned by Restangular?](#how-do-i-handle-crud-operations-in-a-list-returned-by-restangular)
+ - [When I set baseUrl with a port, it's stripped out.](#when-i-set-baseurl-with-a-port-its-stripped-out)
+ - [How can I access the unrestangularized element as well as the restangularized one?](#how-can-i-access-the-unrestangularized-element-as-well-as-the-restangularized-one)
+ - [Restangular fails with status code 0](#restangular-fails-with-status-code-0)
+ - [Why does this depend on Lodash / Underscore?](#why-does-this-depend-on-lodash--underscore)
+ - [How do I cancel a request?](#how-do-i-cancel-a-request)
+- [Supported Angular versions](#supported-angular-versions)
+- [Server Frameworks](#server-frameworks)
+- [Releases Notes](#releases-notes)
+- [License](#license)
+
+**[Back to top](#table-of-contents)**
## Differences with $resource
Restangular has several features that distinguish it from $resource:
-* **It uses promises**. Instead of doing the "magic" filling of objects like $resource, it uses promises.
+* **It uses [promises](http://docs.angularjs.org/api/ng.$q)**. Instead of doing the "magic" filling of objects like $resource, it uses promises.
* **You can use this in $routeProvider.resolve**. As Restangular returns promises, you can return any of the methods in the `$routeProvider.resolve` and you'll get the real object injected into your controller if you want.
-* **It doesn't have all those `$resource` bugs**. Restangular doesn't have problem with trailling slashes, additional `:` in the URL, escapaing information, expecting only arrays for getting lists, etc.
+* **It doesn't have all those `$resource` bugs**. Restangular doesn't have problem with trailing slashes, additional `:` in the URL, escaping information, expecting only arrays for getting lists, etc.
* **It supports all HTTP methods**.
+* **It supports ETag out of the box**. You don't have to do anything. ETags and If-None-Match will be used in all of your requests
+* **It supports self linking elements**. If you receive from the server some item that has a link to itself, you can use that to query the server instead of writing the URL manually.
* **You don't have to create one $resource object per request**. Each time you want to do a request, you can just do it using the object that was returned by Restangular. You don't need to create a new object for this.
* **You don't have to write or remember ANY URL**. With $resource, you need to write the URL Template. In here, you don't write any urls. You just write the name of the resource you want to fetch and that's it.
-* **It supports nested RestFUL resources**. If you have Nested RestFUL resources, Restangular can handle them for you. You don't have to know the URL, the path, or anything to do all of the HTTP operations you want.
+* **It supports nested RESTful resources**. If you have Nested RESTful resources, Restangular can handle them for you. You don't have to know the URL, the path, or anything to do all of the HTTP operations you want.
* **Restangular lets you create your own methods**. You can create your own methods to run the operation that you want. The sky is the limit.
* **Support for wrapped responses**. If your response for a list of element actually returns an object with some property inside which has the list, it's very hard to use $resource. Restangular knows that and it makes it easy on you. Check out https://github.com/mgonto/restangular#my-response-is-actually-wrapped-with-some-metadata-how-do-i-get-the-data-in-that-case
* **You can build your own URLs with Restangular objects easily**. Restangular lets you create a Restangular object for any url you want with a really nice builder.
-Let's see a quick and short example of this features
+Let's see a quick and short example of these features
````javascript
-// It uses promises.
-Restangular.one('users').getList().then(function(users) {
- $scope.user = users[0];
+// Restangular returns promises
+Restangular.all('users').getList() // GET: /users
+.then(function(users) {
+ // returns a list of users
+ $scope.user = users[0]; // first Restangular obj in list: { id: 123 }
})
-// Later in the code.
+// Later in the code...
-// Requests /users/123/cars You don't have to know the URL. Just the name of the resource
-// This is a promise
-$scope.cars = $scope.user.getList('cars');
+// Restangular objects are self-aware and know how to make their own RESTful requests
+$scope.user.getList('cars'); // GET: /users/123/cars
-// POST /users/123/sendMessage You've created your own method with the path & operation that you wanted
-$scope.user.sendMessage();
+// You can also use your own custom methods on Restangular objects
+$scope.user.sendMessage(); // POST: /users/123/sendMessage
-// URL Building
-// GET to /user/123/messages/123/from/123/unread
-$scope.user.one('messages', 123).one('from', 123).getList('unread')
+// Chain methods together to easily build complex requests
+$scope.user.one('messages', 123).one('from', 123).getList('unread');
+// GET: /users/123/messages/123/from/123/unread
````
-#How do I add this to my project?
+**[Back to top](#table-of-contents)**
+
+## How do I add this to my project?
You can download this by:
* Using bower and running `bower install restangular`
* Using npm and running `npm install restangular`
* Downloading it manually by clicking [here to download development unminified version](https://raw.github.com/mgonto/restangular/master/dist/restangular.js) or [here to download minified production version](https://raw.github.com/mgonto/restangular/master/dist/restangular.min.js)
-* Using [JsDelivr CDN files](https://github.com/jimaek/jsdelivr/tree/master/files/restangular):
+* Using [CdnJS CDN files](http://cdnjs.com/libraries/restangular/):
````html
-
-
-
-
-
-
-
+
+
+
````
+**[Back to top](#table-of-contents)**
-#Dependencies
+## Dependencies
-Restangular depends on Angular and (Underscore or Lodash). **angular-resource is no longer needed since version 1.0.6, now this uses `$http` instead of `$resource`**
+Restangular depends on Angular and Lodash (or Underscore).
-#Starter Guide
+**[Back to top](#table-of-contents)**
-## Quick configuration for Lazy Readers
-This is the quick configuration to bootstrap all. Read the rest of the documentation for further configuration and understanding
+# Production apps using Restangular
-````javascript
-angular.module('sample-app', ['restangular'])
- .config(function(RestangularProvider) {
- RestangularProvider.setBaseUrl("/api/v1");
- });
-
-angular.module('sample-app').controller('MainCtrl', function($scope, Restangular) {
- $scope.projects = Restangular.all('projects').getList();
-});
-````
+Each time, there're more Production WebApps using `Restangular`. If your webapp uses it and it's not in the list, please create an issue or submit a PR:
-## Adding dependency to Restangular module in your app
+* **Life360** is using Restangular to build the WebApp version of their platform
+* **Thomson Reuters** is using Restangular for the new Webapp they've built
+* **Quran.com** is using Restangular for their alpha/beta app and soon to be main site
+* **[Worldcampus.co](http://www.worldcampus.co)** is using Restangular for their beta international students social network.
+* **[ENTSO-E Transparency Platform](https://transparency.entsoe.eu)**
-The first thing you need to do after adding link to script file, is mentioning in your app that you'll use Restangular.
+**[Back to top](#table-of-contents)**
+
+# Starter Guide
+
+## Quick Configuration (For Lazy Readers)
+This is all you need to start using all the basic Restangular features.
````javascript
-var app = angular.module('angularjs-starter', ['restangular']);
+// Add Restangular as a dependency to your app
+angular.module('your-app', ['restangular']);
+
+// Inject Restangular into your controller
+angular.module('your-app').controller('MainCtrl', function($scope, Restangular) {
+ // ...
+});
````
-## Using Restangular
+The Restangular service may be injected into any Controller or Directive :)
+Note: When adding Restangular as a dependency it is not capitalized 'restangular'
+ But when injected into your controller it is 'Restangular'
+
+**[Back to top](#table-of-contents)**
-Now that you have everything configured, you can just inject this Service to any Controller or Directive like any other :)
+## Using Restangular
### Creating Main Restangular object
-There're 2 ways of creating a main Restangular object.
-The first one and most common one is by stating the main route of all requests.
+There are 3 ways of creating a main Restangular object.
+The first one and most common one is by stating the main route of all requests.
The second one is by stating the main route and object of all requests.
````javascript
@@ -112,26 +208,43 @@ Restangular.all('accounts')
// Stating main object
Restangular.one('accounts', 1234)
+
+// Gets a list of all of those accounts
+Restangular.several('accounts', 1234, 123, 12345);
````
+**[Back to top](#table-of-contents)**
+
### Let's code!
-Now that we have our main Object lets's start playing with it.
+Now that we have our main Object let's start playing with it.
````javascript
// First way of creating a Restangular object. Just saying the base URL
var baseAccounts = Restangular.all('accounts');
-// This will query /accounts and return a promise. As Angular supports setting promises to scope variables
-// as soon as we get the information from the server, it will be shown in our template :)
-$scope.allAccounts = baseAccounts.getList();
+// This will query /accounts and return a promise.
+baseAccounts.getList().then(function(accounts) {
+ $scope.allAccounts = accounts;
+});
+
+// Does a GET to /accounts
+// Returns an empty array by default. Once a value is returned from the server
+// that array is filled with those values. So you can use this in your template
+$scope.accounts = Restangular.all('accounts').getList().$object;
var newAccount = {name: "Gonto's account"};
// POST /accounts
baseAccounts.post(newAccount);
-//You can do RequestLess "connections" if you need as well
+// GET to http://www.google.com/ You set the URL in this case
+Restangular.allUrl('googlers', 'http://www.google.com/').getList();
+
+// GET to http://www.google.com/1 You set the URL in this case
+Restangular.oneUrl('googlers', 'http://www.google.com/1').get();
+
+// You can do RequestLess "connections" if you need as well
// Just ONE GET to /accounts/123/buildings/456
Restangular.one('accounts', 123).one('buildings', 456).get()
@@ -139,7 +252,7 @@ Restangular.one('accounts', 123).one('buildings', 456).get()
// Just ONE GET to /accounts/123/buildings
Restangular.one('accounts', 123).getList('buildings')
-//Here we use Promises then
+// Here we use Promises then
// GET /accounts
baseAccounts.getList().then(function (accounts) {
// Here we can continue fetching the tree :).
@@ -147,30 +260,33 @@ baseAccounts.getList().then(function (accounts) {
var firstAccount = accounts[0];
// This will query /accounts/123/buildings considering 123 is the id of the firstAccount
$scope.buildings = firstAccount.getList("buildings");
-
+
// GET /accounts/123/places?query=param with request header: x-user:mgonto
- $scope.loggedInPlaces = firstAccount.getList("places", {query: param}, {'x-user': 'mgonto'})
+ $scope.loggedInPlaces = firstAccount.getList("places", {query: 'param'}, {x-user: 'mgonto'})
- // This is a regular JS object, we can change anything we want :)
+ // This is a regular JS object, we can change anything we want :)
firstAccount.name = "Gonto"
-
- //If we wanted to keep the original as it is, we can copy it to a new element
+
+ // If we wanted to keep the original as it is, we can copy it to a new element
var editFirstAccount = Restangular.copy(firstAccount);
editFirstAccount.name = "New Name";
-
+
// PUT /accounts/123. The name of this account will be changed from now on
firstAccount.put();
editFirstAccount.put();
+ // PUT /accounts/123. Save will do POST or PUT accordingly
+ firstAccount.save();
+
// DELETE /accounts/123 We don't have first account anymore :(
firstAccount.remove();
-
+
var myBuilding = {
name: "Gonto's Building",
place: "Argentina"
};
-
+
// POST /accounts/123/buildings with MyBuilding information
firstAccount.post("Buildings", myBuilding).then(function() {
console.log("Object saved OK");
@@ -183,16 +299,16 @@ baseAccounts.getList().then(function (accounts) {
// Instead of posting nested element, a collection can post to itself
// POST /accounts/123/users
users.post({userName: 'unknown'});
-
+
// Custom methods are available now :).
// GET /accounts/123/users/messages?param=myParam
users.customGET("messages", {param: "myParam"})
-
+
var firstUser = users[0];
// GET /accounts/123/users/456. Just in case we want to update one user :)
$scope.userFromServer = firstUser.get();
-
+
// ALL http methods are available :)
// HEAD /accounts/123/users/456
firstUser.head()
@@ -210,39 +326,38 @@ var account = Restangular.one("accounts", 123);
$scope.account = account.get({single: true});
// POST /accounts/123/messages?param=myParam with the body of name: "My Message"
-account.customPOST("messages", {param: "myParam"}, {}, {name: "My Message"})
+account.customPOST({name: "My Message"}, "messages", {param: "myParam"}, {})
````
+**[Back to top](#table-of-contents)**
+
## Configuring Restangular
### Properties
-Restangular comes with defaults for all of it's properties but you can configure them. **So, if you don't need to configure something, there's no need to add the configuration.**
-You can set all this configurations in **`RestangularProvider` or `Restangular` service to change the global configuration** or you can **use the withConfig method in Restangular service to create a new Restangular service with some scoped configuration**. Check the section on this later.
+Restangular comes with defaults for all of its properties but you can configure them. **So, if you don't need to configure something, there's no need to add the configuration.**
+You can set all these configurations in **`RestangularProvider` or `Restangular` service to change the global configuration** or you can **use the withConfig method in Restangular service to create a new Restangular service with some scoped configuration**. Check the section on this later.
-#### baseUrl
-The base URL for all calls to your API. For example if your URL for fetching accounts is http://example.com/api/v1/accounts, then your baseUrl is `/api/v1`. The default baseUrl is an empty string which resolves to the same url that AngularJS is running, so you can also set an absolute url like `http://api.example.com/api/v1` if you need do set another domain.
+#### setBaseUrl
+The base URL for all calls to your API. For example if your URL for fetching accounts is http://example.com/api/v1/accounts, then your baseUrl is `/api/v1`. The default baseUrl is an empty string which resolves to the same url that AngularJS is running, but you can also set an absolute url like `http://api.example.com/api/v1` if you need to set another domain.
-#### extraFields
-This are the fields that you want to save from your parent resources if you need to display them. By default this is an Empty Array which will suit most cases
+#### setExtraFields
+These are the fields that you want to save from your parent resources if you need to display them. By default this is an Empty Array which will suit most cases
-#### parentless
-With this property, you can set if you want Restangularized elements to have a parent or not. So, for example if you get an account and then get a nested list of buildings, you may want the buildings URL to be simple `/buildings/123` instead of `/accounts/123/buildings/123`. This configuration lets you do that.
+#### setParentless
+Use this property to control whether Restangularized elements to have a parent or not. So, for example if you get an account and then get a nested list of buildings, you may want the buildings URL to be simple `/buildings/123` instead of `/accounts/123/buildings/123`. This property lets you do that.
-This method accepts 2 parameters:
+This method accepts 1 parameter, it could be:
* Boolean: Specifies if all elements should be parentless or not
-* Array: Specified the routes (types) of all elements that should be parentless. For example `['buildings']`
+* Array: Specifies the routes (types) of all elements that should be parentless. For example `['buildings']`
-#### defaultHttpFields
-`$http` from AngularJS can receive a bunch of parameters like `cache`, `transformRequest` and so on. You can set all of those properties in the object sent on this setter so that they will be used in EVERY API call made by Restangular. This is very useful for caching for example. All properties that can be set can be checked here: http://docs.angularjs.org/api/ng.$http#Parameters
-
-#### urlCreator
-This is the factory that will create URLs based on the resources. For the time being, only Path UrlCreator is implemented. This means that if you have a resource names Building which is a child of Account, the URL to fetch this will be `/accounts/123/buildings`. In the future, I'll implement more UrlCreator like QueryParams UrlCreator.
+#### setDefaultHttpFields
+`$http` from AngularJS can receive a bunch of parameters like `cache`, `transformRequest` and so on. You can set all of those properties in the object sent on this setter so that they will be used in EVERY API call made by Restangular. This is very useful for caching for example. All properties that can be set can be checked here: http://docs.angularjs.org/api/ng.$http#parameters
#### addElementTransformer
-This is a hook. After each element has been "restangularized" (Added the new methods from Restangular), the corresponding transformer will be called if it fits.
+This is a hook. After each element has been "restangularized" (Added the new methods from Restangular), the corresponding transformer will be called if it fits.
This should be used to add your own methods / functions to entities of certain types.
@@ -252,34 +367,47 @@ You can add as many element transformers as you want. The signature of this meth
* **addElementTransformer(route, isCollection, transformer)**: Transformer is called with all elements that have been restangularized and match the specification regarding if it's a collection or not (true | false)
+#### setTransformOnlyServerElements
+This sets whether transformers will be run for local objects and not by objects returned by the server. This is by default true but can be changed to false if needed (Most people won't need this).
+
-#### onElemRestangularized
+#### setOnElemRestangularized
This is a hook. After each element has been "restangularized" (Added the new methods from Restangular), this will be called. It means that if you receive a list of objects in one call, this method will be called first for the collection and then for each element of the collection.
**I favor the usage of `addElementTransformer` instead of `onElemRestangularized` whenever possible as the implementation is much cleaner.**
-This callback is a function that has 3 parameters:
+This callback is a function that has 4 parameters:
* **elem**: The element that has just been restangularized. Can be a collection or a single element.
* **isCollection**: Boolean indicating if this is a collection or a single element.
* **what**: The model that is being modified. This is the "path" of this resource. For example `buildings`
* **Restangular**: The instanced service to use any of its methods
-
+
This can be used together with `addRestangularMethod` (Explained later) to add custom methods to an element
-#### responseInterceptor (or responseExtractor. It's an Alias)
-The responseInterceptor is called after we get each response from the server. It's a function that receives 4 arguments:
+#### setResponseInterceptor
+**This is deprecated. Use addResponseInterceptor since you can add more than one**.
+
+#### addResponseInterceptor
+The responseInterceptor is called after we get each response from the server. It's a function that receives this arguments:
-* **response**: The response got from the server
+* **data**: The data received got from the server
* **operation**: The operation made. It'll be the HTTP method used except for a `GET` which returns a list of element which will return `getList` so that you can distinguish them.
* **what**: The model that's being requested. It can be for example: `accounts`, `buildings`, etc.
* **url**: The relative URL being requested. For example: `/api/v1/accounts/123`
+* **response**: Full server response including headers
+* **deferred**: The deferred promise for the request.
Some of the use cases of the responseInterceptor are handling wrapped responses and enhancing response elements with more methods among others.
-#### requestInterceptor
+The responseInterceptor must return the restangularized data element.
+
+#### setRequestInterceptor
+**This is deprecated. Use addRequestInterceptor since you can add more than one**.
+
+#### addRequestInterceptor
The requestInterceptor is called before sending any data to the server. It's a function that must return the element to be requested. This function receives the following arguments:
* **element**: The element to send to the server.
@@ -287,46 +415,87 @@ The requestInterceptor is called before sending any data to the server. It's a f
* **what**: The model that's being requested. It can be for example: `accounts`, `buildings`, etc.
* **url**: The relative URL being requested. For example: `/api/v1/accounts/123`
-#### fullRequestInterceptor
-The fullRequestInterceptor is similar to the `requestInterceptor` but more powerful. It lets you change the element, the request parameters and the headers as well.
+#### setFullRequestInterceptor
+**This is deprecated. Use addFullRequestInterceptor since you can add more than one**.
+
+#### addFullRequestInterceptor
+This adds a new fullRequestInterceptor. The fullRequestInterceptor is similar to the `requestInterceptor` but more powerful. It lets you change the element, the request parameters and the headers as well.
It's a function that receives the same as the `requestInterceptor` plus the headers and the query parameters (in that order).
-It must return an object with the following properties:
+It can return an object with any (or all) of following properties:
* **headers**: The headers to send
* **params**: The request parameters to send
* **element**: The element to send
+* **httpConfig**: The httpConfig to call with
+
+If a property isn't returned, the one sent is used.
-#### errorInterceptor
-The errorInterceptor is called whenever there's an error. It's a function that receives the response as a parameter.
+#### setErrorInterceptor
+The errorInterceptor is called whenever there's an error. It's a function that receives the response, the deferred (for the promise) and the Restangular-response handler as parameters.
-The errorInterceptor function, whenever it returns `false`, prevents the promise linked to a Restangular request to be executed.
-All other return values (besides `false`) are ignored and the promise follows the usual path, eventually reaching the success or error hooks.
+The errorInterceptor function, whenever it returns `false`, prevents the promise linked to a Restangular request to be executed. All other return values (besides `false`) are ignored and the promise follows the usual path, eventually reaching the success or error hooks.
-The feature to prevent the promise to complete is usefull whenever you need to intercept each Restangular error response for every request in your AngularJS application in a single place, increasing debugging capabilities and hooking security features in a single place.
+The feature to prevent the promise to complete is useful whenever you need to intercept each Restangular error response for every request in your AngularJS application in a single place, increasing debugging capabilities and hooking security features in a single place.
-#### listTypeIsArray
+````javascript
+
+var refreshAccesstoken = function() {
+ var deferred = $q.defer();
+
+ // Refresh access-token logic
+
+ return deferred.promise;
+};
+
+Restangular.setErrorInterceptor(function(response, deferred, responseHandler) {
+ if(response.status === 403) {
+ refreshAccesstoken().then(function() {
+ // Repeat the request and then call the handlers the usual way.
+ $http(response.config).then(responseHandler, deferred.reject);
+ // Be aware that no request interceptors are called this way.
+ });
+
+ return false; // error handled
+ }
-We don't use `$resource` anymore so this property is depracated. I've left it with an empty setter per now to avoid errors, but it'll be removed in the future.
+ return true; // error not handled
+});
-~~You can set in this property wether the `getList` method will return an Array or not. Most of the times, it will return an array, as it returns a collection of values. However, sometimes this method returns first some metadata and inside it has the array. So this can be used together with `responseExtractor` to get the real array. The default value is true.~~
+````
-#### restangularFields
+#### setRestangularFields
-Restangular required 3 fields for every "Restangularized" element. This are:
+Restangular requires 7 fields for every "Restangularized" element. These are:
* id: Id of the element. Default: id
* route: Name of the route of this element. Default: route
* parentResource: The reference to the parent resource. Default: parentResource
* restangularCollection: A boolean indicating if this is a collection or an element. Default: restangularCollection
+* cannonicalId: If available, the path to the cannonical ID to use. Useful for PK changes
+* etag: Where to save the ETag received from the server. Defaults to `restangularEtag`
+* selfLink: The path to the property that has the URL to this item. If your REST API doesn't return a URL to an item, you can just leave it blank. Defaults to `href`
-All of this fields except for `id` are handled by Restangular, so most of the time you won't change them. You can configure the name of the property that will be binded to all of this fields by setting restangularFields property.
+Also all of Restangular methods and functions are configurable through restangularFields property.
+All of these fields except for `id` and `selfLink` are handled by Restangular, so most of the time you won't change them. You can configure the name of the property that will be binded to all of this fields by setting restangularFields property.
-#### methodOverriders
+#### setMethodOverriders
You can now Override HTTP Methods. You can set here the array of methods to override. All those methods will be sent as POST and Restangular will add an X-HTTP-Method-Override header with the real HTTP method we wanted to do.
-#### defaultRequestParams
+#### setJsonp
+Typical web browsers prohibit requesting data from a server in a different domain (same-origin policy). JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to get around this.
+
+For JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted results. The JSONP parameters passed as arguments to a script are defined by the server.
+
+By setting the value of setJsonp to true, both `get` and `getList` will be performed using JSonp instead of the regular GET.
+
+You will need to add the 'JSON_CALLBACK' string to your URLs (see [$http.jsonp](http://docs.angularjs.org/api/ng.$http#methods_jsonp)). You can use `setDefaultRequestParams` to accomplish this:
+```javascript
+RestangularProvider.setDefaultRequestParams('jsonp', {callback: 'JSON_CALLBACK'});
+```
+
+#### setDefaultRequestParams
You can set default Query parameters to be sent with every request and every method.
@@ -334,25 +503,86 @@ Additionally, if you want to configure request params per method, you can use `r
Supported method to configure are: remove, get, post, put, common (all)
-#### fullResponse
+````javascript
+// set params for multiple methods at once
+Restangular.setDefaultRequestParams(['remove', 'post'], {confirm: true});
-You can set fullResponse to true to get the whole response every time you do any request. The full response has the restangularized data in the `data` field, and also has the headers and config sent. By default, it's set to false.
+// set only for get method
+Restangular.setDefaultRequestParams('get', {limit: 10});
-#### defaultHeaders
+// or for all supported request methods
+Restangular.setDefaultRequestParams({apikey: "secret key"});
+````
-You can set default Headers to be sent with every request.
+#### setFullResponse
-#### requestSuffix
+You can set fullResponse to true to get the whole response every time you do any request. The full response has the restangularized data in the `data` field, and also has the headers and config sent. By default, it's set to false. Please note that in order for Restangular to access custom HTTP headers, your server must respond having the `Access-Control-Expose-Headers:` set.
-If all of your requests require to send some suffix to work, you can set it here. For example, if you need to send the format like `/users/123.json`you can add that `.json` to the suffix using the `setRequestSuffix`method
+````javascript
+// set params for multiple methods at once
+Restangular.setFullResponse(true);
+````
-#### useCannonicalId
+Or set it per service
+````javascript
+// Restangular service that uses setFullResponse
+app.factory('RestFulResponse', function(Restangular) {
+ return Restangular.withConfig(function(RestangularConfigurer) {
+ RestangularConfigurer.setFullResponse(true);
+ });
+});
+
+// Let's use it in the controller
+app.controller('MainCtrl', function(Restangular, RestFulResponse) {
+
+ // Uses full response configuration
+ RestFulResponse.all('users').getList().then(function(response) {
+ $scope.users = response.data;
+ console.log(response.headers);
+ });
+});
+````
+
+#### setDefaultHeaders
+
+You can set default Headers to be sent with every request. Send format: {header_name: header_value}
+
+````javascript
+// set default header "token"
+RestangularProvider.setDefaultHeaders({token: "x-restangular"});
+````
+
+#### setRequestSuffix
+
+If all of your requests require to send some suffix to work, you can set it here. For example, if you need to send the format like `/users/123.json` you can add that `.json` to the suffix using the `setRequestSuffix` method
+
+#### setUseCannonicalId
You can set this to either `true` or `false`. By default it's false. If set to true, then the cannonical ID from the element will be used for URL creation (in DELETE, PUT, POST, etc.). What this means is that if you change the ID of the element and then you do a put, if you set this to true, it'll use the "old" ID which was received from the server. If set to false, it'll use the new ID assigned to the element.
+#### setPlainByDefault
+
+You can set this to `true` or `false`. By default it's false. If set to true, data retrieved will be returned with no embed methods from restangular.
+
+#### setEncodeIds
+
+You can set here if you want to URL Encode IDs or not. By default, it's true.
+
+**[Back to top](#table-of-contents)**
+
+### Accessing configuration
+
+You can also access the configuration via `RestangularProvider` and `Restangular` via the `configuration` property if you don't want to use the setters. Check it out:
+
+````js
+Restangular.configuration.requestSuffix = '/';
+````
+
+**[Back to top](#table-of-contents)**
+
### How to configure them globally
-You can do this configurations in either the `config` or the `run` method. If your configurations don't need any other services, then I'd recommend you do them in the `config`. If your configurations depend on other services, you can configure them in the `run` using `Restangular` instead of `RestangularProvider`
+You can configure this in either the `config` or the `run` method. If your configurations don't need any other services, then I'd recommend you do them in the `config`. If your configurations depend on other services, you can configure them in the `run` using `Restangular` instead of `RestangularProvider`
#### Configuring in the `config`
````javascript
@@ -362,41 +592,43 @@ app.config(function(RestangularProvider) {
RestangularProvider.setResponseExtractor(function(response, operation) {
return response.data;
});
-
+
RestangularProvider.addElementTransformer('accounts', false, function(element) {
element.accountName = 'Changed';
return element;
});
-
+
RestangularProvider.setDefaultHttpFields({cache: true});
RestangularProvider.setMethodOverriders(["put", "patch"]);
-
- // In this case we are maping the id of each element to the _id field.
- // We also change the Restangular route.
+
+ // In this case we are mapping the id of each element to the _id field.
+ // We also change the Restangular route.
// The default value for parentResource remains the same.
RestangularProvider.setRestangularFields({
id: "_id",
- route: "restangularRoute"
+ route: "restangularRoute",
+ selfLink: "self.href"
});
-
+
RestangularProvider.setRequestSuffix('.json');
-
+
// Use Request interceptor
RestangularProvider.setRequestInterceptor(function(element, operation, route, url) {
delete element.name;
return element;
});
-
+
// ..or use the full request interceptor, setRequestInterceptor's more powerful brother!
- RestangularProvider.setFullRequestInterceptor(function(element, operation, route, url, headers, params) {
- delete element.name;
+ RestangularProvider.setFullRequestInterceptor(function(element, operation, route, url, headers, params, httpConfig) {
+ delete element.name;
return {
element: element,
params: _.extend(params, {single: true}),
- headers: headers
+ headers: headers,
+ httpConfig: httpConfig
};
});
-
+
});
````
@@ -410,6 +642,8 @@ app.run(function(Restangular, BaseUrlCalculator) {
});
````
+**[Back to top](#table-of-contents)**
+
### How to create a Restangular service with a different configuration from the global one
Let's assume that for most requests you need some configuration (The global one), and for just a bunch of methods you need another configuration. In that case, you'll need to create another Restangular service with this particular configuration. This scoped configuration will inherit all defaults from the global one. Let's see how.
@@ -420,7 +654,7 @@ app.config(function(RestangularProvider) {
RestangularProvider.setRequestSuffix('.json');
});
-//Restangular service that uses Bing
+// Restangular service that uses Bing
app.factory('BingRestangular', function(Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl('http://www.bing.com');
@@ -429,92 +663,179 @@ app.factory('BingRestangular', function(Restangular) {
// Let's use them from a controller
app.controller('MainCtrl', function(Restangular, BingRestangular) {
-
+
// GET to http://www.google.com/users.json
// Uses global configuration
Restangular.all('users').getList()
-
+
// GET to http://www.bing.com/users.json
// Uses Bing configuration which is based on Global one, therefore .json is added.
BingRestangular.all('users').getList()
});
````
+**[Back to top](#table-of-contents)**
+
+### Decoupled Restangular Service
+
+There're some times where you want to use Restangular but you don't want to expose Restangular object anywhere.
+For those cases, you can actually use the `service` feature of Restangular.
+
+Let's see how it works:
+
+````js
+// Declare factory
+module.factory('Users', function(Restangular) {
+ return Restangular.service('users');
+});
+
+// In your controller you inject Users
+Users.get(2) // GET to /users/2
+Users.one(2).get() // GET to /users/2
+Users.post({data}) // POST to /users
+
+// GET to /users
+Users.getList().then(function(users) {
+ var user = users[0]; // user === {id: 1, name: "Tonto"}
+ user.name = "Gonto";
+ // PUT to /users/1
+ user.put();
+})
+````
+
+You can also use ```withHttpConfig``` on objects created by ```Restangular.service```.
+
+```js
+var personService = Restangular.service('person');
+var entity = personService.withHttpConfig({transformRequest: function(data) {
+ data.fullname = data.firstname + ' ' + data.lastname;
+ return JSON.stringify(data);
+}}).post({
+ "lastname": "Mueller",
+ "firstname": "Gerd"
+}).then(function(resp) {
+ console.log(resp);
+});
+```
+
+We can also use Nested RESTful resources with this:
+
+````js
+var Cars = Restangular.service('cars', Restangular.one('users', 1));
+
+Cars.getList() // GET to /users/1/cars
+````
+
+**[Back to top](#table-of-contents)**
+
## Methods description
-There're 3 sets of methods. Collections have some methods and elements have others. There're are also some common methods for all of them
+There are 3 sets of methods. Collections have some methods and elements have others. There are are also some common methods for all of them
### Restangular methods
-This are the methods that can be called in the Restangular object.
+These are the methods that can be called on the Restangular object.
* **one(route, id)**: This will create a new Restangular object that is just a pointer to one element with the route `route` and the specified id.
* **all(route)**: This will create a new Restangular object that is just a pointer to a list of elements for the specified path.
-* **copy(fromElement)**: This will create a copy of the from element so that we can modified the copied one.
-* **restangularizeElement(parent, element, route)**: Restangularizes a new element
-* **restangularizeCollection(parent, element, route)**: Restangularizes a new collection
+* **oneUrl(route, url)**: This will create a new Restangular object that is just a pointer to one element with the specified URL.
+* **allUrl(route, url)**: This creates a Restangular object that is just a pointer to a list at the specified URL.
+* **copy(fromElement)**: This will create a copy of the from element so that we can modify the copied one.
+* **restangularizeElement(parent, element, route, fromServer, collection, reqParams)**: Restangularizes a new element
+* **restangularizeCollection(parent, element, route, fromServer, reqParams)**: Restangularizes a new collection
+
+**[Back to top](#table-of-contents)**
### Element methods
* **get([queryParams, headers])**: Gets the element. Query params and headers are optionals
* **getList(subElement, [queryParams, headers])**: Gets a nested resource. subElement is mandatory. **It's a string with the name of the nested resource (and URL)**. For example `buildings`
* **put([queryParams, headers])**: Does a put to the current element
* **post(subElement, elementToPost, [queryParams, headers])**: Does a POST and creates a subElement. Subelement is mandatory and is the nested resource. Element to post is the object to post to the server
-* **remove([queryParams, headers])**: Does a DELETE
+* **remove([queryParams, headers])**: Does a DELETE. By default, `remove` sends a request with an empty object, which may cause problems with some servers or browsers. [This](https://github.com/mgonto/restangular/issues/193) shows how to configure RESTangular to have no payload.
* **head([queryParams, headers])**: Does a HEAD
* **trace([queryParams, headers])**: Does a TRACE
* **options([queryParams, headers])**: Does a OPTIONS
-* **patch([queryParams, headers])**: Does a PATCH
+* **patch(object, [queryParams, headers])**: Does a PATCH
* **one(route, id)**: Used for RequestLess connections and URL Building. See section below.
* **all(route)**: Used for RequestLess connections and URL Building. See section below.
+* **several(route, ids*)**: Used for RequestLess connections and URL Building. See section below.
+* **oneUrl(route, url)**: This will create a new Restangular object that is just a pointer to one element with the specified URL.
+* **allUrl(route, url)**: This creates a Restangular object that is just a pointer to a list at the specified URL.
* **getRestangularUrl()**: Gets the URL of the current object.
+* **getRequestedUrl()**: Gets the real URL the current object was requested with (incl. GET parameters). Will equal getRestangularUrl() when no parameters were used, before calling `get()`, or when using on a nested child.
+* **getParentList()**: Gets the parent list to which it belongs (if any)
+* **clone()**: Copies the element. It's an alias to calling `Restangular.copy(elem)`.
+* **plain()**: Returns the plain element received from the server without any of the enhanced methods from Restangular. It's an alias to calling `Restangular.stripRestangular(elem)`
+* **withHttpConfig(httpConfig)**: It lets you set a configuration for $http only for the next call. Check the Local Config HTTP section for an example.
+* **save**: Calling save will determine whether to do PUT or POST accordingly
+
+**[Back to top](#table-of-contents)**
### Collection methods
* **getList([queryParams, headers]): Gets itself again (Remember this is a collection)**.
+* **get(id): Gets one item from the collection by id**.
* **post(elementToPost, [queryParams, headers])**: Creates a new element of this collection.
* **head([queryParams, headers])**: Does a HEAD
* **trace: ([queryParams, headers])**: Does a TRACE
* **options: ([queryParams, headers])**: Does a OPTIONS
-* **patch([queryParams, headers])**: Does a PATCH
+* **patch(object, [queryParams, headers])**: Does a PATCH
+* **remove([queryParams, headers])**: Does a DELETE. By default, `remove` sends a request with an empty object, which may cause problems with some servers or browsers. [This](https://github.com/mgonto/restangular/issues/193) shows how to configure RESTangular to have no payload.
* **putElement(idx, params, headers)**: Puts the element on the required index and returns a promise of the updated new array
* **getRestangularUrl()**: Gets the URL of the current object.
+* **getRequestedUrl()**: Gets the real URL the current object was requested with (incl. GET parameters). Will equal getRestangularUrl() when no parameters were used, before calling `getList()`, or when using on a nested child.
* **one(route, id)**: Used for RequestLess connections and URL Building. See section below.
* **all(route)**: Used for RequestLess connections and URL Building. See section below.
+* **several(route, ids*)**: Used for RequestLess connections and URL Building. See section below.
+* **oneUrl(route, url)**: This will create a new Restangular object that is just a pointer to one element with the specified URL.
+* **allUrl(route, url)**: This creates a Restangular object that is just a pointer to a list at the specified URL.
+* **clone()**: Copies the collection. It's an alias to calling `Restangular.copy(collection)`.
+* **withHttpConfig(httpConfig)**: It lets you set a configuration for $http only for the next call. Check the Local Config HTTP section for an example.
+
+**[Back to top](#table-of-contents)**
### Custom methods
* **customGET(path, [params, headers])**: Does a GET to the specific path. Optionally you can set params and headers.
* **customGETLIST(path, [params, headers])**: Does a GET to the specific path. **In this case, you expect to get an array, not a single element**. Optionally you can set params and headers.
* **customDELETE(path, [params, headers])**: Does a DELETE to the specific path. Optionally you can set params and headers.
-* **customPOST(path, [params, headers, elem])**: Does a POST to the specific path. Optionally you can set params and headers and elem. Elem is the element to post. If it's not set, it's assumed that it's the element itself from which you're calling this function.
-* **customPUT(path, [params, headers, elem])**: Does a PUT to the specific path. Optionally you can set params and headers and elem. Elem is the element to post. If it's not set, it's assumed that it's the element itself from which you're calling this function.
-* **customOperation(operation, path, [params, headers, elem])**: This does a custom operation to the path that we specify. This method is actually used from all the others in this subsection. Operation can be one of: get, post, put, delete, head, options, patch, trace
-* **addRestangularMethod(name, operation, [path, params, headers, elem])**: This will add a new restangular method to this object with the name `name` to the operation and path specified (or current path otherwise). There's a section on how to do this later.
+* **customPOST([elem, path, params, headers])**: Does a POST to the specific path. Optionally you can set params and headers and elem. Elem is the element to post. If it's not set, it's assumed that it's the element itself from which you're calling this function.
+* **customPUT([elem, path, params, headers])**: Does a PUT to the specific path. Optionally you can set params and headers and elem. Elem is the element to post. If it's not set, it's assumed that it's the element itself from which you're calling this function.
+* **customPATCH([elem, path, params, headers])**: Does a PATCH to the specific path. Accepts the same arguments as customPUT.
+* **customOperation(operation, path, [params, headers, elem])**: This does a custom operation to the path that we specify. This method is actually used from all the others in this subsection. Operation can be one of: get, post, put, remove, head, options, patch, trace
+* **addRestangularMethod(name, operation, [path, params, headers, elem])**: This will add a new restangular method to this object with the name `name` to the operation and path specified (or current path otherwise). There's a section on how to do this later.
-
Let's see an example of this:
````javascript
-//GET /accounts/123/messages
+// GET /accounts/123/messages
Restangular.one("accounts", 123).customGET("messages")
-//GET /accounts/messages?param=param2
+// GET /accounts/messages?param=param2
Restangular.all("accounts").customGET("messages", {param: "param2"})
````
+
+All custom methods have an alias where you replace `custom` by `do`. For example, `customGET` is equal to `doGET`. Just pick whatever syntax you prefer.
+
+**[Back to top](#table-of-contents)**
+
## Copying elements
-Before modifying an object, we sometimes want to copy it and then modify the copied object. We can't use `angular.copy` for this because it'll not change the `this` binded in the functions we add to the object. In this cases, you must use `Restangular.copy(fromElement)`.
+Before modifying an object, we sometimes want to copy it and then modify the copied object. We can't use `angular.copy` for this because it'll not change the `this` bound in the functions we add to the object. In this cases, you must use `Restangular.copy(fromElement)`.
+
+**[Back to top](#table-of-contents)**
## Enhanced promises
-Restangular uses enhanced promises when returning. What does this mean? All promises returned now have 2 additional methods and collection promises have 3. This are the methods:
+Restangular uses enhanced promises when returning. What does this mean? All promises returned now have 2 additional methods and collection promises have 3. These are the methods:
* **call(methodName, params*)**: This will return a new promise of the previous value, after calling the method called methodName with the parameters params.
* **get(fieldName)**: This will return a new promise for the type of the field. The param of this new promise is the property `fieldName` from the original promise result.
-* **push(object)**: This method will only be in the promises of arrays. It's a sub set of the call method that does a push.
-
-I know this explanations are quite complicated, so let's see an example :D.
+* **push(object)**: This method will only be in the promises of arrays. It's a subset of the call method that does a push.
+* **$object**: This returns the reference to the object that will be filled once the server responds a value. This means that if you call `getList` this will be an empty array by default. Once the array is returned from the server, this same `$object` property will get filled with results from the server.
+
+I know these explanations are quite complicated, so let's see an example :D.
````javascript
var buildings = Restangular.all("buildings").getList();
// New promise after adding the new building
-// Now you can show in scope this newBuildings promise and it'll show all the buildings
+// Now you can show in scope this newBuildings promise and it'll show all the buildings
// received from server plus the new one added
var newBuildings = buildings.push({name: "gonto"});
@@ -528,8 +849,96 @@ lengthPromise.then(function(length) {
});
````
+**[Back to top](#table-of-contents)**
+
+## Using values directly in templates
+
+Since Angular 1.2, Promise unwrapping in templates has been disabled by default and will be deprecated soon.
+
+**This means that the following will cease to work**:
+
+````js
+$scope.accounts = Restangular.all('accounts').getList();
+````
+
+````html
+
+
{{account.name}}
+
+````
+
+**As this was a really handy way of working with Restangular, I've made a feature similar to $resource that will enable this behavior again**:
+
+````js
+$scope.accounts = Restangular.all('accounts').getList().$object;
+````
+
+````html
+
+
{{account.name}}
+
+````
+
+The `$object` property is a new property I've added to promises. By default, it'll be an empty array or object. Once the sever has responded with the real value, that object or array is filled with the correct response, therefore making the ng-repeat work :). Pretty neat :D
+
+**[Back to top](#table-of-contents)**
+
+## Using Self reference resources
+
+A lot of REST APIs return the URL to self of the element that you're querying. You can use that with Restangular so that you don't have to create the URLs yourself, but use the ones provided by the server.
+
+Let's say that when doing a GET to `/people` you get the following
+
+````javascript
+[{
+ name: "Martin",
+ lastName: "Gontovnikas"
+ self: {
+ link: 'http://www.example.com/people/gonto'
+ }
+}, {
+ name: "John",
+ lastName: "Wayne"
+ self: {
+ link: 'http://www.example.com/people/jhonny'
+ }
+}]
+````
+
+In this case, as you can see, the URL to each element can't be guessed so we need to use that to reference the element. Restangular supports both relative and absolute URLs :).
+
+How do we do this with Restangular?
+
+First, we need to configure the path for the link to self. For that, in the config we do:
+
+````javascript
+RestangularProvider.setRestangularFields({
+ selfLink: 'self.link'
+});
+````
+
+Then, we can just use this :)
+
+````javascript
+// Instead of using all we could also use allUrl to set a URL
+// Restangular.allUrl('people', 'http://www.example.com/people')
+
+Restangular.all('people').getList().then(function(people) {
+
+ var gonto = people[0];
+
+ gonto.name = "Owned";
+
+ // This will do a PUT to http://www.example.com/people/gonto
+ // It uses the self linking property :D
+ gonto.put()
+})
+````
+
+**[Back to top](#table-of-contents)**
+
## URL Building
-Sometimes, we have a lot of entities names with their ids and we just want to fetch the later entity. In those cases, doing a request for everything to get the last entity is an overkill. For those cases, I've added the possibility to create URLs using the same API as creating a new Restangular object. This connections are created without doing any request. Let's see how to do this:
+Sometimes, we have a lot of nested entities (and their IDs), but we just want the last child. In those cases, doing a request for everything to get the last child is overkill. For those cases, I've added the possibility to create URLs using the same API as creating a new Restangular object. This connections are created without making any requests. Let's see how to do this:
````javascript
@@ -548,65 +957,81 @@ Restangular.one("accounts", 123).one("buildings", 456).all("spaces").post({name:
Restangular.one("accounts", 123).one("buildings", 456).remove();
````
+**[Back to top](#table-of-contents)**
+
+## Using local $http configuration
+
+There're sometimes when you want to set a specific configuration $http configuration just for one Restangular's call. For that, you can use `withHttpConfig`. You must call that method just before doing the HTTP request. Let's learn how to use it with the following example:
+
+````js
+Restangular.one('accounts', 123).withHttpConfig({timeout: 100}).getList('buildings');
+
+$scope.account.withHttpConfig({timeout: 100}).put();
+````
+
+**[Back to top](#table-of-contents)**
+
## Creating new Restangular Methods
-Let's assume that your API needs some custom methods to work. If that's the case, always calling customGET or customPOST for that method with all parameters is a pain in the ass. That's why every element has a `addRestangularMethod` method.
+Let's assume that your API needs some custom methods to work. If that's the case, always calling customGET or customPOST for that method with all parameters is a pain in the ass. That's why every element has a `addRestangularMethod` method.
This can be used together with the hook `addElementTransformer` to do some neat stuff. Let's see an example to learn this:
````javascript
-//In your app configuration (config method)
+// In your app configuration (config method)
// It will transform all building elements, NOT collections
RestangularProvider.addElementTransformer('buildings', false, function(building) {
// This will add a method called evaluate that will do a get to path evaluate with NO default
// query params and with some default header
// signature is (name, operation, path, params, headers, elementToPost)
-
+
building.addRestangularMethod('evaluate', 'get', 'evaluate', undefined, {'myHeader': 'value'});
-
+
return building;
});
RestangularProvider.addElementTransformer('users', true, function(user) {
// This will add a method called login that will do a POST to the path login
// signature is (name, operation, path, params, headers, elementToPost)
-
+
user.addRestangularMethod('login', 'post', 'login');
-
+
return user;
});
// Then, later in your code you can do the following:
-//GET to /buildings/123/evaluate?myParam=param with headers myHeader: value
+// GET to /buildings/123/evaluate?myParam=param with headers myHeader: value
-//Signature for this "custom created" methods is (params, headers, elem) if it's a safe operation (GET, OPTIONS, etc.)
+// Signature for this "custom created" methods is (params, headers, elem) if it's a safe operation (GET, OPTIONS, etc.)
// If it's an unsafe operation (POST, PUT, etc.), signature is (elem, params, headers).
-// If something is set to any of this variables, the default set in the method creation will be overrided
+// If something is set to any of this variables, the default set in the method creation will be overridden
// If nothing is set, then the defaults are sent
-Restangular.one('building', 123).evaluate({myParam: 'param'});
+Restangular.one('buildings', 123).evaluate({myParam: 'param'});
-//GET to /buildings/123/evaluate?myParam=param with headers myHeader: specialHeaderCase
+// GET to /buildings/123/evaluate?myParam=param with headers myHeader: specialHeaderCase
-Restangular.one('building', 123).evaluate({myParam: 'param'}, {'myHeader': 'specialHeaderCase'});
+Restangular.one('buildings', 123).evaluate({myParam: 'param'}, {'myHeader': 'specialHeaderCase'});
// Here the body of the POST is going to be {key: value} as POST is an unsafe operation
Restangular.all('users').login({key: value});
````
+**[Back to top](#table-of-contents)**
+
## Adding Custom Methods to Collections
Create custom methods for your collection using Restangular.extendCollection(). This is an alias for:
-```
- Restangular.addElementTransformer(route, true, fn)
+```js
+ Restangular.addElementTransformer(route, true, fn);
```
### Example:
-```
+```js
// create methods for your collection
Restangular.extendCollection('accounts', function(collection) {
collection.totalAmount = function() {
@@ -617,34 +1042,40 @@ Create custom methods for your collection using Restangular.extendCollection().
});
var accountsPromise = Restangular.all('accounts').getList();
-
+
accountsPromise.then(function(accounts) {
accounts.totalAmount(); // invoke your custom collection method
});
```
+**[Back to top](#table-of-contents)**
+
## Adding Custom Methods to Models
Create custom methods for your models using Restangular.extendModel(). This is an alias for:
+```js
+ Restangular.addElementTransformer(route, false, fn);
```
- Restangular.addElementTransformer(route, false, fn)
-```
+
+**[Back to top](#table-of-contents)**
### Example:
-```
+```js
Restangular.extendModel('accounts', function(model) {
model.prettifyAmount = function() {};
return model;
});
var accountPromise = Restangular.one('accounts', 1).get();
-
+
accountPromise.then(function(account) {
account.prettifyAmount(); // invoke your custom model method
});
```
+**[Back to top](#table-of-contents)**
+
# FAQ
#### **How can I handle errors?**
@@ -675,6 +1106,19 @@ RestangularProvider.setDefaultHttpFields({cache: true});
Yes, of course. Every method in Restangular returns a promise so this can be used without any problem.
+#### **How can I send a delete WITHOUT a body?**
+
+You must add a requestInterceptor for this.
+
+````js
+RestangularProvider.setRequestInterceptor(function(elem, operation) {
+ if (operation === "remove") {
+ return null;
+ }
+ return elem;
+})
+````
+
#### **My response is actually wrapped with some metadata. How do I get the data in that case?**
So, let's assume that your data is the following:
@@ -704,25 +1148,25 @@ So, let's assume that your data is the following:
}
````
-In this case, you'd need to configure Restangular's `responseExtractor`and `listTypeIsArray`. See the following:
+In this case, you'd need to use RestangularProvider's `addResponseInterceptor`. See the following:
````javascript
app.config(function(RestangularProvider) {
-
- // Now let's configure the response extractor for each request
- RestangularProvider.setResponseExtractor(function(response, operation, what, url) {
- // This is a get for a list
- var newResponse;
+
+ // add a response interceptor
+ RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
+ var extractedData;
+ // .. to look for getList operations
if (operation === "getList") {
- // Here we're returning an Array which has one special property metadata with our extra information
- newResponse = response.data.data;
- newResponse.metadata = response.data.meta;
+ // .. and handle the data and meta data
+ extractedData = data.data.data;
+ extractedData.meta = data.data.meta;
} else {
- // This is an element
- newResponse = response.data;
+ extractedData = data.data;
}
- return newResponse;
+ return extractedData;
});
+
});
````
@@ -736,6 +1180,28 @@ RestangularProvider.setRestangularFields({
});
````
+#### **What if each of my models has a different ID name like CustomerID for Customer**
+
+In some cases, people have different ID name for each entity. For example, they have CustomerID for customer and EquipmentID for Equipment. If that's the case, you can override Restangular's getIdFromElem. For that, you need to do:
+
+````js
+RestangularProvider.configuration.getIdFromElem = function(elem) {
+ // if route is customers ==> returns customerID
+ return elem[_.initial(elem.route).join('') + "ID"];
+}
+````
+With that, you'd get what you need :)
+
+#### **How can I send files in my request using Restangular?**
+
+This can be done using the customPOST / customPUT method. Look at the following example:
+````js
+Restangular.all('users')
+ .withHttpConfig({transformRequest: angular.identity})
+ .customPOST(formData, undefined, undefined,
+ { 'Content-Type': undefined });
+````
+This basically tells the request to use the *Content-Type: multipart/form-data* as the header. Also *formData* is the body of the request, be sure to add all the params here, including the File you want to send of course. There is an issue already closed but with a lot of information from other users and @mgonto as well: [GitHub - Restangular](https://github.com/mgonto/restangular/issues/420)
#### **How do I handle CRUD operations in a List returned by Restangular?**
@@ -753,8 +1219,8 @@ Restangular.all('users').getList().then(function(users) {
userWithId.name = "Gonto";
userWithId.put();
-
- // ALternatively delete element from list when finished
+
+ // Alternatively delete the element from the list when finished
userWithId.remove().then(function() {
// Updating the list and removing the user after the response is OK.
$scope.users = _.without($scope.users, userWithId);
@@ -763,15 +1229,28 @@ Restangular.all('users').getList().then(function(users) {
});
````
-When you actually get some list by doing
+When you actually get a list by doing
````javascript
-$scope.owners = house.getList('owners')
+$scope.owners = house.getList('owners').$object;
````
You're actually assigning a Promise to the owners value of the $scope. As Angular knows how to process promises, if in your view you do an ng-repeat of this $scope variable, results will be shown once the promise is resolved (Response arrived).
However, changes to that promise that you do from your HTML won't be seen in the scope, as it's not a real array. It's just a promise of an array.
+#### Removing an element from a collection, keeping the collection restangularized
+
+While the example above removes the deleted user from the collection, it also overwrites the collection object with a plain array (because of `_.without`) which no longer knows about its Restangular attributes.
+
+If want to keep the restangularized collection, remove the element by modifying the collection in place:
+
+```javascript
+userWithId.remove().then(function() {
+ var index = $scope.users.indexOf(userWithId);
+ if (index > -1) $scope.users.splice(index, 1);
+});
+```
+
#### When I set baseUrl with a port, it's stripped out.
It won't be stripped out anymore as I've ditched `$resource` :). Now you can happily put the port :).
@@ -794,41 +1273,107 @@ RestangularProvider.setResponseExtractor(function(response) {
return newResponse;
});
````
+Alternatively, if you just want the stripped out response on any given call, you can use the .plain() method, doing something like this:
+
+````javascript
+
+$scope.showData = function () {
+ baseUrl.post(someData).then(function(response) {
+ console.log(response.plain());
+ });
+};
+````
+
+**Addendum :** If you want originalElement to be the original response object instead of having an original value for each key in your newResponse array, replace
+
+
+
+````
+ newResponse[key].originalElement = angular.copy(value);
+````
+
+By
+
+
+````
+ newResponse.originalElement[key] = angular.copy(value);
+````
+
+#### Restangular fails with status code 0
+
+This is typically caused by Cross Origin Request policy. In order to enable cross domain communication and get correct response with appropriate status codes, you must have the CORS headers attached, even in error responses. If the server does not attach the CORS headers to the response then the XHR object won't parse it, thus the XHR object won't have any response body, status or any other response data inside which typically will cause your request to fail with status code 0.
#### Why does this depend on Lodash / Underscore?
-This is a very good question. I could've done the code so that I don't depend on Underscore nor Lodash, but I think both libraries make your life SO much easier. They have all of the "functional" stuff like map, reduce, filter, find, etc.
+This is a very good question. I could've done the code so that I don't depend on Underscore nor Lodash, but I think both libraries make your life SO much easier. They have all of the "functional" stuff like map, reduce, filter, find, etc.
With these libraries, you always work with immutable stuff, you get compatibility for browsers which don't implement ECMA5 nor some of these cool methods, and they're actually quicker.
So, why not use it? If you've never heard of them, by using Restangular, you could start using them. Trust me, you're never going to give them up after this!
+**[Back to top](#table-of-contents)**
+
+#### How do I cancel a request?
+
+Sometimes you may wish to cancel a request, this is how you would do it:
-# Supported Angular's version
+```
+var canceler = $q.defer();
+Restangular.all('users').withHttpConfig({timeout: canceler.promise}).get();
+canceler.resolve(); // cancels the request
+```
+
+This is a little counterintuitive, so let me explain. Restangular is built on top of `$http`, which takes a timeout parameter. As per the $http docs:
+
+ timeout in milliseconds, or promise that should abort the request when resolved.
-Restangular supports both 1.0.X and 1.1.X up to versions 1.0.7 and 1.1.5.
+Resolving the promise (canceler in this case), will cancel the request.
-Also, when using Restangular with version >= 1.1.4, in case you're using Restangular inside a callback not handled by Angular, you've to wrap this all request with a `$scope.apply` to make it work or you need to run one extra `$digest` manually. Check out https://github.com/mgonto/restangular/issues/71
+**[Back to top](#table-of-contents)**
+# Supported Angular versions
+
+Restangular supports all Angular versions from 1.0.X - 1.5.X
+
+Also, when using Restangular with version >= 1.1.4, in case you're using Restangular inside a callback not handled by Angular, you have to wrap the whole request with `$scope.apply` to make it work or you need to run one extra `$digest` manually. Check out https://github.com/mgonto/restangular/issues/71
+
+**[Back to top](#table-of-contents)**
# Server Frameworks
-This server frameworks play real nice with Restangular, as they let you create a Nested Restful Resources API easily:
+Users reported that this server frameworks play real nice with Restangular, as they let you create a Nested RESTful Resources API easily:
* Ruby on Rails
-* CakePHP for PHP
+* CakePHP, Laravel and FatFREE, Symfony2 with RestBundle, Silex for PHP
* Play1 & 2 for Java & scala
+* Dropwizard for Java
* Restify and Express for NodeJS
-* Tastypie for Django
+* Tastypie and Django Rest Framework for Django
+* Slim Framework
+* Symfony2 with FOSRestBundle (PHP)
+* Microsoft ASP.NET Web API 2
+* Grails Framework ([example](https://github.com/rmondejar/grails-angular-duo))
+**[Back to top](#table-of-contents)**
# Releases Notes
-[Click here to see Releases Notes](https://github.com/mgonto/restangular/blob/master/CHANGELOG.md)
+New releases notes are together with releases in GitHub at: https://github.com/mgonto/restangular/releases
+
+To see old releases notes, [you can click here](https://github.com/mgonto/restangular/blob/master/CHANGELOG.md)
+
+**[Back to top](#table-of-contents)**
+
+# Contributors
+
+* Martin Gontovnikas ([@mgonto](https://twitter.com/mgonto))
+* Paul Dijou ([@paul_dijou](https://twitter.com/paul_dijou))
+
+**[Back to top](#table-of-contents)**
# License
The MIT License
-Copyright (c) 2013 Martin Gontovnikas http://www.gon.to/
+Copyright (c) 2014 Martin Gontovnikas http://www.gon.to/
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:
@@ -836,3 +1381,8 @@ The above copyright notice and this permission notice shall be included in all c
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.
+
+
+[](https://bitdeli.com/free "Bitdeli Badge")
+
+**[Back to top](#table-of-contents)**
diff --git a/bower.json b/bower.json
index 4c874d65..ee38a810 100644
--- a/bower.json
+++ b/bower.json
@@ -1,19 +1,18 @@
{
"name": "restangular",
- "version": "1.0.10",
- "main": "./dist/restangular.min.js",
- "description": "Restfull Resources service for AngularJS apps",
+ "main": "./dist/restangular.js",
+ "description": "Restful Resources service for AngularJS apps",
"repository": {
"type": "git",
"url": "git://github.com/mgonto/restangular.git"
},
"dependencies": {
- "lodash": "~1.3.0",
- "angular": "*"
+ "lodash": "~4.17.0",
+ "angular": "~1.x"
},
"ignore": [
"node_modules",
"components",
"lib"
]
-}
\ No newline at end of file
+}
diff --git a/dist/dependencies/angular-resource.js b/dist/dependencies/angular-resource.js
deleted file mode 100644
index d67f501c..00000000
--- a/dist/dependencies/angular-resource.js
+++ /dev/null
@@ -1,457 +0,0 @@
-/**
- * @license AngularJS v1.0.7
- * (c) 2010-2012 Google, Inc. http://angularjs.org
- * License: MIT
- */
-(function(window, angular, undefined) {
-'use strict';
-
-/**
- * @ngdoc overview
- * @name ngResource
- * @description
- */
-
-/**
- * @ngdoc object
- * @name ngResource.$resource
- * @requires $http
- *
- * @description
- * A factory which creates a resource object that lets you interact with
- * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
- *
- * The returned resource object has action methods which provide high-level behaviors without
- * the need to interact with the low level {@link ng.$http $http} service.
- *
- * # Installation
- * To use $resource make sure you have included the `angular-resource.js` that comes in Angular
- * package. You can also find this file on Google CDN, bower as well as at
- * {@link http://code.angularjs.org/ code.angularjs.org}.
- *
- * Finally load the module in your application:
- *
- * angular.module('app', ['ngResource']);
- *
- * and you are ready to get started!
- *
- * @param {string} url A parameterized URL template with parameters prefixed by `:` as in
- * `/user/:username`. If you are using a URL with a port number (e.g.
- * `http://example.com:8080/api`), you'll need to escape the colon character before the port
- * number, like this: `$resource('http://example.com\\:8080/api')`.
- *
- * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
- * `actions` methods.
- *
- * Each key value in the parameter object is first bound to url template if present and then any
- * excess keys are appended to the url search query after the `?`.
- *
- * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
- * URL `/path/greet?salutation=Hello`.
- *
- * If the parameter value is prefixed with `@` then the value of that parameter is extracted from
- * the data object (useful for non-GET operations).
- *
- * @param {Object.