├── .gitignore ├── .jshintrc ├── .travis.yml ├── AssetFile ├── Gemfile ├── LICENSE ├── README.md ├── Rakefile ├── dist └── ember-resource.js ├── jshint.yml ├── spec └── javascripts │ ├── associationsSpec.js │ ├── autoFetchingSpec.js │ ├── deepMergeSpec.js │ ├── deepSetSpec.js │ ├── destroySpec.js │ ├── fetchSpec.js │ ├── identityMapSpec.js │ ├── inheritanceSpec.js │ ├── lifecycleSpec.js │ ├── remoteExpirySpec.js │ ├── resourceCollectionSpec.js │ ├── resourceSpec.js │ ├── resourceURLSpec.js │ ├── saveSpec.js │ ├── schemaSpec.js │ ├── support │ ├── jasmine.yml │ ├── jasmine_config.rb │ └── jasmine_runner.rb │ └── toJSONSpec.js ├── src ├── base.js ├── ember-resource.js ├── identity_map.js ├── remote_expiry.js └── vendor │ └── lru.js └── vendor ├── ember-0.9.8.1.js ├── jquery-1.7.js └── sinon-1.2.0.js /.gitignore: -------------------------------------------------------------------------------- 1 | Gemfile.lock 2 | .jhw-cache 3 | tmp 4 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "predef": [ 3 | "$", "SC", "_", "describe", "it", "expect", "beforeEach", 4 | "afterEach", "spyOn", "runs", "waits", "waitsFor", "sinon" 5 | ], 6 | 7 | "adsafe": false, 8 | "bitwise": true, 9 | "newcap": false, 10 | "eqeqeq": false, 11 | "eqnull": true, 12 | "immed": true, 13 | "nomen": false, 14 | "onevar": false, 15 | "plusplus": false, 16 | "regexp": false, 17 | "safe": false, 18 | "strict": false, 19 | "undef": true, 20 | "white": false, 21 | 22 | "cap": false, 23 | "css": true, 24 | "debug": false, 25 | "es5": false, 26 | "evil": false, 27 | "forin": false, 28 | "fragment": true, 29 | "laxbreak": false, 30 | "on": false, 31 | "sub": false, 32 | 33 | "maxlen": 200, 34 | "indent": 2, 35 | "maxerr": 50, 36 | "passfail": false, 37 | "browser": true, 38 | "rhino": false, 39 | "windows": false, 40 | "widget": false, 41 | "devel": true, 42 | "lastsemic": false, 43 | "newstat": false, 44 | "expr": true 45 | } -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | rvm: 1.9.3 2 | before_script: "sh -e /etc/init.d/xvfb start" 3 | env: "DISPLAY=:99.0" 4 | notifications: 5 | email: 6 | on_success: always 7 | -------------------------------------------------------------------------------- /AssetFile: -------------------------------------------------------------------------------- 1 | require 'rake-pipeline-web-filters' 2 | 3 | output "dist" 4 | 5 | files = ["vendor/lru.js", "base.js", "remote_expiry.js", "identity_map.js", "ember-resource.js"] 6 | 7 | input "src" do 8 | match "{#{files.join(',')}}" do 9 | concat files, "ember-resource.js" 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | gem 'jasmine', '1.1.0' 4 | gem 'JSHint', :git => 'https://github.com/rquinlivan/jshint-gem.git' 5 | gem 'rake' 6 | gem 'rake-pipeline', :git => 'https://github.com/livingsocial/rake-pipeline.git' 7 | gem 'rake-pipeline-web-filters', :git => 'https://github.com/wycats/rake-pipeline-web-filters.git' 8 | gem 'rails', ">= 3.0" #for some reason travis-ci.org wants this 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # This project has moved. The lovely people of Zendesk are now maintaining it at: [https://github.com/zendesk/ember-resource][1]. 2 | 3 | # Ember-Resource [![Build Status](https://secure.travis-ci.org/staugaard/ember-resource.png)](http://travis-ci.org/staugaard/ember-resource) 4 | 5 | A simple library to connect your Ember.js application to JSON backends. 6 | 7 | ## The Mandatory Todo Appplication 8 | 9 | I've created a modified version of the todo application that the Ember.js Tutorial walks you through. 10 | https://github.com/staugaard/sproutcore-resource-todos 11 | This version persists the todo items on the server using a very small sinatra application and MongoDB. 12 | 13 | ## Examples 14 | 15 | We will provide you with some documentation and stuff, but for now here's a little inspiration: 16 | 17 | Think about running Wordpress.org. This is the schema you would use: 18 | 19 | Assuming that /users/1 returns this JSON: 20 | 21 | ```javascript 22 | { 23 | id: 1, 24 | name: "Mick Staugaard" 25 | } 26 | ``` 27 | 28 | You would use this user model: 29 | 30 | ```javascript 31 | MyApp.User = Ember.Resource.define({ 32 | url: '/users', 33 | schema: { 34 | id: Number, 35 | name: String, 36 | blogs: { 37 | type: Ember.ResourceCollection, 38 | itemType: 'MyApp.Blog', 39 | url: '/users/%@/blogs' 40 | } 41 | } 42 | }); 43 | ``` 44 | 45 | Assuming that /blogs/1 returns this JSON: 46 | 47 | ```javascript 48 | { 49 | id: 1, 50 | name: "My awesome blog", 51 | owner_id: 1 52 | } 53 | ``` 54 | 55 | You would use this blog model: 56 | 57 | ```javascript 58 | MyApp.Blog = Ember.Resource.define({ 59 | url: '/blogs' 60 | schema: { 61 | id: Number, 62 | name: String, 63 | owner: { 64 | type: MyApp.User 65 | }, 66 | posts: { 67 | type: Ember.ResourceCollection, 68 | itemType: 'MyApp.Post', 69 | url: '/blogs/%@/posts' 70 | } 71 | } 72 | }); 73 | ``` 74 | 75 | Assuming that /posts/1 returns this JSON: 76 | 77 | ```javascript 78 | { 79 | id: 1, 80 | title: "Welcome to the blog", 81 | body: "OMG I started a blog!", 82 | blog_id: 1 83 | } 84 | ``` 85 | 86 | You would use this post model: 87 | 88 | ```javascript 89 | MyApp.Post = Ember.Resource.define({ 90 | url: '/posts', 91 | schema: { 92 | id: Number, 93 | title: Sting, 94 | body: String, 95 | blog: { 96 | type: MyApp.Blog 97 | }, 98 | comments: { 99 | type: Ember.ResourceCollection, 100 | itemType: 'MyApp.Comment', 101 | url: '/posts/%@/comments' 102 | } 103 | } 104 | }); 105 | ``` 106 | 107 | Assuming that /comments/1 returns this JSON: 108 | 109 | ```javascript 110 | { 111 | id: 1, 112 | body: "I have something constructive to say.", 113 | post_id: 1, 114 | author: { 115 | id: 2, 116 | name: "Comment Author" 117 | } 118 | } 119 | ``` 120 | 121 | You would use this comment model: 122 | 123 | ```javascript 124 | MyApp.Comment = Ember.Resource.define({ 125 | url: '/comments', 126 | schema: { 127 | id: Number, 128 | body: String, 129 | post: { 130 | type: MyApp.Post 131 | }, 132 | author: { 133 | type: MyApp.User, 134 | nested: true 135 | } 136 | } 137 | }); 138 | ``` 139 | 140 | ## Copyright and license 141 | 142 | Copyright 2013 Zendesk 143 | 144 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 145 | You may obtain a copy of the License at 146 | 147 | http://www.apache.org/licenses/LICENSE-2.0 148 | 149 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 150 | 151 | [1]: https://github.com/zendesk/ember-resource 152 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require 'bundler/setup' 2 | require 'pathname' 3 | require 'rake-pipeline' 4 | 5 | namespace :dist do 6 | task :build do 7 | Rake::Pipeline::Project.new('AssetFile').invoke 8 | end 9 | 10 | task :clean do 11 | Rake::Pipeline::Project.new('AssetFile').clean 12 | end 13 | 14 | task :cleanup_tmpdir do 15 | Rake::Pipeline::Project.new('AssetFile').cleanup_tmpdir 16 | end 17 | 18 | end 19 | 20 | namespace :jasmine do 21 | task :require do 22 | require 'jasmine' 23 | end 24 | 25 | task :require_json do 26 | begin 27 | require 'json' 28 | rescue LoadError 29 | puts "You must have a JSON library installed to run jasmine:ci. Try \"gem install json\"" 30 | exit 31 | end 32 | end 33 | 34 | desc "Run continuous integration tests" 35 | task :ci => ["jasmine:require_json", "jasmine:require", "dist:build"] do 36 | if Jasmine::rspec2? 37 | require "rspec" 38 | require "rspec/core/rake_task" 39 | else 40 | require "spec" 41 | require 'spec/rake/spectask' 42 | end 43 | 44 | if Jasmine::rspec2? 45 | RSpec::Core::RakeTask.new(:jasmine_continuous_integration_runner) do |t| 46 | t.rspec_opts = ["--colour", "--format", ENV['JASMINE_SPEC_FORMAT'] || "progress"] 47 | t.verbose = true 48 | t.pattern = ['spec/javascripts/support/jasmine_runner.rb'] 49 | end 50 | else 51 | Spec::Rake::SpecTask.new(:jasmine_continuous_integration_runner) do |t| 52 | t.spec_opts = ["--color", "--format", ENV['JASMINE_SPEC_FORMAT'] || "specdoc"] 53 | t.verbose = true 54 | t.spec_files = ['spec/javascripts/support/jasmine_runner.rb'] 55 | end 56 | end 57 | Rake::Task["jasmine_continuous_integration_runner"].invoke 58 | end 59 | 60 | task :server => ["jasmine:require", "dist:build"] do 61 | jasmine_config_overrides = File.join(Jasmine::Config.new.project_root, 'spec', 'javascripts' ,'support' ,'jasmine_config.rb') 62 | require jasmine_config_overrides if File.exist?(jasmine_config_overrides) 63 | 64 | port = ENV['JASMINE_PORT'] || 8888 65 | puts "your tests are here:" 66 | puts " http://localhost:#{port}/" 67 | Jasmine::Config.new.start_server(port) 68 | end 69 | end 70 | 71 | desc "Run specs via server" 72 | task :jasmine => ['jasmine:server'] 73 | 74 | 75 | require 'jshint/tasks' 76 | JSHint.config_path = 'jshint.yml' 77 | 78 | 79 | task :default => ['jshint', 'jasmine:ci'] 80 | -------------------------------------------------------------------------------- /dist/ember-resource.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most 3 | * recently used items while discarding least recently used items when its limit 4 | * is reached. 5 | * 6 | * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson 7 | * See README.md for details. 8 | * 9 | * Illustration of the design: 10 | * 11 | * entry entry entry entry 12 | * ______ ______ ______ ______ 13 | * | head |.newer => | |.newer => | |.newer => | tail | 14 | * | A | | B | | C | | D | 15 | * |______| <= older.|______| <= older.|______| <= older.|______| 16 | * 17 | * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added 18 | */ 19 | function LRUCache (limit) { 20 | // Current size of the cache. (Read-only). 21 | this.size = 0; 22 | // Maximum number of items this cache can hold. 23 | this.limit = limit; 24 | this._keymap = {}; 25 | } 26 | 27 | /** 28 | * Put into the cache associated with . Returns the entry which was 29 | * removed to make room for the new entry. Otherwise undefined is returned 30 | * (i.e. if there was enough room already). 31 | */ 32 | LRUCache.prototype.put = function(key, value) { 33 | var entry = {key:key, value:value}; 34 | // Note: No protection agains replacing, and thus orphan entries. By design. 35 | this._keymap[key] = entry; 36 | if (this.tail) { 37 | // link previous tail to the new tail (entry) 38 | this.tail.newer = entry; 39 | entry.older = this.tail; 40 | } else { 41 | // we're first in -- yay 42 | this.head = entry; 43 | } 44 | // add new entry to the end of the linked list -- it's now the freshest entry. 45 | this.tail = entry; 46 | if (this.size === this.limit) { 47 | // we hit the limit -- remove the head 48 | return this.shift(); 49 | } else { 50 | // increase the size counter 51 | this.size++; 52 | } 53 | } 54 | 55 | /** 56 | * Purge the least recently used (oldest) entry from the cache. Returns the 57 | * removed entry or undefined if the cache was empty. 58 | * 59 | * If you need to perform any form of finalization of purged items, this is a 60 | * good place to do it. Simply override/replace this function: 61 | * 62 | * var c = new LRUCache(123); 63 | * c.shift = function() { 64 | * var entry = LRUCache.prototype.shift.call(this); 65 | * doSomethingWith(entry); 66 | * return entry; 67 | * } 68 | */ 69 | LRUCache.prototype.shift = function() { 70 | // todo: handle special case when limit == 1 71 | var entry = this.head; 72 | if (entry) { 73 | if (this.head.newer) { 74 | this.head = this.head.newer; 75 | this.head.older = undefined; 76 | } else { 77 | this.head = undefined; 78 | } 79 | // Remove last strong reference to and remove links from the purged 80 | // entry being returned: 81 | entry.newer = entry.older = undefined; 82 | // delete is slow, but we need to do this to avoid uncontrollable growth: 83 | delete this._keymap[entry.key]; 84 | } 85 | return entry; 86 | } 87 | 88 | /** 89 | * Get and register recent use of . Returns the value associated with 90 | * or undefined if not in cache. 91 | */ 92 | LRUCache.prototype.get = function(key, returnEntry) { 93 | // First, find our cache entry 94 | var entry = this._keymap[key]; 95 | if (entry === undefined) return; // Not cached. Sorry. 96 | // As was found in the cache, register it as being requested recently 97 | if (entry === this.tail) { 98 | // Already the most recenlty used entry, so no need to update the list 99 | return entry.value; 100 | } 101 | // HEAD--------------TAIL 102 | // <.older .newer> 103 | // <--- add direction -- 104 | // A B C E 105 | if (entry.newer) { 106 | if (entry === this.head) 107 | this.head = entry.newer; 108 | entry.newer.older = entry.older; // C <-- E. 109 | } 110 | if (entry.older) 111 | entry.older.newer = entry.newer; // C. --> E 112 | entry.newer = undefined; // D --x 113 | entry.older = this.tail; // D. --> E 114 | if (this.tail) 115 | this.tail.newer = entry; // E. <-- D 116 | this.tail = entry; 117 | return returnEntry ? entry : entry.value; 118 | } 119 | 120 | // ---------------------------------------------------------------------------- 121 | // Following code is optional and can be removed without breaking the core 122 | // functionality. 123 | 124 | /** 125 | * Check if is in the cache without registering recent use. Feasible if 126 | * you do not want to chage the state of the cache, but only "peek" at it. 127 | * Returns the entry associated with if found, or undefined if not found. 128 | */ 129 | LRUCache.prototype.find = function(key) { 130 | return this._keymap[key]; 131 | } 132 | 133 | /** 134 | * Update the value of entry with . Returns the old value, or undefined if 135 | * entry was not in the cache. 136 | */ 137 | LRUCache.prototype.set = function(key, value) { 138 | var oldvalue, entry = this.get(key, true); 139 | if (entry) { 140 | oldvalue = entry.value; 141 | entry.value = value; 142 | } else { 143 | oldvalue = this.put(key, value); 144 | if (oldvalue) oldvalue = oldvalue.value; 145 | } 146 | return oldvalue; 147 | } 148 | 149 | /** 150 | * Remove entry from cache and return its value. Returns undefined if not 151 | * found. 152 | */ 153 | LRUCache.prototype.remove = function(key) { 154 | var entry = this._keymap[key]; 155 | if (!entry) return; 156 | delete this._keymap[entry.key]; // need to do delete unfortunately 157 | if (entry.newer && entry.older) { 158 | // relink the older entry with the newer entry 159 | entry.older.newer = entry.newer; 160 | entry.newer.older = entry.older; 161 | } else if (entry.newer) { 162 | // remove the link to us 163 | entry.newer.older = undefined; 164 | // link the newer entry to head 165 | this.head = entry.newer; 166 | } else if (entry.older) { 167 | // remove the link to us 168 | entry.older.newer = undefined; 169 | // link the newer entry to head 170 | this.tail = entry.older; 171 | } else {// if(entry.older === undefined && entry.newer === undefined) { 172 | this.head = this.tail = undefined; 173 | } 174 | 175 | this.size--; 176 | return entry.value; 177 | } 178 | 179 | /** Removes all entries */ 180 | LRUCache.prototype.removeAll = function() { 181 | // This should be safe, as we never expose strong refrences to the outside 182 | this.head = this.tail = undefined; 183 | this.size = 0; 184 | this._keymap = {}; 185 | } 186 | 187 | /** 188 | * Return an array containing all keys of entries stored in the cache object, in 189 | * arbitrary order. 190 | */ 191 | if (typeof Object.keys === 'function') { 192 | LRUCache.prototype.keys = function() { return Object.keys(this._keymap); } 193 | } else { 194 | LRUCache.prototype.keys = function() { 195 | var keys = []; 196 | for (var k in this._keymap) keys.push(k); 197 | return keys; 198 | } 199 | } 200 | 201 | /** 202 | * Call `fun` for each entry. Starting with the newest entry if `desc` is a true 203 | * value, otherwise starts with the oldest (head) enrty and moves towards the 204 | * tail. 205 | * 206 | * `fun` is called with 3 arguments in the context `context`: 207 | * `fun.call(context, Object key, Object value, LRUCache self)` 208 | */ 209 | LRUCache.prototype.forEach = function(fun, context, desc) { 210 | if (context === true) { desc = true; context = undefined; } 211 | else if (typeof context !== 'object') context = this; 212 | if (desc) { 213 | var entry = this.tail; 214 | while (entry) { 215 | fun.call(context, entry.key, entry.value, this); 216 | entry = entry.older; 217 | } 218 | } else { 219 | var entry = this.head; 220 | while (entry) { 221 | fun.call(context, entry.key, entry.value, this); 222 | entry = entry.newer; 223 | } 224 | } 225 | } 226 | 227 | /** Returns a JSON (array) representation */ 228 | LRUCache.prototype.toJSON = function() { 229 | var s = [], entry = this.head; 230 | while (entry) { 231 | s.push({key:entry.key.toJSON(), value:entry.value.toJSON()}); 232 | entry = entry.newer; 233 | } 234 | return s; 235 | } 236 | 237 | /** Returns a String representation */ 238 | LRUCache.prototype.toString = function() { 239 | var s = '', entry = this.head; 240 | while (entry) { 241 | s += String(entry.key)+':'+entry.value; 242 | if (entry = entry.newer) 243 | s += ' < '; 244 | } 245 | return s; 246 | } 247 | 248 | // Export ourselves 249 | if (typeof this === 'object') this.LRUCache = LRUCache; 250 | (function() { 251 | 252 | window.Ember = window.Ember || window.SC; 253 | 254 | window.Ember.Resource = window.Ember.Object.extend({ 255 | resourcePropertyWillChange: window.Ember.K, 256 | resourcePropertyDidChange: window.Ember.K 257 | }); 258 | 259 | window.Ember.Resource.SUPPORT_AUTOFETCH = true; 260 | }()); 261 | (function(exports) { 262 | 263 | var Ember = exports.Ember, NullTransport = { 264 | subscribe: Ember.K, 265 | unsubscribe: Ember.K 266 | }; 267 | 268 | Ember.Resource.PushTransport = NullTransport; 269 | 270 | var RemoteExpiry = Ember.Mixin.create({ 271 | init: function() { 272 | var ret = this._super(), 273 | self = this, 274 | remoteExpiryScope = this.get('remoteExpiryKey'); 275 | 276 | this.set('_subscribedForExpiry', false); 277 | 278 | if(!remoteExpiryScope) { 279 | return ret; 280 | } 281 | 282 | Ember.addListener(this, 'didFetch', this, function() { 283 | self.subscribeForExpiry(); 284 | }); 285 | 286 | return ret; 287 | }, 288 | 289 | subscribeForExpiry: function() { 290 | var remoteExpiryScope = this.get('remoteExpiryKey'), 291 | self = this; 292 | 293 | if(!remoteExpiryScope) { 294 | return; 295 | } 296 | 297 | if(this.get('_subscribedForExpiry')) { 298 | return; 299 | } 300 | 301 | Ember.Resource.PushTransport.subscribe(remoteExpiryScope, function(message) { 302 | self.updateExpiry(message); 303 | }); 304 | 305 | this.set('_subscribedForExpiry', true); 306 | }, 307 | 308 | updateExpiry: function(message) { 309 | var updatedAt = message && message.updatedAt; 310 | if(!updatedAt) return; 311 | if(this.stale(updatedAt)) { 312 | this.set('expiryUpdatedAt', updatedAt); 313 | if(this.get('remoteExpiryAutoFetch')) { 314 | this.set('isExpired', true); 315 | this.fetch(); 316 | } else { 317 | this.expire(); 318 | } 319 | } 320 | }, 321 | 322 | stale: function(updatedAt) { 323 | return !this.get('expiryUpdatedAt') || (+this.get('expiryUpdatedAt') < +updatedAt); 324 | } 325 | }); 326 | 327 | Ember.Resource.RemoteExpiry = RemoteExpiry; 328 | 329 | }(this)); 330 | (function() { 331 | Ember.Resource.IdentityMap = function(limit) { 332 | this.cache = new LRUCache(limit || Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT); 333 | }; 334 | 335 | Ember.Resource.IdentityMap.prototype = { 336 | get: function() { 337 | return LRUCache.prototype.get.apply(this.cache, arguments); 338 | }, 339 | 340 | put: function() { 341 | return LRUCache.prototype.put.apply(this.cache, arguments); 342 | }, 343 | 344 | remove: function() { 345 | return LRUCache.prototype.remove.apply(this.cache, arguments); 346 | }, 347 | 348 | clear: function() { 349 | return LRUCache.prototype.removeAll.apply(this.cache, arguments); 350 | }, 351 | 352 | size: function() { 353 | return this.cache.size; 354 | }, 355 | 356 | limit: function() { 357 | return this.cache.limit; 358 | } 359 | 360 | }; 361 | 362 | Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT = 500; 363 | 364 | }()); 365 | (function(exports) { 366 | 367 | var expandSchema, expandSchemaItem, createSchemaProperties, 368 | mergeSchemas; 369 | 370 | var Ember = exports.Ember; 371 | 372 | function isString(obj) { 373 | return !!(obj === '' || (obj && obj !== String && obj.charCodeAt && obj.substr)); 374 | } 375 | 376 | function isObject(obj) { 377 | return obj === Object(obj); 378 | } 379 | 380 | Ember.Resource.deepSet = function(obj, path, value) { 381 | if (Ember.typeOf(path) === 'string') { 382 | Ember.Resource.deepSet(obj, path.split('.'), value); 383 | return; 384 | } 385 | 386 | var key = path.shift(); 387 | 388 | if (path.length === 0) { 389 | Ember.set(obj, key, value); 390 | } else { 391 | var newObj = Ember.get(obj, key); 392 | 393 | if (newObj === null || newObj === undefined) { 394 | newObj = {}; 395 | Ember.set(obj, key, newObj); 396 | } 397 | 398 | Ember.propertyWillChange(newObj, path); 399 | Ember.Resource.deepSet(newObj, path, value); 400 | Ember.propertyDidChange(newObj, path); 401 | } 402 | }; 403 | 404 | Ember.Resource.deepMerge = function(objA, objB) { 405 | var oldValue, newValue; 406 | 407 | for (var key in objB) { 408 | if (objB.hasOwnProperty(key)) { 409 | oldValue = Ember.get(objA, key); 410 | newValue = Ember.get(objB, key); 411 | 412 | if (Ember.typeOf(newValue) === 'object' && Ember.typeOf(oldValue) === 'object') { 413 | Ember.propertyWillChange(objA, key); 414 | Ember.Resource.deepMerge(oldValue, newValue); 415 | Ember.propertyDidChange(objA, key); 416 | } else { 417 | Ember.set(objA, key, newValue); 418 | } 419 | } 420 | } 421 | }; 422 | 423 | Ember.Resource.AbstractSchemaItem = Ember.Object.extend({ 424 | name: Ember.required(String), 425 | fetchable: Ember.required(Boolean), 426 | getValue: Ember.required(Function), 427 | setValue: Ember.required(Function), 428 | 429 | dependencies: Ember.computed('path', function() { 430 | var deps = ['data.' + this.get('path')]; 431 | 432 | if(Ember.Resource.SUPPORT_AUTOFETCH) { 433 | deps.push('isExpired'); 434 | } 435 | 436 | return deps; 437 | }).cacheable(), 438 | 439 | data: function(instance) { 440 | return Ember.get(instance, 'data'); 441 | }, 442 | 443 | type: Ember.computed('theType', function() { 444 | var type = this.get('theType'); 445 | if (isString(type)) { 446 | type = Ember.getPath(type); 447 | if (type) { 448 | this.set('theType', type); 449 | } else { 450 | type = this.get('theType'); 451 | } 452 | } 453 | return type; 454 | }).cacheable(), 455 | 456 | propertyFunction: function(name, value) { 457 | var schemaItem = this.constructor.schema[name]; 458 | if (arguments.length === 2) { 459 | this.resourcePropertyWillChange(name, value); 460 | schemaItem.setValue.call(schemaItem, this, value); 461 | value = schemaItem.getValue.call(schemaItem, this); 462 | this.resourcePropertyDidChange(name, value); 463 | } else { 464 | value = schemaItem.getValue.call(schemaItem, this); 465 | if ((value === undefined || Ember.get(this, 'isExpired')) && schemaItem.get('fetchable')) { 466 | this.scheduleFetch(); 467 | } 468 | } 469 | return value; 470 | }, 471 | 472 | property: function() { 473 | var cp = new Ember.ComputedProperty(this.propertyFunction); 474 | return cp.property.apply(cp, this.get('dependencies')).cacheable(); 475 | }, 476 | 477 | toJSON: function(instance) { 478 | return undefined; 479 | } 480 | }); 481 | Ember.Resource.AbstractSchemaItem.reopenClass({ 482 | create: function(name, schema) { 483 | var instance = this._super.apply(this); 484 | instance.set('name', name); 485 | return instance; 486 | } 487 | }); 488 | 489 | 490 | Ember.Resource.SchemaItem = Ember.Resource.AbstractSchemaItem.extend({}); 491 | 492 | Ember.Resource.SchemaItem.reopenClass({ 493 | create: function(name, schema) { 494 | var definition = schema[name]; 495 | 496 | if (definition instanceof Ember.Resource.AbstractSchemaItem) { return definition; } 497 | 498 | var type; 499 | if (definition === Number || definition === String || definition === Boolean || definition === Date || definition === Object) { 500 | definition = {type: definition}; 501 | schema[name] = definition; 502 | } 503 | 504 | if(isObject(definition)) { 505 | type = definition.type; 506 | } 507 | 508 | if (type) { 509 | if (type.isEmberResource || Ember.typeOf(type) === 'string') { // a has-one association 510 | return Ember.Resource.HasOneSchemaItem.create(name, schema); 511 | } else if(type.isEmberResourceCollection) { // a has-many association 512 | return Ember.Resource.HasManySchemaItem.create(name, schema); 513 | } else { // a regular attribute 514 | return Ember.Resource.AttributeSchemaItem.create(name, schema); 515 | } 516 | } 517 | } 518 | }); 519 | 520 | Ember.Resource.AttributeSchemaItem = Ember.Resource.AbstractSchemaItem.extend({ 521 | fetchable: true, 522 | theType: Object, 523 | path: Ember.required(String), 524 | 525 | getValue: function(instance) { 526 | var value; 527 | var data = this.data(instance); 528 | if (data) { 529 | value = Ember.getPath(data, this.get('path')); 530 | } 531 | 532 | if (this.typeCast) { 533 | value = this.typeCast(value); 534 | } 535 | 536 | return value; 537 | }, 538 | 539 | setValue: function(instance, value) { 540 | var data = this.data(instance); 541 | if (!data) return; 542 | 543 | if (this.typeCast) { 544 | value = this.typeCast(value); 545 | } 546 | if (value !== null && value !== undefined && Ember.typeOf(value.toJSON) == 'function') { 547 | value = value.toJSON(); 548 | } 549 | Ember.Resource.deepSet(data, this.get('path'), value); 550 | }, 551 | 552 | toJSON: function(instance) { 553 | return Ember.get(instance, this.name); 554 | } 555 | }); 556 | 557 | Ember.Resource.AttributeSchemaItem.reopenClass({ 558 | create: function(name, schema) { 559 | var definition = schema[name]; 560 | var instance; 561 | 562 | if (this === Ember.Resource.AttributeSchemaItem) { 563 | switch (definition.type) { 564 | case Number: 565 | return Ember.Resource.NumberAttributeSchemaItem.create(name, schema); 566 | case String: 567 | return Ember.Resource.StringAttributeSchemaItem.create(name, schema); 568 | case Boolean: 569 | return Ember.Resource.BooleanAttributeSchemaItem.create(name, schema); 570 | case Date: 571 | return Ember.Resource.DateAttributeSchemaItem.create(name, schema); 572 | default: 573 | instance = this._super.apply(this, arguments); 574 | instance.set('fetchable', name !== 'id'); 575 | instance.set('path', definition.path || name); 576 | return instance; 577 | } 578 | } 579 | else { 580 | instance = this._super.apply(this, arguments); 581 | instance.set('fetchable', name !== 'id'); 582 | instance.set('path', definition.path || name); 583 | return instance; 584 | } 585 | } 586 | }); 587 | 588 | Ember.Resource.NumberAttributeSchemaItem = Ember.Resource.AttributeSchemaItem.extend({ 589 | theType: Number, 590 | typeCast: function(value) { 591 | if (isNaN(value)) { 592 | value = undefined; 593 | } 594 | 595 | if (value === undefined || value === null || Ember.typeOf(value) === 'number') { 596 | return value; 597 | } else { 598 | return Number(value); 599 | } 600 | } 601 | }); 602 | 603 | Ember.Resource.StringAttributeSchemaItem = Ember.Resource.AttributeSchemaItem.extend({ 604 | theType: String, 605 | typeCast: function(value) { 606 | if (value === undefined || value === null || Ember.typeOf(value) === 'string') { 607 | return value; 608 | } else { 609 | return '' + value; 610 | } 611 | } 612 | }); 613 | 614 | Ember.Resource.BooleanAttributeSchemaItem = Ember.Resource.AttributeSchemaItem.extend({ 615 | theType: Boolean, 616 | typeCast: function(value) { 617 | if (value === undefined || value === null || Ember.typeOf(value) === 'boolean') { 618 | return value; 619 | } else { 620 | return value === 'true'; 621 | } 622 | } 623 | }); 624 | 625 | Ember.Resource.DateAttributeSchemaItem = Ember.Resource.AttributeSchemaItem.extend({ 626 | theType: Date, 627 | typeCast: function(value) { 628 | if (value === undefined || value === null || Ember.typeOf(value) === 'date') { 629 | return value; 630 | } else { 631 | return new Date(value); 632 | } 633 | }, 634 | toJSON: function(instance) { 635 | var value = Ember.get(instance, this.name); 636 | return value ? value.toJSON() : value; 637 | } 638 | }); 639 | 640 | Ember.Resource.HasOneSchemaItem = Ember.Resource.AbstractSchemaItem.extend({ 641 | fetchable: true 642 | }); 643 | Ember.Resource.HasOneSchemaItem.reopenClass({ 644 | create: function(name, schema) { 645 | var definition = schema[name]; 646 | if (this === Ember.Resource.HasOneSchemaItem) { 647 | if (definition.nested) { 648 | return Ember.Resource.HasOneNestedSchemaItem.create(name, schema); 649 | } else { 650 | return Ember.Resource.HasOneRemoteSchemaItem.create(name, schema); 651 | } 652 | } 653 | else { 654 | var instance = this._super.apply(this, arguments); 655 | instance.set('theType', definition.type); 656 | if (definition.parse) { 657 | instance.set('parse', definition.parse); 658 | } 659 | return instance; 660 | } 661 | } 662 | }); 663 | 664 | Ember.Resource.HasOneNestedSchemaItem = Ember.Resource.HasOneSchemaItem.extend({ 665 | getValue: function(instance) { 666 | var data = this.data(instance); 667 | if (!data) return; 668 | var type = this.get('type'); 669 | var value = Ember.getPath(data, this.get('path')); 670 | if (value) { 671 | value = (this.get('parse') || type.parse).call(type, Ember.copy(value)); 672 | return type.create({}, value); 673 | } 674 | return value; 675 | }, 676 | 677 | setValue: function(instance, value) { 678 | var data = this.data(instance); 679 | if (!data) return; 680 | 681 | if (value instanceof this.get('type')) { 682 | value = Ember.get(value, 'data'); 683 | } 684 | 685 | Ember.Resource.deepSet(data, this.get('path'), value); 686 | }, 687 | 688 | toJSON: function(instance) { 689 | var value = Ember.get(instance, this.name); 690 | return value ? value.toJSON() : value; 691 | } 692 | }); 693 | Ember.Resource.HasOneNestedSchemaItem.reopenClass({ 694 | create: function(name, schema) { 695 | var definition = schema[name]; 696 | var instance = this._super.apply(this, arguments); 697 | instance.set('path', definition.path || name); 698 | 699 | var id_name = name + '_id'; 700 | if (!schema[id_name]) { 701 | schema[id_name] = {type: Number, association: instance }; 702 | schema[id_name] = Ember.Resource.HasOneNestedIdSchemaItem.create(id_name, schema); 703 | } 704 | 705 | return instance; 706 | } 707 | }); 708 | Ember.Resource.HasOneNestedIdSchemaItem = Ember.Resource.AbstractSchemaItem.extend({ 709 | fetchable: true, 710 | theType: Number, 711 | getValue: function(instance) { 712 | return instance.getPath(this.get('path')); 713 | }, 714 | setValue: function(instance, value) { 715 | Ember.set(instance, this.getPath('association.name'), {id: value}); 716 | } 717 | }); 718 | Ember.Resource.HasOneNestedIdSchemaItem.reopenClass({ 719 | create: function(name, schema) { 720 | var definition = schema[name]; 721 | var instance = this._super.apply(this, arguments); 722 | instance.set('association', definition.association); 723 | instance.set('path', definition.association.get('path') + '.id'); 724 | return instance; 725 | } 726 | }); 727 | 728 | 729 | Ember.Resource.HasOneRemoteSchemaItem = Ember.Resource.HasOneSchemaItem.extend({ 730 | getValue: function(instance) { 731 | var data = this.data(instance); 732 | if (!data) return; 733 | var id = Ember.getPath(data, this.get('path')); 734 | if (id) { 735 | return this.get('type').create({}, {id: id}); 736 | } 737 | }, 738 | 739 | setValue: function(instance, value) { 740 | var data = this.data(instance); 741 | if (!data) return; 742 | var id = Ember.get(value || {}, 'id'); 743 | Ember.Resource.deepSet(data, this.get('path'), id); 744 | } 745 | }); 746 | Ember.Resource.HasOneRemoteSchemaItem.reopenClass({ 747 | create: function(name, schema) { 748 | var definition = schema[name]; 749 | var instance = this._super.apply(this, arguments); 750 | var path = definition.path || name + '_id'; 751 | instance.set('path', path); 752 | 753 | if (!schema[path]) { 754 | schema[path] = Number; 755 | schema[path] = Ember.Resource.SchemaItem.create(path, schema); 756 | } 757 | 758 | return instance; 759 | } 760 | }); 761 | 762 | 763 | Ember.Resource.HasManySchemaItem = Ember.Resource.AbstractSchemaItem.extend({ 764 | itemType: Ember.computed('theItemType', function() { 765 | var type = this.get('theItemType'); 766 | if (isString(type)) { 767 | type = Ember.getPath(type); 768 | if (type) { 769 | this.set('theItemType', type); 770 | } else { 771 | type = this.get('theItemType'); 772 | } 773 | } 774 | return type; 775 | }).cacheable() 776 | }); 777 | 778 | Ember.Resource.HasManySchemaItem.reopenClass({ 779 | create: function(name, schema) { 780 | var definition = schema[name]; 781 | if (this === Ember.Resource.HasManySchemaItem) { 782 | if (definition.url) { 783 | return Ember.Resource.HasManyRemoteSchemaItem.create(name, schema); 784 | } else if (definition.nested) { 785 | return Ember.Resource.HasManyNestedSchemaItem.create(name, schema); 786 | } else { 787 | return Ember.Resource.HasManyInArraySchemaItem.create(name, schema); 788 | } 789 | } else { 790 | var instance = this._super.apply(this, arguments); 791 | instance.set('theType', definition.type); 792 | instance.set('theItemType', definition.itemType); 793 | if (definition.parse) { 794 | instance.set('parse', definition.parse); 795 | } 796 | return instance; 797 | } 798 | } 799 | }); 800 | 801 | Ember.Resource.HasManyRemoteSchemaItem = Ember.Resource.HasManySchemaItem.extend({ 802 | fetchable: false, 803 | dependencies: ['id', 'isInitializing'], 804 | getValue: function(instance) { 805 | if (Ember.get(instance, 'isInitializing')) return; 806 | 807 | var options = { 808 | type: this.get('itemType') 809 | }; 810 | 811 | if (this.get('parse')) options.parse = this.get('parse'); 812 | 813 | var url = this.url(instance); 814 | if (url) { 815 | options.url = url; 816 | } else { 817 | options.content = []; 818 | } 819 | 820 | return this.get('type').create(options); 821 | }, 822 | 823 | setValue: function(instance, value) { 824 | throw('you can not set a remote has many association'); 825 | } 826 | }); 827 | Ember.Resource.HasManyRemoteSchemaItem.reopenClass({ 828 | create: function(name, schema) { 829 | var definition = schema[name]; 830 | 831 | var instance = this._super.apply(this, arguments); 832 | 833 | if (Ember.typeOf(definition.url) === 'function') { 834 | instance.url = definition.url; 835 | } else { 836 | instance.url = function(obj) { 837 | var id = obj.get('id'); 838 | if (id) { 839 | return definition.url.fmt(id); 840 | } 841 | }; 842 | } 843 | 844 | return instance; 845 | } 846 | }); 847 | 848 | Ember.Resource.HasManyNestedSchemaItem = Ember.Resource.HasManySchemaItem.extend({ 849 | fetchable: true, 850 | getValue: function(instance) { 851 | var data = this.data(instance); 852 | if (!data) return; 853 | data = Ember.getPath(data, this.get('path')); 854 | if (data === undefined || data === null) return data; 855 | data = Ember.copy(data); 856 | 857 | var options = { 858 | type: this.get('itemType'), 859 | content: data 860 | }; 861 | 862 | if (this.get('parse')) options.parse = this.get('parse'); 863 | 864 | return this.get('type').create(options); 865 | }, 866 | 867 | setValue: function(instance, value) { 868 | }, 869 | 870 | toJSON: function(instance) { 871 | var value = Ember.get(instance, this.name); 872 | return value ? value.toJSON() : value; 873 | } 874 | }); 875 | Ember.Resource.HasManyNestedSchemaItem.reopenClass({ 876 | create: function(name, schema) { 877 | var definition = schema[name]; 878 | 879 | var instance = this._super.apply(this, arguments); 880 | instance.set('path', definition.path || name); 881 | 882 | return instance; 883 | } 884 | }); 885 | 886 | Ember.Resource.HasManyInArraySchemaItem = Ember.Resource.HasManySchemaItem.extend({ 887 | fetchable: true, 888 | getValue: function(instance) { 889 | var data = this.data(instance); 890 | if (!data) return; 891 | data = Ember.getPath(data, this.get('path')); 892 | if (data === undefined || data === null) return data; 893 | 894 | 895 | return this.get('type').create({ 896 | type: this.get('itemType'), 897 | content: data.map(function(id) { return {id: id}; }) 898 | }); 899 | }, 900 | 901 | setValue: function(instance, value) { 902 | }, 903 | 904 | toJSON: function(instance) { 905 | var value = Ember.get(instance, this.name); 906 | return value ? value.mapProperty('id') : value; 907 | } 908 | }); 909 | Ember.Resource.HasManyInArraySchemaItem.reopenClass({ 910 | create: function(name, schema) { 911 | var definition = schema[name]; 912 | 913 | var instance = this._super.apply(this, arguments); 914 | instance.set('path', definition.path || name + '_ids'); 915 | 916 | return instance; 917 | } 918 | }); 919 | 920 | 921 | // Gives custom error handlers access to the resource object. 922 | // 1. `this` will refer to the Ember.Resource object. 923 | // 2. `resource` will be passed as the last argument 924 | // 925 | // function errorHandler() { 926 | // this; // the Ember.Resource 927 | // } 928 | // 929 | // function errorHandler(jqXHR, textStatus, errorThrown, resource) { 930 | // resource; // another way to reference the resource object 931 | // } 932 | // 933 | var errorHandlerWithContext = function(errorHandler, context) { 934 | return function() { 935 | var args = Array.prototype.slice.call(arguments, 0); 936 | args.push(context); 937 | errorHandler.apply(context, args); 938 | }; 939 | }; 940 | 941 | Ember.Resource.ajax = function(options) { 942 | options.dataType = options.dataType || 'json'; 943 | options.type = options.type || 'GET'; 944 | 945 | if(options.error) { 946 | options.error = errorHandlerWithContext(options.error, options); 947 | } else if(Ember.Resource.errorHandler) { 948 | options.error = errorHandlerWithContext(Ember.Resource.errorHandler, options); 949 | } 950 | 951 | return $.ajax(options); 952 | }; 953 | 954 | Ember.Resource.Lifecycle = { 955 | INITIALIZING: 0, 956 | UNFETCHED: 10, 957 | EXPIRING: 20, 958 | EXPIRED: 30, 959 | FETCHING: 40, 960 | FETCHED: 50, 961 | SAVING: 60, 962 | DESTROYING: 70, 963 | DESTROYED: 80, 964 | 965 | clock: Ember.Object.create({ 966 | now: new Date(), 967 | 968 | tick: function() { 969 | Ember.Resource.Lifecycle.clock.set('now', new Date()); 970 | }, 971 | 972 | start: function() { 973 | this.stop(); 974 | Ember.Resource.Lifecycle.clock.set('timer', setInterval(Ember.Resource.Lifecycle.clock.tick, 10000)); 975 | }, 976 | 977 | stop: function() { 978 | var timer = Ember.Resource.Lifecycle.clock.get('timer'); 979 | if (timer) { 980 | clearInterval(timer); 981 | } 982 | } 983 | }), 984 | 985 | classMixin: Ember.Mixin.create({ 986 | create: function(options, data) { 987 | options = options || {}; 988 | options.resourceState = Ember.Resource.Lifecycle.INITIALIZING; 989 | 990 | var instance = this._super.apply(this, arguments); 991 | 992 | if (Ember.get(instance, 'resourceState') === Ember.Resource.Lifecycle.INITIALIZING) { 993 | Ember.set(instance, 'resourceState', Ember.Resource.Lifecycle.UNFETCHED); 994 | } 995 | 996 | return instance; 997 | } 998 | }), 999 | 1000 | prototypeMixin: Ember.Mixin.create({ 1001 | expireIn: 60 * 5, 1002 | resourceState: 0, 1003 | autoFetch: true, 1004 | 1005 | init: function() { 1006 | this._super.apply(this, arguments); 1007 | 1008 | var self = this; 1009 | 1010 | if(!Ember.Resource.SUPPORT_AUTOFETCH) { 1011 | this.set('autoFetch', false); 1012 | } 1013 | 1014 | var updateExpiry = function() { 1015 | var expireAt = new Date(); 1016 | expireAt.setSeconds(expireAt.getSeconds() + Ember.get(self, 'expireIn')); 1017 | Ember.set(self, 'expireAt', expireAt); 1018 | }; 1019 | 1020 | Ember.addListener(this, 'willFetch', this, function() { 1021 | Ember.set(self, 'resourceState', Ember.Resource.Lifecycle.FETCHING); 1022 | updateExpiry(); 1023 | }); 1024 | 1025 | Ember.addListener(this, 'didFetch', this, function() { 1026 | Ember.set(self, 'resourceState', Ember.Resource.Lifecycle.FETCHED); 1027 | updateExpiry(); 1028 | }); 1029 | 1030 | Ember.addListener(this, 'didFail', this, function() { 1031 | Ember.set(self, 'resourceState', Ember.Resource.Lifecycle.UNFETCHED); 1032 | updateExpiry(); 1033 | }); 1034 | 1035 | var resourceStateBeforeSave; 1036 | Ember.addListener(this, 'willSave', this, function() { 1037 | resourceStateBeforeSave = Ember.get(self, 'resourceState'); 1038 | Ember.set(self, 'resourceState', Ember.Resource.Lifecycle.SAVING); 1039 | }); 1040 | 1041 | Ember.addListener(this, 'didSave', this, function() { 1042 | Ember.set(self, 'resourceState', resourceStateBeforeSave || Ember.Resource.Lifecycle.UNFETCHED); 1043 | }); 1044 | }, 1045 | 1046 | isFetchable: Ember.computed('resourceState', function() { 1047 | var state = Ember.get(this, 'resourceState'); 1048 | return state == Ember.Resource.Lifecycle.UNFETCHED || state === Ember.Resource.Lifecycle.EXPIRED; 1049 | }).cacheable(), 1050 | 1051 | isAutoFetchable: Ember.computed('isFetchable', 'autoFetch', function() { 1052 | return this.get('isFetchable') && this.get('autoFetch'); 1053 | }).cacheable(), 1054 | 1055 | isInitializing: Ember.computed('resourceState', function() { 1056 | return (Ember.get(this, 'resourceState') || Ember.Resource.Lifecycle.INITIALIZING) === Ember.Resource.Lifecycle.INITIALIZING; 1057 | }).cacheable(), 1058 | 1059 | isFetching: Ember.computed('resourceState', function() { 1060 | return (Ember.get(this, 'resourceState')) === Ember.Resource.Lifecycle.FETCHING; 1061 | }).cacheable(), 1062 | 1063 | isFetched: Ember.computed('resourceState', function() { 1064 | return (Ember.get(this, 'resourceState')) === Ember.Resource.Lifecycle.FETCHED; 1065 | }).cacheable(), 1066 | 1067 | isSavable: Ember.computed('resourceState', function() { 1068 | var state = Ember.get(this, 'resourceState'); 1069 | var unsavableState = [ 1070 | Ember.Resource.Lifecycle.INITIALIZING, 1071 | Ember.Resource.Lifecycle.FETCHING, 1072 | Ember.Resource.Lifecycle.SAVING, 1073 | Ember.Resource.Lifecycle.DESTROYING 1074 | ]; 1075 | 1076 | return state && !unsavableState.contains(state); 1077 | }).cacheable(), 1078 | 1079 | isSaving: Ember.computed('resourceState', function() { 1080 | return (Ember.get(this, 'resourceState')) === Ember.Resource.Lifecycle.SAVING; 1081 | }).cacheable(), 1082 | 1083 | scheduleFetch: function() { 1084 | if (Ember.get(this, 'isAutoFetchable')) { 1085 | Ember.run.next(this, this.fetch); 1086 | } 1087 | }, 1088 | 1089 | expire: function() { 1090 | Ember.run.next(this, function() { 1091 | Ember.set(this, 'expireAt', new Date()); 1092 | Ember.Resource.Lifecycle.clock.tick(); 1093 | }); 1094 | }, 1095 | 1096 | updateIsExpired: Ember.observer(function() { 1097 | var isExpired = Ember.get(this, 'resourceState') === Ember.Resource.Lifecycle.EXPIRED; 1098 | if (isExpired) return true; 1099 | 1100 | var expireAt = Ember.get(this, 'expireAt'); 1101 | if (expireAt) { 1102 | var now = Ember.Resource.Lifecycle.clock.get('now'); 1103 | isExpired = expireAt.getTime() <= now.getTime(); 1104 | } 1105 | 1106 | var oldIsExpired = Ember.get(this, 'isExpired'); 1107 | 1108 | if (( isExpired && !oldIsExpired ) || 1109 | ( (isExpired === false) && oldIsExpired)) { 1110 | Ember.set(this, 'isExpired', isExpired); 1111 | } 1112 | }, 'Ember.Resource.Lifecycle.clock.now', 'expireAt', 'resourceState'), 1113 | 1114 | isExpired: Ember.computed(function(name, value) { 1115 | if (value) { 1116 | Ember.set(this, 'resourceState', Ember.Resource.Lifecycle.EXPIRED); 1117 | } 1118 | return value; 1119 | }).cacheable() 1120 | }) 1121 | }; 1122 | Ember.Resource.Lifecycle.clock.start(); 1123 | 1124 | Ember.Resource.reopen({ 1125 | isEmberResource: true, 1126 | 1127 | updateWithApiData: function(json) { 1128 | var data = Ember.get(this, 'data'); 1129 | Ember.beginPropertyChanges(data); 1130 | Ember.Resource.deepMerge(data, this.constructor.parse(json)); 1131 | Ember.endPropertyChanges(data); 1132 | }, 1133 | 1134 | willFetch: function() {}, 1135 | didFetch: function() {}, 1136 | willSave: function() {}, 1137 | didSave: function() {}, 1138 | didFail: function() {}, 1139 | 1140 | fetched: function() { 1141 | if(!this._fetchDfd) { 1142 | this._fetchDfd = $.Deferred(); 1143 | } 1144 | return this._fetchDfd; 1145 | }, 1146 | 1147 | fetch: function(ajaxOptions) { 1148 | var sideloads; 1149 | if (!Ember.get(this, 'isFetchable')) return $.when(); 1150 | 1151 | var url = this.resourceURL(); 1152 | 1153 | if (!url) return; 1154 | 1155 | var self = this; 1156 | 1157 | if (this.deferedFetch && !Ember.get(this, 'isExpired')) return this.deferedFetch; 1158 | 1159 | self.willFetch.call(self); 1160 | Ember.sendEvent(self, 'willFetch'); 1161 | 1162 | ajaxOptions = $.extend({}, ajaxOptions, { 1163 | url: url, 1164 | resource: this, 1165 | operation: 'read' 1166 | }); 1167 | 1168 | sideloads = this.constructor.sideloads; 1169 | 1170 | if(sideloads && sideloads.length !== 0) { 1171 | ajaxOptions.data = {include: sideloads.join(",")}; 1172 | } 1173 | 1174 | this.deferedFetch = Ember.Resource.ajax(ajaxOptions).done(function(json) { 1175 | self.updateWithApiData(json); 1176 | }); 1177 | 1178 | this.deferedFetch.fail(function() { 1179 | self.didFail.call(self); 1180 | Ember.sendEvent(self, 'didFail'); 1181 | self.fetched().reject(); 1182 | }); 1183 | 1184 | this.deferedFetch.done(function() { 1185 | self.didFetch.call(self); 1186 | Ember.sendEvent(self, 'didFetch'); 1187 | self.fetched().resolve(); 1188 | }); 1189 | 1190 | this.deferedFetch.always(function() { 1191 | self.deferedFetch = null; 1192 | }); 1193 | 1194 | return this.deferedFetch; 1195 | }, 1196 | 1197 | resourceURL: function() { 1198 | return this.constructor.resourceURL(this); 1199 | }, 1200 | 1201 | // Turn this resource into a JSON object to be saved via AJAX. Override 1202 | // this method to produce different syncing behavior. 1203 | toJSON: function() { 1204 | var json = {}; 1205 | var schemaItem, path, value; 1206 | for (var name in this.constructor.schema) { 1207 | if (this.constructor.schema.hasOwnProperty(name)) { 1208 | schemaItem = this.constructor.schema[name]; 1209 | if (schemaItem instanceof Ember.Resource.AbstractSchemaItem) { 1210 | path = schemaItem.get('path'); 1211 | value = schemaItem.toJSON(this); 1212 | if (value !== undefined) { 1213 | Ember.Resource.deepSet(json, path, value); 1214 | } 1215 | } 1216 | } 1217 | } 1218 | 1219 | return json; 1220 | }, 1221 | 1222 | isNew: Ember.computed('id', function() { 1223 | return !Ember.get(this, 'id'); 1224 | }).cacheable(), 1225 | 1226 | save: function(options) { 1227 | options = options || {}; 1228 | if (!Ember.get(this, 'isSavable')) return false; 1229 | 1230 | var ajaxOptions = { 1231 | contentType: 'application/json', 1232 | data: JSON.stringify(this.toJSON()), 1233 | resource: this 1234 | }; 1235 | 1236 | if (Ember.get(this, 'isNew')) { 1237 | ajaxOptions.type = 'POST'; 1238 | ajaxOptions.url = this.constructor.resourceURL(); 1239 | ajaxOptions.operation = 'create'; 1240 | } else { 1241 | ajaxOptions.type = 'PUT'; 1242 | ajaxOptions.url = this.resourceURL(); 1243 | ajaxOptions.operation = 'update'; 1244 | } 1245 | 1246 | var self = this; 1247 | 1248 | self.willSave.call(self); 1249 | Ember.sendEvent(self, 'willSave'); 1250 | 1251 | var deferedSave = Ember.Resource.ajax(ajaxOptions); 1252 | 1253 | deferedSave.done(function(data, status, response) { 1254 | var location = response.getResponseHeader('Location'); 1255 | if (location) { 1256 | var id = self.constructor.idFromURL(location); 1257 | if (id) { 1258 | Ember.set(self, 'id', id); 1259 | } 1260 | } 1261 | 1262 | if (options.update !== false && Ember.typeOf(data) === 'object') { 1263 | self.updateWithApiData(data); 1264 | } 1265 | }); 1266 | 1267 | deferedSave.always(function() { 1268 | self.didSave.call(self); 1269 | Ember.sendEvent(self, 'didSave'); 1270 | }); 1271 | 1272 | return deferedSave; 1273 | }, 1274 | 1275 | destroy: function() { 1276 | if(this.get('id')) { 1277 | this.constructor.identityMap.remove(this.get('id')); 1278 | } 1279 | this._super(); 1280 | }, 1281 | 1282 | destroyResource: function() { 1283 | var previousState = Ember.get(this, 'resourceState'), self = this; 1284 | Ember.set(this, 'resourceState', Ember.Resource.Lifecycle.DESTROYING); 1285 | return Ember.Resource.ajax({ 1286 | type: 'DELETE', 1287 | operation: 'destroy', 1288 | url: this.resourceURL(), 1289 | resource: this 1290 | }).done(function() { 1291 | Ember.set(self, 'resourceState', Ember.Resource.Lifecycle.DESTROYED); 1292 | self.destroy(); 1293 | }).fail(function() { 1294 | Ember.set(self, 'resourceState', previousState); 1295 | }); 1296 | } 1297 | }, Ember.Resource.Lifecycle.prototypeMixin); 1298 | 1299 | expandSchema = function(schema) { 1300 | for (var name in schema) { 1301 | if (schema.hasOwnProperty(name)) { 1302 | schema[name] = Ember.Resource.SchemaItem.create(name, schema); 1303 | } 1304 | } 1305 | 1306 | return schema; 1307 | }; 1308 | 1309 | mergeSchemas = function(childSchema, parentSchema) { 1310 | var schema = Ember.copy(parentSchema || {}); 1311 | 1312 | for (var name in childSchema) { 1313 | if (childSchema.hasOwnProperty(name)) { 1314 | if (schema.hasOwnProperty(name)) { 1315 | throw("Schema item '" + name + "' is already defined"); 1316 | } 1317 | 1318 | schema[name] = childSchema[name]; 1319 | } 1320 | } 1321 | 1322 | return schema; 1323 | }; 1324 | 1325 | createSchemaProperties = function(schema) { 1326 | var properties = {}, schemaItem; 1327 | 1328 | for (var propertyName in schema) { 1329 | if (schema.hasOwnProperty(propertyName)) { 1330 | properties[propertyName] = schema[propertyName].property(); 1331 | } 1332 | } 1333 | 1334 | return properties; 1335 | }; 1336 | 1337 | Ember.Resource.reopenClass({ 1338 | isEmberResource: true, 1339 | schema: {}, 1340 | 1341 | baseClass: function() { 1342 | if (this === Ember.Resource) { 1343 | return null; 1344 | } else { 1345 | return this.baseResourceClass || this; 1346 | } 1347 | }, 1348 | 1349 | subclassFor: function(options, data) { 1350 | return this; 1351 | }, 1352 | 1353 | // Create an instance of this resource. If `options` includes an 1354 | // `id`, first check the identity map and return the existing resource 1355 | // with that ID if found. 1356 | create: function(options, data) { 1357 | data = data || {}; 1358 | options = options || {}; 1359 | 1360 | var klass = this.subclassFor(options, data), idToRestore = options.id; 1361 | 1362 | if (klass === this) { 1363 | var instance; 1364 | this.identityMap = this.identityMap || new Ember.Resource.IdentityMap(this.identityMapLimit); 1365 | 1366 | var id = data.id || options.id; 1367 | if (id && !options.skipIdentityMap) { 1368 | id = id.toString(); 1369 | instance = this.identityMap.get(id); 1370 | 1371 | if (!instance) { 1372 | instance = this._super.call(this, { data: data }); 1373 | this.identityMap.put(id, instance); 1374 | } else { 1375 | instance.updateWithApiData(data); 1376 | // ignore incoming resourceState and id arguments 1377 | delete options.resourceState; 1378 | delete options.id; 1379 | } 1380 | } else { 1381 | instance = this._super.call(this, { data: data }); 1382 | } 1383 | 1384 | delete options.data; 1385 | 1386 | Ember.beginPropertyChanges(instance); 1387 | var mixin = {}; 1388 | var hasMixin = false; 1389 | for (var name in options) { 1390 | if (options.hasOwnProperty(name)) { 1391 | if (this.schema[name]) { 1392 | instance.set(name, options[name]); 1393 | } else { 1394 | mixin[name] = options[name]; 1395 | hasMixin = true; 1396 | } 1397 | } 1398 | } 1399 | if (hasMixin) { 1400 | instance.reopen(mixin); 1401 | } 1402 | Ember.endPropertyChanges(instance); 1403 | 1404 | options.id = idToRestore; 1405 | return instance; 1406 | } else { 1407 | return klass.create(options, data); 1408 | } 1409 | }, 1410 | 1411 | // Parse JSON -- likely returned from an AJAX call -- into the 1412 | // properties for an instance of this resource. Override this method 1413 | // to produce different parsing behavior. 1414 | parse: function(json) { 1415 | return json; 1416 | }, 1417 | 1418 | // Define a resource class. 1419 | // 1420 | // Parameters: 1421 | // 1422 | // * `schema` -- the properties schema for the resource class 1423 | // * `url` -- either a function that returns the URL for syncing 1424 | // resources or a string. If the latter, a string of the form 1425 | // "/widgets" is turned into a function that returns "/widgets" if 1426 | // the Widget's ID is not present and "/widgets/{id}" if it is. 1427 | // * `parse` -- the function used to parse JSON returned from AJAX 1428 | // calls into the resource properties. By default, simply returns 1429 | // the JSON. 1430 | define: function(options) { 1431 | options = options || {}; 1432 | var schema = expandSchema(options.schema); 1433 | schema = mergeSchemas(schema, this.schema); 1434 | 1435 | var klass = this.extend(createSchemaProperties(schema), Ember.Resource.RemoteExpiry); 1436 | 1437 | var classOptions = { 1438 | schema: schema 1439 | }; 1440 | 1441 | if (this !== Ember.Resource) { 1442 | classOptions.baseResourceClass = this.baseClass() || this; 1443 | } 1444 | 1445 | if (options.url) { 1446 | classOptions.url = options.url; 1447 | } 1448 | 1449 | if (options.parse) { 1450 | classOptions.parse = options.parse; 1451 | } 1452 | 1453 | if (options.identityMapLimit) { 1454 | classOptions.identityMapLimit = options.identityMapLimit; 1455 | } 1456 | 1457 | if(options.sideloads) { 1458 | classOptions.sideloads = options.sideloads; 1459 | } 1460 | 1461 | klass.reopenClass(classOptions); 1462 | 1463 | return klass; 1464 | }, 1465 | 1466 | resourceURL: function(instance) { 1467 | if (Ember.typeOf(this.url) == 'function') { 1468 | return this.url(instance); 1469 | } else if (this.url) { 1470 | if (instance) { 1471 | var id = Ember.get(instance, 'id'); 1472 | if(!id) { 1473 | return this.url; 1474 | } 1475 | 1476 | if (id && (Ember.typeOf(id) !== 'number' || id > 0)) { 1477 | return this.url + '/' + id; 1478 | } 1479 | } else { 1480 | return this.url; 1481 | } 1482 | } 1483 | }, 1484 | 1485 | idFromURL: function(url) { 1486 | var regex; 1487 | if (!this.schema.id) return; 1488 | 1489 | if (this.schema.id.get('type') === Number) { 1490 | regex = /\/(\d+)(\.\w+)?$/; 1491 | } else { 1492 | regex = /\/([^\/\.]+)(\.\w+)?$/; 1493 | } 1494 | 1495 | var match = (url || '').match(regex); 1496 | if (match) { 1497 | return match[1]; 1498 | } 1499 | } 1500 | }, Ember.Resource.Lifecycle.classMixin); 1501 | 1502 | Ember.ResourceCollection = Ember.ArrayProxy.extend(Ember.Resource.RemoteExpiry, { 1503 | isEmberResourceCollection: true, 1504 | type: Ember.required(), 1505 | 1506 | fetched: function() { 1507 | if(!this._fetchDfd) { 1508 | this._fetchDfd = $.Deferred(); 1509 | } 1510 | return this._fetchDfd; 1511 | }, 1512 | 1513 | fetch: function(ajaxOptions) { 1514 | if (!Ember.get(this, 'isFetchable') || Ember.get(this, 'prePopulated')) return $.when(); 1515 | 1516 | var self = this; 1517 | 1518 | if (this.deferedFetch && !Ember.get(this, 'isExpired')) return this.deferedFetch; 1519 | 1520 | Ember.sendEvent(self, 'willFetch'); 1521 | 1522 | this.deferedFetch = this._fetch(function(json) { 1523 | Ember.set(self, 'content', self.parse(json)); 1524 | }, ajaxOptions); 1525 | 1526 | this.deferedFetch.always(function() { 1527 | Ember.sendEvent(self, 'didFetch'); 1528 | self.fetched().resolve(); 1529 | self.deferredFetch = null; 1530 | }); 1531 | return this.deferedFetch; 1532 | }, 1533 | _resolveType: function() { 1534 | if (isString(this.type)) { 1535 | var type = Ember.getPath(this.type); 1536 | if (type) this.type = type; 1537 | } 1538 | }, 1539 | _fetch: function(callback, ajaxOptions) { 1540 | this._resolveType(); 1541 | ajaxOptions = $.extend({}, ajaxOptions, { 1542 | url: this.resolveUrl(), 1543 | resource: this, 1544 | operation: 'read', 1545 | success: callback 1546 | }); 1547 | return Ember.Resource.ajax(ajaxOptions); 1548 | }, 1549 | resolveUrl: function() { 1550 | return this.get('url') || this.type.resourceURL(); 1551 | }, 1552 | instantiateItems: function(items) { 1553 | this._resolveType(); 1554 | return items.map(function(item) { 1555 | if (item instanceof this.type) { 1556 | return item; 1557 | } else { 1558 | return this.type.create({}, item); 1559 | } 1560 | }, this); 1561 | }, 1562 | parse: function(json) { 1563 | this._resolveType(); 1564 | if (Ember.typeOf(this.type.parse) == 'function') { 1565 | return json.map(this.type.parse); 1566 | } 1567 | else { 1568 | return json; 1569 | } 1570 | }, 1571 | 1572 | length: Ember.computed('content.length', 'resourceState', 'isExpired', function() { 1573 | var content = Ember.get(this, 'content'); 1574 | var length = content ? Ember.get(content, 'length') : 0; 1575 | if (length === 0 || Ember.get(this, 'isExpired')) this.scheduleFetch(); 1576 | return length; 1577 | }).cacheable(), 1578 | 1579 | content: Ember.computed(function(name, value) { 1580 | if (arguments.length === 2) { // setter 1581 | return this.instantiateItems(value); 1582 | } 1583 | }).cacheable(), 1584 | 1585 | autoFetchOnExpiry: Ember.observer(function() { 1586 | if (Ember.get(this, 'isAutoFetchable') && Ember.get(this, 'isExpired') && Ember.get(this, 'hasArrayObservers')) { 1587 | this.fetch(); 1588 | } 1589 | }, 'isExpired', 'hasArrayObservers'), 1590 | 1591 | toJSON: function() { 1592 | return this.map(function(item) { 1593 | return item.toJSON(); 1594 | }); 1595 | } 1596 | }, Ember.Resource.Lifecycle.prototypeMixin); 1597 | 1598 | Ember.ResourceCollection.reopenClass({ 1599 | isEmberResourceCollection: true, 1600 | identityMapLimit: Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT * 5, 1601 | create: function(options) { 1602 | options = options || {}; 1603 | var content = options.content; 1604 | delete options.content; 1605 | 1606 | options.prePopulated = !! content; 1607 | 1608 | var instance; 1609 | 1610 | if (!options.prePopulated && options.url) { 1611 | this.identityMap = this.identityMap || new Ember.Resource.IdentityMap(this.identityMapLimit); 1612 | var identity = [options.type, options.url]; 1613 | instance = this.identityMap.get(identity) || this._super.call(this, options); 1614 | this.identityMap.put(identity, instance); 1615 | } 1616 | 1617 | if (!instance) { 1618 | instance = this._super.call(this, options); 1619 | 1620 | if (content) { 1621 | Ember.set(instance, 'content', instance.parse(content)); 1622 | } 1623 | } 1624 | 1625 | return instance; 1626 | } 1627 | }, Ember.Resource.Lifecycle.classMixin); 1628 | }(this)); 1629 | -------------------------------------------------------------------------------- /jshint.yml: -------------------------------------------------------------------------------- 1 | # ------------ rake task options ------------ 2 | 3 | # JS files to check by default, if no parameters are passed to rake jshint 4 | # (you may want to limit this only to your own scripts and exclude any external scripts and frameworks) 5 | 6 | # this can be overridden by adding 'paths' and 'exclude_paths' parameter to rake command: 7 | # rake jshint paths=path1,path2,... exclude_paths=library1,library2,... 8 | 9 | paths: 10 | - spec/javascripts/**/*.js 11 | - src/**/*.js 12 | 13 | exclude_paths: 14 | 15 | 16 | # ------------ jshint options ------------ 17 | # visit http://jshint.com/ for complete documentation 18 | 19 | # "enforce" type options (true means potentially more warnings) 20 | 21 | adsafe: false # true if ADsafe rules should be enforced. See http://www.ADsafe.org/ 22 | bitwise: true # true if bitwise operators should not be allowed 23 | newcap: false # true if Initial Caps must be used with constructor functions 24 | eqeqeq: false # true if === should be required (for ALL equality comparisons) 25 | immed: false # true if immediate function invocations must be wrapped in parens 26 | nomen: false # true if initial or trailing underscore in identifiers should be forbidden 27 | onevar: false # true if only one var statement per function should be allowed 28 | plusplus: false # true if ++ and -- should not be allowed 29 | regexp: false # true if . and [^...] should not be allowed in RegExp literals 30 | safe: false # true if the safe subset rules are enforced (used by ADsafe) 31 | strict: false # true if the ES5 "use strict"; pragma is required 32 | undef: true # true if variables must be declared before used 33 | white: false # true if strict whitespace rules apply (see also 'indent' option) 34 | 35 | # "allow" type options (false means potentially more warnings) 36 | 37 | cap: false # true if upper case HTML should be allowed 38 | css: false # true if CSS workarounds should be tolerated 39 | debug: false # true if debugger statements should be allowed (set to false before going into production) 40 | es5: false # true if ECMAScript 5 syntax should be allowed 41 | evil: false # true if eval should be allowed 42 | forin: false # true if unfiltered 'for in' statements should be allowed 43 | fragment: false # true if HTML fragments should be allowed 44 | laxbreak: false # true if statement breaks should not be checked 45 | on: false # true if HTML event handlers (e.g. onclick="...") should be allowed 46 | sub: false # true if subscript notation may be used for expressions better expressed in dot notation 47 | 48 | # other options 49 | 50 | maxlen: 160 # Maximum line length 51 | indent: 2 # Number of spaces that should be used for indentation - used only if 'white' option is set 52 | maxerr: 50 # The maximum number of warnings reported (per file) 53 | passfail: false # true if the scan should stop on first error (per file) 54 | # following are relevant only if undef = true 55 | predef: '$,Ember,SC,jasmine,describe,beforeEach,it,afterEach,expect,spyOn,runs,waits,waitsFor,sinon' # Names of predefined global variables - comma-separated string or a YAML array 56 | browser: true # true if the standard browser globals should be predefined 57 | rhino: false # true if the Rhino environment globals should be predefined 58 | windows: false # true if Windows-specific globals should be predefined 59 | widget: false # true if the Yahoo Widgets globals should be predefined 60 | devel: false # true if functions like alert, confirm, console, prompt etc. are predefined 61 | 62 | # jshint options 63 | loopfunc: true # true if functions should be allowed to be defined within loops 64 | asi: true # true if automatic semicolon insertion should be tolerated 65 | boss: true # true if advanced usage of assignments and == should be allowed 66 | couch: true # true if CouchDB globals should be predefined 67 | curly: false # true if curly braces around blocks should be required (even in if/for/while) 68 | noarg: true # true if arguments.caller and arguments.callee should be disallowed 69 | node: true # true if the Node.js environment globals should be predefined 70 | noempty: true # true if empty blocks should be disallowed 71 | nonew: true # true if using `new` for side-effects should be disallowed 72 | 73 | 74 | # ------------ jshint_on_rails custom lint options (switch to true to disable some annoying warnings) ------------ 75 | 76 | # ignores "missing semicolon" warning at the end of a function; this lets you write one-liners 77 | # like: x.map(function(i) { return i + 1 }); without having to put a second semicolon inside the function 78 | lastsemic: false 79 | 80 | # allows you to use the 'new' expression as a statement (without assignment) 81 | # so you can call e.g. new Ajax.Request(...), new Effect.Highlight(...) without assigning to a dummy variable 82 | newstat: false 83 | 84 | # ignores the "Expected an assignment or function call and instead saw an expression" warning, 85 | # if the expression contains a proper statement and makes sense; this lets you write things like: 86 | # element && element.show(); 87 | # valid || other || lastChance || alert('OMG!'); 88 | # selected ? show() : hide(); 89 | # although these will still cause a warning: 90 | # element && link; 91 | # selected ? 5 : 10; 92 | statinexp: false 93 | -------------------------------------------------------------------------------- /spec/javascripts/associationsSpec.js: -------------------------------------------------------------------------------- 1 | describe('associations', function() { 2 | var Address = Ember.Resource.define({ 3 | schema: { 4 | id: Number, 5 | street: String, 6 | zip: Number, 7 | city: String 8 | }, 9 | 10 | parse: function(json) { 11 | json.city = json.city || json.city_name; 12 | delete json.city_name; 13 | return json; 14 | } 15 | }); 16 | 17 | describe('has one embedded', function() { 18 | var data; 19 | 20 | beforeEach(function() { 21 | data = { 22 | name: 'Joe Doe', 23 | address: { 24 | street: '1 My Street', 25 | zip: 12345 26 | } 27 | }; 28 | }); 29 | 30 | it('should use embedded data', function() { 31 | var Person = Ember.Resource.define({ 32 | schema: { 33 | name: String, 34 | address: {type: Address, nested: true} 35 | } 36 | }); 37 | 38 | var instance = Person.create({}, data); 39 | var address = instance.get('address'); 40 | 41 | expect(address instanceof Address).toBe(true); 42 | expect(address.get('street')).toBe('1 My Street'); 43 | expect(address.get('zip')).toBe(12345); 44 | 45 | instance.set('address', Address.create({street: '2 Your Street'})); 46 | expect(instance.getPath('data.address.street')).toBe('2 Your Street'); 47 | expect(instance.getPath('data.address.zip')).toBeUndefined(); 48 | }); 49 | 50 | it('should support path overriding', function() { 51 | var Person = Ember.Resource.define({ 52 | schema: { 53 | name: String, 54 | address: {type: Address, nested: true, path: 'addresses.home'} 55 | } 56 | }); 57 | 58 | data.addresses = { home: data.address }; 59 | delete data.address; 60 | 61 | var instance = Person.create({}, data); 62 | var address = instance.get('address'); 63 | 64 | expect(address instanceof Address).toBe(true); 65 | expect(address.get('street')).toBe('1 My Street'); 66 | expect(address.get('zip')).toBe(12345); 67 | 68 | instance.set('address', Address.create({street: '2 Your Street'})); 69 | expect(instance.getPath('data.addresses.home.street')).toBe('2 Your Street'); 70 | expect(instance.getPath('data.addresses.home.zip')).toBeUndefined(); 71 | }); 72 | 73 | it('should have an id accessor', function() { 74 | var Person = Ember.Resource.define({ 75 | schema: { 76 | name: String, 77 | address: {type: Address, nested: true} 78 | } 79 | }); 80 | 81 | data.address.id = '1'; 82 | 83 | var instance = Person.create({}, data); 84 | data = instance.get('data'); 85 | var address = instance.get('address'); 86 | 87 | expect(instance.get('address_id')).toBe(1); 88 | 89 | instance.set('address_id', '2'); 90 | 91 | expect(instance.get('address_id')).toBe(2); 92 | expect(instance.get('address')).not.toBe(address); 93 | expect(instance.getPath('address.id')).toBe(2); 94 | }); 95 | }); 96 | 97 | describe('has many', function() { 98 | var Person; 99 | 100 | describe('with url', function() { 101 | 102 | beforeEach(function() { 103 | Person = Ember.Resource.define({ 104 | schema: { 105 | id: Number, 106 | name: String, 107 | home_addresses: { 108 | type: Ember.ResourceCollection, 109 | itemType: Address, 110 | url: '/people/%@/addresses' 111 | }, 112 | work_addresses: { 113 | type: Ember.ResourceCollection, 114 | itemType: Address, 115 | url: function(instance) { 116 | return '/people/' + instance.get('id') + '/addresses'; 117 | } 118 | } 119 | } 120 | }); 121 | }); 122 | 123 | it('should support url strings', function() { 124 | var person = Person.create({id: 1, name: 'Mick Staugaard'}); 125 | var homeAddresses = person.get('home_addresses'); 126 | 127 | expect(homeAddresses).toBeDefined(); 128 | expect(homeAddresses instanceof Ember.ResourceCollection).toBe(true); 129 | expect(homeAddresses.type).toBe(Address); 130 | expect(homeAddresses.url).toBe('/people/1/addresses'); 131 | }); 132 | 133 | it('should support url functions', function() { 134 | var person = Person.create({id: 1, name: 'Mick Staugaard'}); 135 | var workAddresses = person.get('work_addresses'); 136 | 137 | expect(workAddresses).toBeDefined(); 138 | expect(workAddresses instanceof Ember.ResourceCollection).toBe(true); 139 | expect(workAddresses.type).toBe(Address); 140 | expect(workAddresses.url).toBe('/people/1/addresses'); 141 | }); 142 | }); 143 | 144 | describe('nested', function() { 145 | beforeEach(function() { 146 | Person = Ember.Resource.define({ 147 | schema: { 148 | name: String, 149 | home_addresses: { 150 | type: Ember.ResourceCollection, 151 | itemType: Address, 152 | nested: true 153 | }, 154 | work_addresses: { 155 | type: Ember.ResourceCollection, 156 | itemType: Address, 157 | nested: true, 158 | path: 'office_addresses' 159 | } 160 | } 161 | }); 162 | }); 163 | 164 | it('should use the nested data', function() { 165 | var data = { 166 | name: 'Joe Doe', 167 | home_addresses: [ 168 | { 169 | street: '1 My Street', 170 | zip: 12345 171 | }, 172 | { 173 | street: '2 Your Street', 174 | zip: 23456 175 | } 176 | ] 177 | }; 178 | 179 | var person = Person.create({}, data); 180 | var homeAddresses = person.get('home_addresses'); 181 | 182 | expect(homeAddresses).toBeDefined(); 183 | expect(homeAddresses instanceof Ember.ResourceCollection).toBe(true); 184 | expect(homeAddresses.type).toBe(Address); 185 | expect(homeAddresses.get('length')).toBe(2); 186 | 187 | var address; 188 | for (var i=0; i < data.home_addresses.length; i++) { 189 | address = homeAddresses.objectAt(i); 190 | expect(address).toBeDefined(); 191 | expect(address instanceof Address).toBe(true); 192 | expect(address.get('street')).toBe(data.home_addresses[i].street); 193 | expect(address.get('zip')).toBe(data.home_addresses[i].zip); 194 | } 195 | 196 | address = homeAddresses.objectAt(0); 197 | 198 | address.set('street', '3 Other Street'); 199 | expect(address.get('street')).toBe('3 Other Street'); 200 | }); 201 | 202 | it("should use the class's parse method", function() { 203 | var data = { 204 | name: 'Joe Doe', 205 | home_addresses: [ 206 | { 207 | street: '1 My Street', 208 | zip: 12345, 209 | city_name: 'Anytown' 210 | } 211 | ] 212 | }; 213 | 214 | var person = Person.create({}, data), 215 | address = person.get('home_addresses').objectAt(0); 216 | 217 | expect(address).toBeTruthy(); 218 | expect(address.get('city')).toEqual('Anytown'); 219 | }); 220 | }); 221 | 222 | describe('in array', function() { 223 | beforeEach(function() { 224 | Person = Ember.Resource.define({ 225 | schema: { 226 | name: String, 227 | home_addresses: { 228 | type: Ember.ResourceCollection, 229 | itemType: Address, 230 | path: 'home_address_ids' 231 | } 232 | } 233 | }); 234 | }); 235 | 236 | it("should use the ids in the array", function() { 237 | var data = { 238 | name: 'Joe Doe', 239 | home_address_ids: [1, 2] 240 | }; 241 | 242 | var person = Person.create({}, data), 243 | addresses = person.get('home_addresses'); 244 | 245 | expect(addresses.get('length')).toBe(2); 246 | expect(addresses.objectAt(0).get('id')).toBe(1); 247 | expect(addresses.objectAt(1).get('id')).toBe(2); 248 | }); 249 | }); 250 | 251 | }); 252 | }); 253 | -------------------------------------------------------------------------------- /spec/javascripts/autoFetchingSpec.js: -------------------------------------------------------------------------------- 1 | describe('Auto fetching', function() { 2 | var Person, server; 3 | 4 | beforeEach(function() { 5 | Person = Ember.Resource.define({ 6 | url: '/people', 7 | schema: { 8 | id: Number, 9 | name: String 10 | } 11 | }); 12 | 13 | server = sinon.fakeServer.create(); 14 | Ember.Resource.Lifecycle.clock.tick(); 15 | }); 16 | 17 | afterEach(function() { 18 | server.restore(); 19 | }); 20 | 21 | describe('of models', function() { 22 | var person; 23 | 24 | beforeEach(function() { 25 | server.respondWith("GET", "/people/1", 26 | [200, { "Content-Type": "application/json" }, 27 | '{ "id": 1, "name": "Mick Staugaard" }']); 28 | person = Person.create({id: 1}); 29 | }); 30 | 31 | it('getting known attributes should not schedule a fetch', function() { 32 | spyOn(person, 'fetch'); 33 | runs(function() { 34 | expect(person.get('id')).toBe(1); 35 | }); 36 | 37 | waits(100); 38 | 39 | runs(function() { 40 | expect(person.fetch).not.toHaveBeenCalled(); 41 | }); 42 | }); 43 | 44 | it('getting known attributes that are not defined should schedule a fetch', function() { 45 | runs(function() { 46 | expect(person.get('name')).toBeUndefined(); 47 | }); 48 | 49 | waits(100); 50 | 51 | runs(function() { 52 | server.respond(); 53 | expect(person.get('name')).toBe('Mick Staugaard'); 54 | }); 55 | }); 56 | 57 | it('getting unknown attributes should not schedule a fetch', function() { 58 | spyOn(person, 'fetch'); 59 | runs(function() { 60 | expect(person.get('notInSchema')).toBeUndefined(); 61 | }); 62 | 63 | waits(100); 64 | 65 | runs(function() { 66 | expect(person.fetch).not.toHaveBeenCalled(); 67 | }); 68 | }); 69 | 70 | it('should not fetch when autoFetch is false', function() { 71 | spyOn(person, 'fetch'); 72 | person.set('autoFetch', false); 73 | 74 | runs(function() { 75 | expect(person.get('name')).toBeUndefined(); 76 | }); 77 | 78 | waits(100); 79 | 80 | runs(function() { 81 | expect(person.fetch).not.toHaveBeenCalled(); 82 | }); 83 | }); 84 | }); 85 | 86 | describe('of collections', function() { 87 | var people; 88 | 89 | beforeEach(function() { 90 | server.respondWith("GET", "/people", 91 | [200, { "Content-Type": "application/json" }, 92 | '[{ "id": 1, "name": "Mick Staugaard" }]']); 93 | people = Ember.ResourceCollection.create({type: Person}); 94 | server.respond(); 95 | }); 96 | 97 | it('should not fetch on creation', function() { 98 | var hasFetched = false; 99 | var TestCollection = Ember.ResourceCollection.extend({ 100 | fetch: function() { 101 | hasFetched = true; 102 | } 103 | }); 104 | 105 | runs(function() { 106 | people = TestCollection.create({type: Person}); 107 | }); 108 | 109 | waits(100); 110 | 111 | runs(function() { 112 | expect(hasFetched).toBe(false); 113 | }); 114 | }); 115 | 116 | describe('that are fetched', function() { 117 | beforeEach(function() { 118 | people.fetch(); 119 | server.respond(); 120 | 121 | waitsFor(function() { 122 | return people.get('length') > 0; 123 | }, 'collection never fetched', 1000); 124 | 125 | runs(function() { 126 | server.restore(); 127 | server = sinon.fakeServer.create(); 128 | server.respondWith("GET", "/people", 129 | [200, { "Content-Type": "application/json" }, 130 | '[{ "id": 1, "name": "Mick Staugaard" }, { "id": 2, "name": "Shajith Chacko" }]']); 131 | }); 132 | }); 133 | 134 | it('should not be refetched', function() { 135 | runs(function() { 136 | people.fetch(); 137 | server.respond(); 138 | }); 139 | 140 | waits(1000); 141 | 142 | runs(function() { 143 | expect(people.get('length')).toBe(1); 144 | }); 145 | }); 146 | 147 | it('should return a resolved deferred', function() { 148 | var result = people.fetch(); 149 | expect(result).not.toBeUndefined(); 150 | expect(result.state()).toBe('resolved'); 151 | }); 152 | 153 | describe('and expired', function() { 154 | beforeEach(function() { 155 | runs(function() { 156 | people.expire(); 157 | }); 158 | 159 | waitsFor(function() { 160 | return people.get('isExpired'); 161 | }, 'collection never expired', 1000); 162 | }); 163 | 164 | it('should refetch', function() { 165 | waitsFor(function() { 166 | server.respond(); 167 | return people.get('length') === 2; 168 | }, 'collection never refetched', 2000); 169 | }); 170 | 171 | describe('and autofetch turned off', function(){ 172 | beforeEach(function() { 173 | 174 | runs(function() { 175 | people.set('autoFetch', false); 176 | people.expire(); 177 | }); 178 | 179 | }); 180 | 181 | describe('and has Array Observers ', function(){ 182 | beforeEach(function() { 183 | people.addArrayObserver({}); 184 | 185 | runs(function() { 186 | spyOn(people, 'fetch'); 187 | }); 188 | 189 | waitsFor(function() { 190 | return people.get('isExpired'); 191 | }, 'collection never expired', 1000); 192 | }); 193 | 194 | it('should not refetch', function() { 195 | expect(people.fetch).not.toHaveBeenCalled(); 196 | }); 197 | 198 | }); 199 | 200 | describe('and has no Array Observers ', function(){ 201 | beforeEach(function() { 202 | 203 | runs(function() { 204 | spyOn(people, 'fetch'); 205 | }); 206 | 207 | waitsFor(function() { 208 | return people.get('isExpired'); 209 | }, 'collection never expired', 1000); 210 | }); 211 | 212 | it('should not refetch', function() { 213 | expect(people.fetch).not.toHaveBeenCalled(); 214 | }); 215 | 216 | }); 217 | 218 | }); 219 | 220 | describe('and autofetch turned on', function(){ 221 | beforeEach(function() { 222 | runs(function() { 223 | people.set('autoFetch', true); 224 | people.expire(); 225 | }); 226 | }); 227 | 228 | describe('and has Array Observers ', function(){ 229 | beforeEach(function() { 230 | people.addArrayObserver({}); 231 | 232 | runs(function() { 233 | spyOn(people, 'fetch'); 234 | }); 235 | 236 | waitsFor(function() { 237 | return people.get('isExpired'); 238 | }, 'collection never expired', 1000); 239 | }); 240 | 241 | it('should refetch', function() { 242 | expect(people.fetch).toHaveBeenCalled(); 243 | }); 244 | 245 | }); 246 | 247 | describe('and has no Array Observers ', function(){ 248 | beforeEach(function() { 249 | 250 | runs(function() { 251 | spyOn(people, 'fetch'); 252 | }); 253 | 254 | waitsFor(function() { 255 | return people.get('isExpired'); 256 | }, 'collection never expired', 1000); 257 | }); 258 | 259 | it('should not refetch', function() { 260 | expect(people.fetch).not.toHaveBeenCalled(); 261 | }); 262 | 263 | }); 264 | 265 | }); 266 | 267 | }); 268 | 269 | }); 270 | 271 | }); 272 | 273 | }); 274 | -------------------------------------------------------------------------------- /spec/javascripts/deepMergeSpec.js: -------------------------------------------------------------------------------- 1 | describe('deepMerge', function() { 2 | it('should add missing keys', function() { 3 | var obj = {}; 4 | Ember.Resource.deepMerge(obj, {a: 'foo'}); 5 | 6 | expect(obj.a).toBeDefined(); 7 | expect(obj.a).toBe('foo'); 8 | }); 9 | 10 | it('should override keys', function() { 11 | var obj = {a: 'foo'}; 12 | Ember.Resource.deepMerge(obj, {a: 'bar'}); 13 | 14 | expect(obj.a).toBeDefined(); 15 | expect(obj.a).toBe('bar'); 16 | }); 17 | 18 | it('should leave other keys', function() { 19 | var obj = {a: 'foo'}; 20 | Ember.Resource.deepMerge(obj, {b: 'bar'}); 21 | 22 | expect(obj.a).toBeDefined(); 23 | expect(obj.a).toBe('foo'); 24 | }); 25 | 26 | it('merge recursively', function() { 27 | var obj = {a: {b: 'foo'}}; 28 | Ember.Resource.deepMerge(obj, {a: {b: 'bar'}}); 29 | 30 | expect(obj.a.b).toBeDefined(); 31 | expect(obj.a.b).toBe('bar'); 32 | }); 33 | }); 34 | -------------------------------------------------------------------------------- /spec/javascripts/deepSetSpec.js: -------------------------------------------------------------------------------- 1 | describe('deepSet', function() { 2 | it('should set at the given path', function() { 3 | var obj = {}; 4 | Ember.Resource.deepSet(obj, 'a', 'foo'); 5 | 6 | expect(obj.a).toBeDefined(); 7 | expect(obj.a).toBe('foo'); 8 | }); 9 | 10 | it('should overwrite at the given path', function() { 11 | var obj = {a: 'foo'}; 12 | Ember.Resource.deepSet(obj, 'a', 'bar'); 13 | 14 | expect(obj.a).toBeDefined(); 15 | expect(obj.a).toBe('bar'); 16 | }); 17 | 18 | it('should create empty Object at missing nodes', function() { 19 | var obj = {}; 20 | Ember.Resource.deepSet(obj, 'a.b.c', 'foo'); 21 | 22 | expect(obj.a).toBeDefined(); 23 | expect(Ember.typeOf(obj.a)).toBe('object'); 24 | 25 | expect(obj.a.b).toBeDefined(); 26 | expect(Ember.typeOf(obj.a.b)).toBe('object'); 27 | 28 | expect(obj.a.b.c).toBeDefined(); 29 | expect(obj.a.b.c).toBe('foo'); 30 | }); 31 | 32 | }); 33 | -------------------------------------------------------------------------------- /spec/javascripts/destroySpec.js: -------------------------------------------------------------------------------- 1 | describe('Destroying a resource instance', function() { 2 | var Model, model, server; 3 | 4 | beforeEach(function() { 5 | Model = Ember.Resource.define({ 6 | schema: { 7 | id: Number, 8 | name: String, 9 | subject: String 10 | }, 11 | url: '/people' 12 | }); 13 | 14 | server = sinon.fakeServer.create(); 15 | }); 16 | 17 | afterEach(function() { 18 | server.restore(); 19 | Ember.Resource.errorHandler = null; 20 | }); 21 | 22 | describe('#destroy', function() { 23 | 24 | beforeEach(function() { 25 | model = Model.create({id: 1}); 26 | expect(Model.identityMap.get(1)).toEqual(model); 27 | model.destroy(); 28 | }); 29 | 30 | it('should remove the object from the identity map', function() { 31 | expect(Model.identityMap.get(1)).toBe(undefined); 32 | }); 33 | }); 34 | 35 | describe('handling errors on resource destruction', function() { 36 | beforeEach(function() { 37 | server.respondWith('DELETE', '/people', [422, {}, '[["foo", "bar"]]']); 38 | }); 39 | 40 | it('should pass a reference to the resource to the error handling function', function() { 41 | var spy = jasmine.createSpy(); 42 | 43 | Ember.Resource.errorHandler = function(a, b, c, fourthArgument) { 44 | spy(fourthArgument.resource, fourthArgument.operation); 45 | }; 46 | 47 | var resource = Model.create({ id: 1, name: 'f0o' }); 48 | resource.destroyResource(); 49 | server.respond(); 50 | 51 | expect(spy).toHaveBeenCalledWith(resource, "destroy"); 52 | }); 53 | }); 54 | }); 55 | -------------------------------------------------------------------------------- /spec/javascripts/fetchSpec.js: -------------------------------------------------------------------------------- 1 | describe('deferred fetch', function() { 2 | var Person, people, server; 3 | 4 | beforeEach(function() { 5 | Person = Ember.Resource.define({ 6 | url: '/people', 7 | schema: { 8 | id: Number, 9 | name: String 10 | } 11 | }).extend({ 12 | autoFetch: false 13 | }); 14 | 15 | server = sinon.fakeServer.create(); 16 | server.respondWith("GET", "/people/1", 17 | [200, { "Content-Type": "application/json" }, 18 | '{ "id": 1, "name": "Mick Staugaard" }']); 19 | 20 | 21 | }); 22 | 23 | afterEach(function() { 24 | server.restore(); 25 | }); 26 | 27 | describe("fetched() for resources", function() { 28 | it("should resolve when the fetch completes", function() { 29 | var handler = jasmine.createSpy(); 30 | 31 | var person = Person.create({id: 1}); 32 | person.fetched().done(function() { 33 | handler(); 34 | }); 35 | 36 | person.fetch(); 37 | server.respond(); 38 | 39 | expect(handler).toHaveBeenCalled(); 40 | }); 41 | }); 42 | 43 | describe('handling errors on fetch for resources', function() { 44 | beforeEach(function() { 45 | server.respondWith('GET', '/people/2', [422, {}, '[["foo", "bar"]]']); 46 | }); 47 | 48 | it('should not prevent subsequent fetches from happening', function() { 49 | var resource = Person.create({ id: 2 }); 50 | 51 | resource.fetch(); 52 | server.respond(); 53 | 54 | spyOn(resource, 'willFetch').andReturn($.when()); 55 | resource.fetch(); 56 | server.respond(); 57 | expect(resource.willFetch).toHaveBeenCalled(); 58 | }); 59 | 60 | it('should pass a reference to the resource to the error handling function', function() { 61 | var spy = jasmine.createSpy(); 62 | Ember.Resource.errorHandler = function(a, b, c, fourthArgument) { 63 | spy(fourthArgument.resource, fourthArgument.operation); 64 | }; 65 | 66 | var resource = Person.create({ id: 2 }); 67 | 68 | resource.fetch(); 69 | server.respond(); 70 | 71 | expect(spy).toHaveBeenCalledWith(resource, "read"); 72 | }); 73 | }); 74 | 75 | describe('handling errors on fetch for collections', function() { 76 | beforeEach(function() { 77 | people = Ember.ResourceCollection.create({type: Person}); 78 | server.respondWith('GET', '/people', [422, {}, '[["foo", "bar"]]']); 79 | }); 80 | 81 | it('should pass a reference to the resource to the error handling function', function() { 82 | var spy = jasmine.createSpy(); 83 | Ember.Resource.errorHandler = function(a, b, c, fourthArgument) { 84 | spy(fourthArgument.resource, fourthArgument.operation); 85 | }; 86 | 87 | people.fetch(); 88 | server.respond(); 89 | 90 | expect(spy).toHaveBeenCalledWith(people, "read"); 91 | }); 92 | }); 93 | 94 | describe("fetched() for resource collections", function() { 95 | beforeEach(function() { 96 | server.restore(); 97 | server.respondWith("GET", "/people", 98 | [200, { "Content-Type": "application/json" }, 99 | '[{ "id": 1, "name": "Mick Staugaard" }]']); 100 | people = Ember.ResourceCollection.create({type: Person}); 101 | 102 | }); 103 | 104 | afterEach(function() { 105 | window.stopHere = false; 106 | }); 107 | 108 | it("should resolve when the fetch completes", function() { 109 | 110 | var handler = jasmine.createSpy(); 111 | 112 | runs(function() { 113 | people.expire(); 114 | 115 | people.fetched().done(function() { 116 | handler(); 117 | }); 118 | 119 | people.fetch(); 120 | server.respond(); 121 | }); 122 | 123 | waits(1000); 124 | 125 | runs(function() { 126 | expect(handler).toHaveBeenCalled(); 127 | }); 128 | }); 129 | }); 130 | 131 | }); 132 | -------------------------------------------------------------------------------- /spec/javascripts/identityMapSpec.js: -------------------------------------------------------------------------------- 1 | describe('identity map', function() { 2 | var Address = Em.Resource.define({ 3 | identityMapLimit: 10 4 | }); 5 | 6 | it('should default to a limit of DEFAULT_IDENTITY_MAP_LIMIT', function() { 7 | var Foo = Em.Resource.define(); 8 | Foo.create({id: 1}); 9 | expect(Foo.identityMap.limit()).toBe(Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT); 10 | }); 11 | 12 | it('should return the same object when requested multiple times', function() { 13 | var address1 = Address.create({id: 1}); 14 | var address2 = Address.create({id: 1}); 15 | expect(address1).toBe(address2); 16 | }); 17 | 18 | it('should limit the number of objects retained', function() { 19 | var address; 20 | for(var i=1; i<=20; i++) { 21 | address = Address.create({id: i}); 22 | } 23 | 24 | expect(Address.identityMap.size()).toBe(10); 25 | }); 26 | 27 | it('should not clobber the resourceState of an already cached object', function() { 28 | var address = Address.create({id: 1}); 29 | address.set('resourceState', 50); 30 | address = Address.create({id: 1}); 31 | expect(address.get('resourceState')).toBe(50); 32 | }); 33 | 34 | describe("for resource collections", function() { 35 | var Addresses = Em.ResourceCollection.extend(); 36 | 37 | Addresses.reopenClass({ 38 | identityMapLimit: 10 39 | }); 40 | 41 | it('should default to a limit of 5x DEFAULT_IDENTITY_MAP_LIMIT', function() { 42 | var Foo = Em.ResourceCollection.extend(); 43 | Foo.create({type: Address, url: '/foo'}); 44 | expect(Foo.identityMap.limit()).toBe(Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT * 5); 45 | }); 46 | 47 | it('should return the same object when requested multiple times', function() { 48 | var addresses1 = Addresses.create({type: Address, url: '/address/'}); 49 | var addresses2 = Addresses.create({type: Address, url: '/address/'}); 50 | 51 | expect(addresses1).toBe(addresses2); 52 | }); 53 | 54 | it('should limit the number of objects retained', function() { 55 | var address; 56 | for(var i=1; i<=20; i++) { 57 | address = Addresses.create({type: Address, url: '/address/' + i}); 58 | } 59 | 60 | expect(Address.identityMap.size()).toBe(10); 61 | }); 62 | 63 | 64 | }); 65 | }); 66 | -------------------------------------------------------------------------------- /spec/javascripts/inheritanceSpec.js: -------------------------------------------------------------------------------- 1 | describe('Inheritance', function() { 2 | var Person; 3 | 4 | var keys = function(object) { 5 | var keys = []; 6 | for (var key in object) { 7 | if (object.hasOwnProperty(key)) keys.push(key); 8 | } 9 | return keys.sort(); 10 | }; 11 | 12 | beforeEach(function() { 13 | Person = Ember.Resource.define({ 14 | url: '/people', 15 | schema: { 16 | id: Number, 17 | name: String 18 | } 19 | }); 20 | }); 21 | 22 | it('should support many levels of inheritance', function() { 23 | expect(keys(Person.schema)).toEqual(['id', 'name']); 24 | 25 | var Worker = Person.define({ 26 | schema: { 27 | salary: Number 28 | } 29 | }); 30 | 31 | expect(keys(Worker.schema)).toEqual(['id', 'name', 'salary']); 32 | 33 | var LuckyBastard = Worker.define({ 34 | schema: { 35 | stockOptions: Number 36 | } 37 | }); 38 | 39 | expect(keys(LuckyBastard.schema)).toEqual(['id', 'name', 'salary', 'stockOptions']); 40 | }); 41 | 42 | it('should blow up when you try to redifine properties', function() { 43 | var defineBadSubclass = function() { 44 | return Person.define({ 45 | schema: { 46 | name: String 47 | } 48 | }); 49 | }; 50 | expect(defineBadSubclass).toThrow("Schema item 'name' is already defined"); 51 | }); 52 | 53 | it('should inherit the resource url', function() { 54 | var personUrl = Person.url; 55 | 56 | expect(personUrl).toBeDefined(); 57 | 58 | var Worker = Person.define({ 59 | schema: { 60 | salary: Number 61 | } 62 | }); 63 | 64 | expect(Worker.url).toBe(personUrl); 65 | }); 66 | 67 | it('should allow overriding the url', function() { 68 | var personUrl = Person.url; 69 | 70 | expect(personUrl).toBeDefined(); 71 | expect(personUrl).toNotBe('/workers'); 72 | 73 | var Worker = Person.define({ 74 | url: '/workers', 75 | schema: { 76 | salary: Number 77 | } 78 | }); 79 | 80 | expect(Worker.url).toBe('/workers'); 81 | 82 | }); 83 | 84 | }); 85 | -------------------------------------------------------------------------------- /spec/javascripts/lifecycleSpec.js: -------------------------------------------------------------------------------- 1 | /*globals Ember */ 2 | describe('Lifecycle', function() { 3 | var Person, server; 4 | 5 | beforeEach(function() { 6 | Person = Ember.Resource.define({ 7 | url: '/people', 8 | schema: { 9 | id: Number, 10 | name: String 11 | } 12 | }); 13 | 14 | server = sinon.fakeServer.create(); 15 | server.respondWith("GET", "/people/1", 16 | [200, { "Content-Type": "application/json" }, 17 | '{ "id": 1, "name": "Mick Staugaard" }']); 18 | }); 19 | 20 | afterEach(function() { 21 | server.restore(); 22 | }); 23 | 24 | describe('new object', function() { 25 | var person; 26 | beforeEach(function() { 27 | person = Person.create({id: 1}); 28 | }); 29 | 30 | it('should be in the UNFETCHED state', function() { 31 | expect(person.get('resourceState')).toBe(Ember.Resource.Lifecycle.UNFETCHED); 32 | }); 33 | 34 | it('should not be expired', function() { 35 | expect(person.get('isExpired')).toBeFalsy(); 36 | }); 37 | 38 | it('should never expire', function() { 39 | expect(person.get('expireAt')).toBeUndefined(); 40 | }); 41 | 42 | it('should be fetchable', function() { 43 | expect(person.get('isFetchable')).toBe(true); 44 | }); 45 | }); 46 | 47 | describe('fetching', function() { 48 | var person; 49 | beforeEach(function() { 50 | person = Person.create({id: 1}); 51 | person.fetch(); 52 | }); 53 | 54 | it('should put the object in a FETCHING state', function() { 55 | expect(person.get('resourceState')).toBe(Ember.Resource.Lifecycle.FETCHING); 56 | }); 57 | 58 | describe('is done', function() { 59 | beforeEach(function() { 60 | server.respond(); 61 | }); 62 | 63 | it('should put the object in a FETCHED state when the fetch is done', function() { 64 | expect(person.get('resourceState')).toBe(Ember.Resource.Lifecycle.FETCHED); 65 | }); 66 | 67 | it('should set expiry in 5 minutes', function() { 68 | var fiveMinutesFromNow = new Date(); 69 | fiveMinutesFromNow.setSeconds(fiveMinutesFromNow.getSeconds() + (60 * 5)); 70 | 71 | expect(person.get('expireAt')).toBeDefined(); 72 | expect(person.get('expireAt').getTime()).toBeCloseTo(fiveMinutesFromNow.getTime(), 2); 73 | }); 74 | }); 75 | 76 | }); 77 | 78 | describe('expiry', function() { 79 | var person; 80 | 81 | beforeEach(function() { 82 | person = Person.create({id: 1}); 83 | Ember.Resource.Lifecycle.clock.tick(); 84 | }); 85 | 86 | it('should be expired with an expireAt in the past', function() { 87 | var expiry = new Date(); 88 | expiry.setFullYear(expiry.getFullYear() - 1); 89 | person.set('expireAt', expiry); 90 | expect(person.get('isExpired')).toBe(true); 91 | expect(person.get('resourceState')).toBe(Ember.Resource.Lifecycle.EXPIRED); 92 | }); 93 | 94 | it('should be expired with an expireAt in the future', function() { 95 | var expiry = new Date(); 96 | expiry.setFullYear(expiry.getFullYear() + 1); 97 | person.set('expireAt', expiry); 98 | expect(person.get('isExpired')).toBeFalsy(); 99 | expect(person.get('resourceState')).toBe(Ember.Resource.Lifecycle.UNFETCHED); 100 | }); 101 | 102 | it('should expire when "expire" is called', function() { 103 | expect(person.get('isExpired')).toBeFalsy(); 104 | person.expire(); 105 | waitsFor(function() { 106 | return person.get('isExpired'); 107 | }, 'person never expired', 1000); 108 | }); 109 | }); 110 | 111 | }); 112 | -------------------------------------------------------------------------------- /spec/javascripts/remoteExpirySpec.js: -------------------------------------------------------------------------------- 1 | /*globals Ember, jasmine */ 2 | describe('remote expiry', function() { 3 | var Resource; 4 | describe('on a resource with a remote expiry key', function() { 5 | beforeEach(function() { 6 | Resource = Ember.Resource.define().extend({ 7 | remoteExpiryKey: "foo" 8 | }); 9 | this.resource = Resource.create(); 10 | spyOn(this.resource, 'subscribeForExpiry'); 11 | }); 12 | 13 | it('should subscribe for expiry on fetch', function() { 14 | Ember.sendEvent(this.resource, 'didFetch'); 15 | Ember.run.sync(); 16 | expect(this.resource.subscribeForExpiry).toHaveBeenCalled(); 17 | }); 18 | }); 19 | 20 | describe('on a resource with no remote expiry key', function() { 21 | beforeEach(function() { 22 | Resource = Ember.Resource.define().extend(); 23 | this.resource = Resource.create(); 24 | spyOn(this.resource, 'subscribeForExpiry'); 25 | }); 26 | 27 | it('should not subscribe for expiry on fetch', function() { 28 | Ember.sendEvent(this.resource, 'didFetch'); 29 | Ember.run.sync(); 30 | expect(this.resource.subscribeForExpiry).not.toHaveBeenCalled(); 31 | }); 32 | }); 33 | 34 | describe("subscribing for expiry", function() { 35 | beforeEach(function() { 36 | Resource = Ember.Resource.define().extend({ 37 | remoteExpiryKey: "foo" 38 | }); 39 | this.resource = Resource.create(); 40 | this.spy = spyOn(Ember.Resource.PushTransport, 'subscribe'); 41 | Ember.sendEvent(this.resource, 'didFetch'); 42 | Ember.run.sync(); 43 | }); 44 | 45 | it('should use the PushTransport', function() { 46 | expect(Ember.Resource.PushTransport.subscribe).toHaveBeenCalledWith("foo", jasmine.any(Function)); 47 | }); 48 | 49 | it('should subscribe to Ember.Resource.PushTransport', function() { 50 | expect(this.spy.callCount).toEqual(1); 51 | }); 52 | 53 | it('should not subscribe more than once', function() { 54 | Ember.sendEvent(this.resource, 'didFetch'); 55 | Ember.run.sync(); 56 | expect(this.spy.callCount).toEqual(1); 57 | }); 58 | }); 59 | 60 | describe("updating expiry", function() { 61 | beforeEach(function() { 62 | Resource = Ember.Resource.define().extend({ 63 | remoteExpiryKey: "foo" 64 | }); 65 | this.resource = Resource.create(); 66 | this.date = 1345511310; 67 | spyOn(this.resource, 'expire'); 68 | spyOn(this.resource, 'fetch'); 69 | }); 70 | 71 | it('should expire resource when stale', function() { 72 | this.resource.updateExpiry({ 73 | updatedAt: this.date 74 | }); 75 | expect(this.resource.expire).toHaveBeenCalled(); 76 | }); 77 | 78 | it('should not expire resource when fresh', function() { 79 | this.resource.set('expiryUpdatedAt', 1345511310 + 200); 80 | this.resource.updateExpiry({ 81 | updatedAt: this.date 82 | }); 83 | expect(this.resource.expire).not.toHaveBeenCalled(); 84 | }); 85 | 86 | it('should not expire resource when message is malformed', function() { 87 | this.resource.updateExpiry({}); 88 | expect(this.resource.expire).not.toHaveBeenCalled(); 89 | }); 90 | 91 | describe("with remote expiry auto fetch", function() { 92 | beforeEach(function() { 93 | this.resource.set('remoteExpiryAutoFetch', true); 94 | }); 95 | 96 | it('should refetch resource when stale', function() { 97 | var resource = this.resource; 98 | 99 | this.resource.updateExpiry({ 100 | updatedAt: this.date 101 | }); 102 | 103 | waitsFor(function() { 104 | return resource.get('isExpired'); 105 | }, 'resource never expired', 1000); 106 | 107 | runs(function() { 108 | expect(this.resource.fetch).toHaveBeenCalled(); 109 | expect(this.resource.expire).not.toHaveBeenCalled(); 110 | }); 111 | }); 112 | 113 | it('should not refetch resource when fresh', function() { 114 | this.resource.set('expiryUpdatedAt', 1345511310 + 200); 115 | this.resource.updateExpiry({ 116 | updatedAt: this.date 117 | }); 118 | expect(this.resource.expire).not.toHaveBeenCalled(); 119 | expect(this.resource.fetch).not.toHaveBeenCalled(); 120 | }); 121 | 122 | it('should not refetch resource when message is malformed', function() { 123 | this.resource.updateExpiry({}); 124 | expect(this.resource.expire).not.toHaveBeenCalled(); 125 | expect(this.resource.fetch).not.toHaveBeenCalled(); 126 | }); 127 | }); 128 | }); 129 | }); 130 | -------------------------------------------------------------------------------- /spec/javascripts/resourceCollectionSpec.js: -------------------------------------------------------------------------------- 1 | /*globals Em*/ 2 | 3 | describe('ResourceCollection', function() { 4 | 5 | it("reads from it's url property if present", function() { 6 | var Model = Em.Resource.define({ 7 | url: '/url/from/resource' 8 | }); 9 | 10 | var collection = Em.ResourceCollection.create({ 11 | type: Model, 12 | 13 | url: function() { 14 | return '/url/from/collection'; 15 | }.property().cacheable() 16 | }); 17 | 18 | expect(collection.resolveUrl()).toEqual('/url/from/collection'); 19 | }); 20 | 21 | describe("when prepopulated", function() { 22 | 23 | beforeEach(function() { 24 | this.collection = Em.ResourceCollection.create({ 25 | type: Object, 26 | content: [ { name: 'hello' } ] 27 | }); 28 | }); 29 | 30 | it('knows it is prePopulated', function() { 31 | expect(this.collection.get('prePopulated')).toBeTruthy(); 32 | }); 33 | 34 | it('returns a resolved deferred for #fetch', function() { 35 | var result = this.collection.fetch(); 36 | expect(result).not.toBeUndefined(); 37 | expect(result.isResolved()).toBeTruthy(); 38 | }); 39 | 40 | }); 41 | 42 | }); 43 | -------------------------------------------------------------------------------- /spec/javascripts/resourceSpec.js: -------------------------------------------------------------------------------- 1 | describe('A Resource instance', function() { 2 | var Model, model, server; 3 | 4 | beforeEach(function() { 5 | Model = Ember.Resource.define({ 6 | schema: { 7 | id: Number, 8 | name: String, 9 | subject: String 10 | }, 11 | url: '/people' 12 | }); 13 | 14 | }); 15 | 16 | 17 | describe("defining a resource", function() { 18 | 19 | describe("with a sideloads attribute", function() { 20 | var subject; 21 | beforeEach(function() { 22 | subject = Em.Resource.define({ 23 | url: "/users", 24 | sideloads: ["abilities", "weapons"] 25 | }); 26 | }); 27 | 28 | it("should not include the sideloads in resourceURL", function() { 29 | var user = subject.create({id: 1}); 30 | expect(user.resourceURL()).toEqual("/users/1"); 31 | }); 32 | 33 | it("should send the sideloads in AJAX fetches", function() { 34 | var user = subject.create({id: 1}); 35 | spyOn(Em.Resource, 'ajax').andReturn($.when()); 36 | user.fetch(); 37 | expect(Em.Resource.ajax).toHaveBeenCalledWith({ 38 | url: "/users/1", 39 | resource: user, 40 | operation: 'read', 41 | data: {include: "abilities,weapons"} 42 | }); 43 | }); 44 | }); 45 | }); 46 | 47 | describe('with no ID', function() { 48 | 49 | beforeEach(function() { 50 | model = Model.create({}); 51 | }); 52 | 53 | it('does not fetch when setting an attribute', function() { 54 | spyOn(model, 'fetch'); 55 | model.set('name', 'Patricia'); 56 | expect(model.fetch).not.toHaveBeenCalled(); 57 | }); 58 | 59 | it('allows setting a property to undefined', function() { 60 | model.set('name', 'Carlos'); 61 | expect(model.get('name')).toEqual('Carlos'); 62 | model.set('name', undefined); 63 | expect(model.get('name')).toBeUndefined(); 64 | }); 65 | 66 | }); 67 | 68 | describe('with a negative ID', function() { 69 | beforeEach(function() { 70 | model = Model.create({id: -1}); 71 | }); 72 | 73 | it('should not have a URL', function() { 74 | expect(model.resourceURL()).toBeUndefined(); 75 | }) 76 | }); 77 | 78 | it('allows setting of properties not in the schema during creation', function() { 79 | model = Model.create({ 80 | undefinedProperty: 'foo' 81 | }); 82 | 83 | expect(model.get('undefinedProperty')).toEqual('foo'); 84 | }); 85 | 86 | it('allows setting functions during creation', function() { 87 | model = Model.create({ 88 | undefinedProperty: function() { return 'foo'; } 89 | }); 90 | 91 | expect(Ember.typeOf(model.undefinedProperty)).toEqual('function'); 92 | expect(model.undefinedProperty()).toEqual('foo'); 93 | }); 94 | 95 | it('allows setting observers during creation', function() { 96 | var observerDidFire = false; 97 | model = Model.create({ 98 | myObserver: function() { observerDidFire = true; }.observes('foo') 99 | }); 100 | observerDidFire = false; 101 | model.set('foo', 'new value'); 102 | 103 | expect(observerDidFire).toBe(true); 104 | }); 105 | 106 | it('allows setting computed properties during creation', function() { 107 | model = Model.create({ 108 | undefinedProperty: function() { return this.get('foo') + '!'; }.property('foo') 109 | }); 110 | model.set('foo', 'foo'); 111 | 112 | expect(model.get('undefinedProperty')).toEqual('foo!'); 113 | }); 114 | 115 | 116 | it('allows setting of properties not in the schema during creation, considering paths', function() { 117 | 118 | Model = Ember.Resource.define({ 119 | schema: { 120 | id: Number, 121 | name: String, 122 | foo: {type: String, path: 'data.foo'} 123 | }, 124 | url: '/people' 125 | }); 126 | 127 | model = Model.create({ id: 1, undefinedProperty: 'foo', entry_id: 1, foo: 'bar' }); 128 | // expect(model.get('undefinedProperty')).toEqual('foo'); 129 | // expect(model.get('id')).toEqual(1); 130 | 131 | }); 132 | 133 | 134 | describe('updating objects already in identity map', function() { 135 | beforeEach(function() { 136 | model = Model.create({id: 1, name: 'blah'}); 137 | }); 138 | 139 | it('should update objects in the identity map with new data', function() { 140 | expect(model.get('subject')).toBeUndefined(); 141 | model = Model.create({id: 1, name: 'boo', subject: 'bar'}); 142 | expect(model.get('name')).toBe('boo'); 143 | expect(model.get('subject')).toBe('bar'); 144 | }); 145 | }); 146 | 147 | describe('when setting a property value', function() { 148 | beforeEach(function() { 149 | model = Model.create({name: 'Aardvark'}); 150 | }); 151 | 152 | it('should execute callbacks with the property name and new value', function() { 153 | spyOn(model, 'resourcePropertyWillChange'); 154 | spyOn(model, 'resourcePropertyDidChange'); 155 | model.set('name', 'Zebra'); 156 | expect(model.resourcePropertyWillChange).toHaveBeenCalledWith('name', 'Zebra'); 157 | expect(model.resourcePropertyDidChange).toHaveBeenCalledWith('name', 'Zebra'); 158 | }); 159 | }); 160 | }); 161 | -------------------------------------------------------------------------------- /spec/javascripts/resourceURLSpec.js: -------------------------------------------------------------------------------- 1 | /*globals describe, it, beforeEach, expect, Em */ 2 | describe('resourceURL', function() { 3 | var subject, instance; 4 | describe("for a resource with a string #url", function() { 5 | beforeEach(function() { 6 | subject = Em.Resource.define({ 7 | url: "/users/me" 8 | }); 9 | }); 10 | 11 | describe("for an instance with an id", function() { 12 | beforeEach(function() { 13 | instance = subject.create({id: 1}); 14 | }); 15 | 16 | it("should append the id to the string", function() { 17 | expect(instance.resourceURL()).toEqual("/users/me/1"); 18 | }); 19 | }); 20 | 21 | describe("for an instance with no id", function() { 22 | beforeEach(function() { 23 | instance = subject.create(); 24 | }); 25 | 26 | it("should return the string", function() { 27 | expect(instance.resourceURL()).toEqual("/users/me"); 28 | }); 29 | }); 30 | }); 31 | 32 | describe("for a resource with a function #url", function() { 33 | beforeEach(function() { 34 | subject = Em.Resource.define({ 35 | url: function(instance) { 36 | return "/users/%@".fmt(instance.get('id')); 37 | } 38 | }); 39 | }); 40 | 41 | describe("for an instance", function() { 42 | beforeEach(function() { 43 | instance = subject.create({id: 1}); 44 | }); 45 | it("should return the result of invoking the function with the instance", function() { 46 | spyOn(subject, 'url').andCallThrough(); 47 | 48 | expect(instance.resourceURL()).toEqual("/users/1"); 49 | expect(subject.url).toHaveBeenCalledWith(instance); 50 | }); 51 | }); 52 | 53 | }); 54 | }); 55 | -------------------------------------------------------------------------------- /spec/javascripts/saveSpec.js: -------------------------------------------------------------------------------- 1 | describe('Saving a resource instance', function() { 2 | var Model, model, server; 3 | 4 | beforeEach(function() { 5 | Model = Ember.Resource.define({ 6 | schema: { 7 | id: Number, 8 | name: String, 9 | subject: String 10 | }, 11 | url: '/people' 12 | }); 13 | 14 | server = sinon.fakeServer.create(); 15 | }); 16 | 17 | afterEach(function() { 18 | server.restore(); 19 | Ember.Resource.errorHandler = null; 20 | }); 21 | 22 | describe('handling errors on save', function() { 23 | beforeEach(function() { 24 | server.respondWith('POST', '/people', [422, {}, '[["foo", "bar"]]']); 25 | }); 26 | 27 | it('should pass a reference to the resource to the error handling function', function() { 28 | var spy = jasmine.createSpy(); 29 | Ember.Resource.errorHandler = function(a, b, c, fourthArgument) { 30 | spy(fourthArgument.resource, fourthArgument.operation); 31 | }; 32 | 33 | var resource = Model.create({ name: 'foo' }); 34 | resource.save(); 35 | server.respond(); 36 | 37 | expect(spy).toHaveBeenCalledWith(resource, "create"); 38 | }); 39 | }); 40 | 41 | describe('handling errors on create', function() { 42 | beforeEach(function() { 43 | server.respondWith('PUT', '/people/1', [422, {}, '[["foo", "bar"]]']); 44 | }); 45 | 46 | it('should pass a reference to the resource to the error handling function', function() { 47 | var spy = jasmine.createSpy(); 48 | Ember.Resource.errorHandler = function(a, b, c, fourthArgument) { 49 | spy(fourthArgument.resource, fourthArgument.operation); 50 | }; 51 | 52 | var resource = Model.create({ name: 'foo' }); 53 | resource.set('isNew', false); 54 | resource.set('id', 1); 55 | 56 | resource.save(); 57 | server.respond(); 58 | 59 | expect(spy).toHaveBeenCalledWith(resource, "update"); 60 | }); 61 | }); 62 | 63 | describe('resourceState', function() { 64 | describe('saving', function() { 65 | var resource; 66 | 67 | beforeEach(function() { 68 | server.respondWith('POST', '/people', [201, {}, '']); 69 | resource = Model.create({ name: 'foo' }); 70 | expect(resource.get('resourceState')).not.toBe(Ember.Resource.Lifecycle.SAVING); 71 | }); 72 | 73 | it('should change to the saving state while saving', function() { 74 | expect(resource.save()).toBeTruthy(); 75 | expect(resource.get('resourceState')).toBe(Ember.Resource.Lifecycle.SAVING); 76 | }); 77 | 78 | it('should indicate that it is saving', function() { 79 | expect(resource.get('isSaving')).toBe(false); 80 | expect(resource.save()).toBeTruthy(); 81 | expect(resource.get('isSaving')).toBe(true); 82 | }); 83 | 84 | it('should change to previous state after save completes', function() { 85 | var previousState = resource.get('resourceState'); 86 | expect(resource.save()).toBeTruthy(); 87 | expect(resource.get('resourceState')).not.toBe(previousState); 88 | server.respond(); 89 | expect(resource.get('resourceState')).toBe(previousState); 90 | }); 91 | 92 | it('should not allow concurrent saves', function() { 93 | expect(resource.save()).toBeTruthy(); 94 | expect(resource.save()).toBe(false); 95 | server.respond(); 96 | expect(resource.save()).toBeTruthy(); 97 | }); 98 | }); 99 | 100 | }); 101 | 102 | describe('updating from response', function() { 103 | var resource; 104 | 105 | describe('with default Location header parsing', function() { 106 | beforeEach(function() { 107 | server.respondWith('POST', '/people', [201, {'Location': 'http://example.com/people/25.json'}, '']); 108 | resource = Model.create({ name: 'foo' }); 109 | }); 110 | 111 | it('should update with the id from the Location header', function() { 112 | resource.save(); 113 | server.respond(); 114 | expect(resource.get('id')).toBe(25); 115 | }); 116 | }); 117 | 118 | describe('with a custom Location header parser', function() { 119 | beforeEach(function() { 120 | server.respondWith('POST', '/people', [201, {'Location': 'http://example.com/people/25.json'}, '']); 121 | Model.reopenClass({ 122 | idFromURL: function(url) { 123 | return 100; 124 | } 125 | }); 126 | 127 | resource = Model.create({ name: 'foo' }); 128 | }); 129 | 130 | it('should update with the id from the custom parser', function() { 131 | resource.save(); 132 | server.respond(); 133 | expect(resource.get('id')).toBe(100); 134 | }); 135 | }); 136 | 137 | describe('from a response body', function() { 138 | beforeEach(function() { 139 | server.respondWith('POST', '/people', [201, { "Content-Type": "application/json" }, '{ "id": 1, "subject": "the subject" }']); 140 | resource = Model.create({ name: 'foo' }); 141 | }); 142 | 143 | it('should update with the data given', function() { 144 | resource.save(); 145 | server.respond(); 146 | expect(resource.get('id')).toBe(1); 147 | expect(resource.get('subject')).toBe('the subject'); 148 | expect(resource.get('name')).toBe('foo'); 149 | }); 150 | 151 | it('should not update with the data if you pass the update: false option', function() { 152 | resource.save({update: false}); 153 | server.respond(); 154 | expect(resource.get('id')).toBeUndefined(); 155 | expect(resource.get('subject')).toBeUndefined(); 156 | expect(resource.get('name')).toBe('foo'); 157 | }) 158 | 159 | describe('resource has one embedded association', function() { 160 | beforeEach(function() { 161 | var Address = Ember.Resource.define({ 162 | schema: { 163 | street: String, 164 | zip: Number, 165 | city: String 166 | } 167 | }); 168 | var Person = Ember.Resource.define({ 169 | schema: { 170 | id: Number, 171 | name: String, 172 | address: {type: Address, nested: true} 173 | }, 174 | url: '/persons' 175 | }); 176 | server.respondWith('POST', '/persons', [201, { "Content-Type": "application/json" }, '{ "id": 1, "address": { "street": "baz" } }']); 177 | resource = Person.create({ name: 'foo' }, { address: { street: 'bar' } }); 178 | }); 179 | 180 | it("should update with the data given", function() { 181 | resource.save(); 182 | server.respond(); 183 | expect(resource.get('id')).toBe(1); 184 | expect(resource.getPath('address.street')).toBe('baz'); 185 | }); 186 | }); 187 | }); 188 | 189 | }); 190 | }); 191 | -------------------------------------------------------------------------------- /spec/javascripts/schemaSpec.js: -------------------------------------------------------------------------------- 1 | describe('schema definition', function() { 2 | describe('of attributes', function() { 3 | var Model; 4 | 5 | beforeEach(function() { 6 | Model = Ember.Resource.define({ 7 | schema: { 8 | id: {type: Number, path: 'somewhere.deep.id'}, 9 | size: {type: Number}, 10 | age: Number, 11 | name: String, 12 | birthday: Date, 13 | single: Boolean 14 | } 15 | }); 16 | }); 17 | 18 | it('should use the specified path if given', function() { 19 | expect(Model.schema.id.path).toBe('somewhere.deep.id'); 20 | }); 21 | 22 | it('should use the attribute name as path if not specified', function() { 23 | expect(Model.schema.size.path).toBe('size'); 24 | }); 25 | 26 | it('should support Number', function() { 27 | expect(Model.schema.age.get('type')).toBe(Number); 28 | expect(Model.schema.age.path).toBe('age'); 29 | }); 30 | 31 | it('should support String', function() { 32 | expect(Model.schema.name.get('type')).toBe(String); 33 | expect(Model.schema.name.path).toBe('name'); 34 | }); 35 | 36 | it('should support Date', function() { 37 | expect(Model.schema.birthday.get('type')).toBe(Date); 38 | expect(Model.schema.birthday.path).toBe('birthday'); 39 | }); 40 | 41 | it('should support Boolean', function() { 42 | expect(Model.schema.single.get('type')).toBe(Boolean); 43 | expect(Model.schema.single.path).toBe('single'); 44 | }); 45 | }); 46 | 47 | describe('of has-one associations', function() { 48 | var Model, Person, Address; 49 | 50 | beforeEach(function() { 51 | Address = Ember.Resource.define({ 52 | schema: { 53 | street: String, 54 | zip: Number 55 | } 56 | }); 57 | 58 | Model = Ember.Resource.define({ 59 | schema: { 60 | home_address: {type: Address}, 61 | work_address: {type: Address, path: 'work_addr_id'}, 62 | work_addr_id: String, 63 | other_address: {type: Address, nested: true} 64 | } 65 | }); 66 | }); 67 | 68 | it('should use the specified path when given', function() { 69 | expect(Model.schema.work_address.get('path')).toBe('work_addr_id'); 70 | }); 71 | 72 | it('should guess a path from the name when not given', function() { 73 | expect(Model.schema.home_address.get('path')).toBe('home_address_id'); 74 | }); 75 | 76 | it('should define a Number attribute at the path if not present', function() { 77 | expect(Model.schema.home_address_id).toBeDefined(); 78 | expect(Model.schema.home_address_id.get('type')).toBe(Number); 79 | }); 80 | 81 | it('should not override the attribute at the path if present', function() { 82 | expect(Model.schema.work_addr_id).toBeDefined(); 83 | expect(Model.schema.work_addr_id.get('type')).toBe(String); 84 | }); 85 | 86 | it('should create an *_id attribute for nested associations', function() { 87 | expect(Model.schema.other_address).toBeDefined(); 88 | expect(Model.schema.other_address_id).toBeDefined(); 89 | expect(Model.schema.other_address_id instanceof Ember.Resource.HasOneNestedIdSchemaItem).toBe(true); 90 | expect(Model.schema.other_address_id.get('association')).toBe(Model.schema.other_address); 91 | expect(Model.schema.other_address_id.get('path')).toBe('other_address.id'); 92 | }); 93 | }); 94 | 95 | it('should create Number properties', function() { 96 | var Model = Ember.Resource.define({ 97 | schema: { 98 | id: Number, 99 | size: Number 100 | } 101 | }); 102 | var data = {id: 1, size: '5'}; 103 | var instance = Model.create({}, data); 104 | data = instance.get('data'); 105 | 106 | expect(instance.get('id')).toBe(1); 107 | expect(instance.get('size')).toBe(5); 108 | 109 | instance.set('id', '2'); 110 | expect(instance.getPath('data.id')).toBe(2); 111 | 112 | instance.set('size', 3); 113 | expect(instance.getPath('data.size')).toBe(3); 114 | 115 | instance.set('size', 'foo'); 116 | expect(instance.get('size')).toBeUndefined(); 117 | expect(instance.getPath('data.size')).toBeUndefined(); 118 | 119 | instance.set('size', NaN); 120 | expect(instance.get('size')).toBeUndefined(); 121 | expect(instance.getPath('data.size')).toBeUndefined(); 122 | }); 123 | 124 | it('should create String properties', function() { 125 | var Model = Ember.Resource.define({ 126 | schema: { 127 | id: String, 128 | size: String 129 | } 130 | }); 131 | var data = {id: 1, size: 'large'}; 132 | var instance = Model.create({}, data); 133 | data = instance.get('data'); 134 | 135 | expect(instance.get('id')).toBe('1'); 136 | expect(instance.get('size')).toBe('large'); 137 | 138 | instance.set('id', 2); 139 | expect(instance.getPath('data.id')).toBe('2'); 140 | 141 | instance.set('size', 'small'); 142 | expect(instance.getPath('data.size')).toBe('small'); 143 | }); 144 | 145 | it('should create Date properties', function() { 146 | var date = new Date(); 147 | var dateString = date.toJSON(); 148 | 149 | var Model = Ember.Resource.define({ 150 | schema: { 151 | createdAt: Date, 152 | updatedAt: Date 153 | } 154 | }); 155 | var data = {createdAt: dateString, updatedAt: date}; 156 | var instance = Model.create({}, data); 157 | data = instance.get('data'); 158 | 159 | expect(instance.get('createdAt')).toEqual(date); 160 | expect(instance.get('updatedAt')).toEqual(date); 161 | 162 | date = new Date(); 163 | dateString = date.toJSON(); 164 | 165 | instance.set('createdAt', date); 166 | expect(instance.getPath('data.createdAt')).toEqual(dateString, "convert a Date instance to a string"); 167 | 168 | instance.set('updatedAt', dateString); 169 | expect(instance.getPath('data.updatedAt')).toEqual(dateString, 'convert a string ("' + dateString + '") to a string'); 170 | }); 171 | 172 | it('should create Boolean properties', function() { 173 | var Model = Ember.Resource.define({ 174 | schema: { 175 | 'public': Boolean, 176 | active: Boolean, 177 | good: Boolean, 178 | bad: Boolean 179 | } 180 | }); 181 | var data = {'public': true, active: false, good: 'true', bad: 'false'}; 182 | var instance = Model.create({}, data); 183 | data = instance.get('data'); 184 | 185 | expect(instance.get('public')).toBe(true); 186 | expect(instance.get('active')).toBe(false); 187 | expect(instance.get('good')).toBe(true); 188 | expect(instance.get('bad')).toBe(false); 189 | 190 | instance.set('public', 'true'); 191 | expect(instance.getPath('data.public')).toBe(true, "convert 'true' to true"); 192 | 193 | instance.set('public', 'false'); 194 | expect(instance.getPath('data.public')).toBe(false, "convert 'false' to false"); 195 | 196 | instance.set('public', true); 197 | expect(instance.getPath('data.public')).toBe(true, "convert true to true"); 198 | 199 | instance.set('public', false); 200 | expect(instance.getPath('data.public')).toBe(false, "convert false to false"); 201 | }); 202 | }); 203 | -------------------------------------------------------------------------------- /spec/javascripts/support/jasmine.yml: -------------------------------------------------------------------------------- 1 | # src_files 2 | # 3 | # Return an array of filepaths relative to src_dir to include before jasmine specs. 4 | # Default: [] 5 | # 6 | # EXAMPLE: 7 | # 8 | # src_files: 9 | # - lib/source1.js 10 | # - lib/source2.js 11 | # - dist/**/*.js 12 | # 13 | src_files: 14 | - vendor/jquery-1.7.js 15 | - vendor/ember-0.9.8.1.js 16 | - vendor/sinon-1.2.0.js 17 | - dist/ember-resource.js 18 | 19 | # stylesheets 20 | # 21 | # Return an array of stylesheet filepaths relative to src_dir to include before jasmine specs. 22 | # Default: [] 23 | # 24 | # EXAMPLE: 25 | # 26 | # stylesheets: 27 | # - css/style.css 28 | # - stylesheets/*.css 29 | # 30 | stylesheets: 31 | 32 | # helpers 33 | # 34 | # Return an array of filepaths relative to spec_dir to include before jasmine specs. 35 | # Default: ["helpers/**/*.js"] 36 | # 37 | # EXAMPLE: 38 | # 39 | # helpers: 40 | # - helpers/**/*.js 41 | # 42 | helpers: 43 | - helpers/**/*.js 44 | 45 | # spec_files 46 | # 47 | # Return an array of filepaths relative to spec_dir to include. 48 | # Default: ["**/*[sS]pec.js"] 49 | # 50 | # EXAMPLE: 51 | # 52 | # spec_files: 53 | # - **/*[sS]pec.js 54 | # 55 | spec_files: 56 | - '**/*[sS]pec.js' 57 | 58 | # src_dir 59 | # 60 | # Source directory path. Your src_files must be returned relative to this path. Will use root if left blank. 61 | # Default: project root 62 | # 63 | # EXAMPLE: 64 | # 65 | # src_dir: public 66 | # 67 | src_dir: 68 | 69 | # spec_dir 70 | # 71 | # Spec directory path. Your spec_files must be returned relative to this path. 72 | # Default: spec/javascripts 73 | # 74 | # EXAMPLE: 75 | # 76 | # spec_dir: spec/javascripts 77 | # 78 | spec_dir: spec/javascripts 79 | -------------------------------------------------------------------------------- /spec/javascripts/support/jasmine_config.rb: -------------------------------------------------------------------------------- 1 | module Jasmine 2 | class Config 3 | 4 | # Add your overrides or custom config code here 5 | 6 | end 7 | end 8 | 9 | 10 | # Note - this is necessary for rspec2, which has removed the backtrace 11 | module Jasmine 12 | class SpecBuilder 13 | def declare_spec(parent, spec) 14 | me = self 15 | example_name = spec["name"] 16 | @spec_ids << spec["id"] 17 | backtrace = @example_locations[parent.description + " " + example_name] 18 | parent.it example_name, {} do 19 | me.report_spec(spec["id"]) 20 | end 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /spec/javascripts/support/jasmine_runner.rb: -------------------------------------------------------------------------------- 1 | $:.unshift(ENV['JASMINE_GEM_PATH']) if ENV['JASMINE_GEM_PATH'] # for gem testing purposes 2 | 3 | require 'rubygems' 4 | require 'jasmine' 5 | jasmine_config_overrides = File.expand_path(File.join(File.dirname(__FILE__), 'jasmine_config.rb')) 6 | require jasmine_config_overrides if File.exist?(jasmine_config_overrides) 7 | if Jasmine::rspec2? 8 | require 'rspec' 9 | else 10 | require 'spec' 11 | end 12 | 13 | jasmine_config = Jasmine::Config.new 14 | spec_builder = Jasmine::SpecBuilder.new(jasmine_config) 15 | 16 | should_stop = false 17 | 18 | if Jasmine::rspec2? 19 | RSpec.configuration.after(:suite) do 20 | spec_builder.stop if should_stop 21 | end 22 | else 23 | Spec::Runner.configure do |config| 24 | config.after(:suite) do 25 | spec_builder.stop if should_stop 26 | end 27 | end 28 | end 29 | 30 | spec_builder.start 31 | should_stop = true 32 | spec_builder.declare_suites -------------------------------------------------------------------------------- /spec/javascripts/toJSONSpec.js: -------------------------------------------------------------------------------- 1 | describe('toJSON', function() { 2 | it('should use toJSON of each of the schema items', function() { 3 | var Book = Ember.Resource.define({ 4 | schema: { 5 | id: Number, 6 | title: String 7 | } 8 | }); 9 | 10 | var book = Book.create({id: 1, title: 'Rework'}); 11 | 12 | spyOn(Book.schema.id, 'toJSON').andReturn(1); 13 | spyOn(Book.schema.title, 'toJSON').andReturn(undefined); 14 | 15 | var json = book.toJSON(); 16 | 17 | expect(Book.schema.id.toJSON).toHaveBeenCalledWith(book); 18 | expect(Book.schema.title.toJSON).toHaveBeenCalledWith(book); 19 | 20 | expect(json).toEqual({id: 1}); 21 | }); 22 | 23 | describe('nested objects', function() { 24 | var Address = Ember.Resource.define({ 25 | schema: { 26 | city: String 27 | } 28 | }); 29 | 30 | var Person = Ember.Resource.define({ 31 | schema: { 32 | id: Number, 33 | name: String, 34 | address: { 35 | type: Address, 36 | nested: true 37 | } 38 | } 39 | }); 40 | 41 | var attributes = { 42 | name: 'John Smit', 43 | address: { 44 | city: 'London' 45 | } 46 | }; 47 | 48 | it('should return updated values of nested objects', function() { 49 | var person = Person.create(attributes), 50 | newCity = 'Liverpool', 51 | newName = 'Smit Johnson'; 52 | 53 | Ember.setPath(person, 'address.city', newCity); 54 | Ember.set(person, 'name', newName); 55 | 56 | var json = person.toJSON(); 57 | 58 | expect(json).toEqual({ 59 | name: newName, 60 | address: { city: newCity } 61 | }); 62 | }); 63 | }); 64 | 65 | describe('remote has one associations', function() { 66 | var Address = Ember.Resource.define({ 67 | schema: { 68 | id: Number, 69 | city: String 70 | } 71 | }); 72 | 73 | var Person = Ember.Resource.define({ 74 | schema: { 75 | id: Number, 76 | name: String, 77 | address: { type: Address } 78 | } 79 | }); 80 | 81 | it('should return the id of the association at the path', function() { 82 | var address = Address.create({id: 1, city: 'San Francisco'}); 83 | var person = Person.create({id: 1, name: 'Mick Staugaard', address: address}); 84 | 85 | var json = person.toJSON(); 86 | expect(json.address).toBeUndefined(); 87 | expect(json.address_id).toBe(1); 88 | }); 89 | 90 | }); 91 | 92 | describe('remote has many associations', function() { 93 | var Book = Ember.Resource.define({ 94 | schema: { 95 | id: Number, 96 | title: String 97 | } 98 | }); 99 | 100 | var Library = Ember.Resource.define({ 101 | schema: { 102 | name: String, 103 | 104 | books: { 105 | type: Ember.ResourceCollection, 106 | itemType: Book, 107 | url: '/libraries/%@/books' 108 | } 109 | } 110 | }); 111 | 112 | it('should not be included', function() { 113 | var library = Library.create({name: 'The Robarts Library'}); 114 | Ember.setPath(library, 'books.content', [{ id: 1, title: 'The Hobbit' }]); 115 | expect(library.toJSON()).toEqual({ name: 'The Robarts Library' }); 116 | }); 117 | }); 118 | 119 | describe('has many in array associations', function() { 120 | var Book = Ember.Resource.define({ 121 | schema: { 122 | id: Number, 123 | title: String 124 | } 125 | }); 126 | 127 | var Library = Ember.Resource.define({ 128 | schema: { 129 | name: String, 130 | 131 | books: { 132 | type: Ember.ResourceCollection, 133 | itemType: Book 134 | } 135 | } 136 | }); 137 | 138 | it('should include the ids of the items', function() { 139 | var library = Library.create({}, { 140 | name: 'The Robarts Library', 141 | books_ids: [1,2,3] 142 | }); 143 | 144 | expect(library.toJSON()).toEqual({ 145 | name: 'The Robarts Library', 146 | books_ids: [1,2,3] 147 | }); 148 | }) 149 | }); 150 | }); 151 | -------------------------------------------------------------------------------- /src/base.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | 3 | window.Ember = window.Ember || window.SC; 4 | 5 | window.Ember.Resource = window.Ember.Object.extend({ 6 | resourcePropertyWillChange: window.Ember.K, 7 | resourcePropertyDidChange: window.Ember.K 8 | }); 9 | 10 | window.Ember.Resource.SUPPORT_AUTOFETCH = true; 11 | }()); 12 | -------------------------------------------------------------------------------- /src/ember-resource.js: -------------------------------------------------------------------------------- 1 | (function(exports) { 2 | 3 | var expandSchema, expandSchemaItem, createSchemaProperties, 4 | mergeSchemas; 5 | 6 | var Ember = exports.Ember; 7 | 8 | function isString(obj) { 9 | return !!(obj === '' || (obj && obj !== String && obj.charCodeAt && obj.substr)); 10 | } 11 | 12 | function isObject(obj) { 13 | return obj === Object(obj); 14 | } 15 | 16 | Ember.Resource.deepSet = function(obj, path, value) { 17 | if (Ember.typeOf(path) === 'string') { 18 | Ember.Resource.deepSet(obj, path.split('.'), value); 19 | return; 20 | } 21 | 22 | var key = path.shift(); 23 | 24 | if (path.length === 0) { 25 | Ember.set(obj, key, value); 26 | } else { 27 | var newObj = Ember.get(obj, key); 28 | 29 | if (newObj === null || newObj === undefined) { 30 | newObj = {}; 31 | Ember.set(obj, key, newObj); 32 | } 33 | 34 | Ember.propertyWillChange(newObj, path); 35 | Ember.Resource.deepSet(newObj, path, value); 36 | Ember.propertyDidChange(newObj, path); 37 | } 38 | }; 39 | 40 | Ember.Resource.deepMerge = function(objA, objB) { 41 | var oldValue, newValue; 42 | 43 | for (var key in objB) { 44 | if (objB.hasOwnProperty(key)) { 45 | oldValue = Ember.get(objA, key); 46 | newValue = Ember.get(objB, key); 47 | 48 | if (Ember.typeOf(newValue) === 'object' && Ember.typeOf(oldValue) === 'object') { 49 | Ember.propertyWillChange(objA, key); 50 | Ember.Resource.deepMerge(oldValue, newValue); 51 | Ember.propertyDidChange(objA, key); 52 | } else { 53 | Ember.set(objA, key, newValue); 54 | } 55 | } 56 | } 57 | }; 58 | 59 | Ember.Resource.AbstractSchemaItem = Ember.Object.extend({ 60 | name: Ember.required(String), 61 | fetchable: Ember.required(Boolean), 62 | getValue: Ember.required(Function), 63 | setValue: Ember.required(Function), 64 | 65 | dependencies: Ember.computed('path', function() { 66 | var deps = ['data.' + this.get('path')]; 67 | 68 | if(Ember.Resource.SUPPORT_AUTOFETCH) { 69 | deps.push('isExpired'); 70 | } 71 | 72 | return deps; 73 | }).cacheable(), 74 | 75 | data: function(instance) { 76 | return Ember.get(instance, 'data'); 77 | }, 78 | 79 | type: Ember.computed('theType', function() { 80 | var type = this.get('theType'); 81 | if (isString(type)) { 82 | type = Ember.getPath(type); 83 | if (type) { 84 | this.set('theType', type); 85 | } else { 86 | type = this.get('theType'); 87 | } 88 | } 89 | return type; 90 | }).cacheable(), 91 | 92 | propertyFunction: function(name, value) { 93 | var schemaItem = this.constructor.schema[name]; 94 | if (arguments.length === 2) { 95 | this.resourcePropertyWillChange(name, value); 96 | schemaItem.setValue.call(schemaItem, this, value); 97 | value = schemaItem.getValue.call(schemaItem, this); 98 | this.resourcePropertyDidChange(name, value); 99 | } else { 100 | value = schemaItem.getValue.call(schemaItem, this); 101 | if ((value === undefined || Ember.get(this, 'isExpired')) && schemaItem.get('fetchable')) { 102 | this.scheduleFetch(); 103 | } 104 | } 105 | return value; 106 | }, 107 | 108 | property: function() { 109 | var cp = new Ember.ComputedProperty(this.propertyFunction); 110 | return cp.property.apply(cp, this.get('dependencies')).cacheable(); 111 | }, 112 | 113 | toJSON: function(instance) { 114 | return undefined; 115 | } 116 | }); 117 | Ember.Resource.AbstractSchemaItem.reopenClass({ 118 | create: function(name, schema) { 119 | var instance = this._super.apply(this); 120 | instance.set('name', name); 121 | return instance; 122 | } 123 | }); 124 | 125 | 126 | Ember.Resource.SchemaItem = Ember.Resource.AbstractSchemaItem.extend({}); 127 | 128 | Ember.Resource.SchemaItem.reopenClass({ 129 | create: function(name, schema) { 130 | var definition = schema[name]; 131 | 132 | if (definition instanceof Ember.Resource.AbstractSchemaItem) { return definition; } 133 | 134 | var type; 135 | if (definition === Number || definition === String || definition === Boolean || definition === Date || definition === Object) { 136 | definition = {type: definition}; 137 | schema[name] = definition; 138 | } 139 | 140 | if(isObject(definition)) { 141 | type = definition.type; 142 | } 143 | 144 | if (type) { 145 | if (type.isEmberResource || Ember.typeOf(type) === 'string') { // a has-one association 146 | return Ember.Resource.HasOneSchemaItem.create(name, schema); 147 | } else if(type.isEmberResourceCollection) { // a has-many association 148 | return Ember.Resource.HasManySchemaItem.create(name, schema); 149 | } else { // a regular attribute 150 | return Ember.Resource.AttributeSchemaItem.create(name, schema); 151 | } 152 | } 153 | } 154 | }); 155 | 156 | Ember.Resource.AttributeSchemaItem = Ember.Resource.AbstractSchemaItem.extend({ 157 | fetchable: true, 158 | theType: Object, 159 | path: Ember.required(String), 160 | 161 | getValue: function(instance) { 162 | var value; 163 | var data = this.data(instance); 164 | if (data) { 165 | value = Ember.getPath(data, this.get('path')); 166 | } 167 | 168 | if (this.typeCast) { 169 | value = this.typeCast(value); 170 | } 171 | 172 | return value; 173 | }, 174 | 175 | setValue: function(instance, value) { 176 | var data = this.data(instance); 177 | if (!data) return; 178 | 179 | if (this.typeCast) { 180 | value = this.typeCast(value); 181 | } 182 | if (value !== null && value !== undefined && Ember.typeOf(value.toJSON) == 'function') { 183 | value = value.toJSON(); 184 | } 185 | Ember.Resource.deepSet(data, this.get('path'), value); 186 | }, 187 | 188 | toJSON: function(instance) { 189 | return Ember.get(instance, this.name); 190 | } 191 | }); 192 | 193 | Ember.Resource.AttributeSchemaItem.reopenClass({ 194 | create: function(name, schema) { 195 | var definition = schema[name]; 196 | var instance; 197 | 198 | if (this === Ember.Resource.AttributeSchemaItem) { 199 | switch (definition.type) { 200 | case Number: 201 | return Ember.Resource.NumberAttributeSchemaItem.create(name, schema); 202 | case String: 203 | return Ember.Resource.StringAttributeSchemaItem.create(name, schema); 204 | case Boolean: 205 | return Ember.Resource.BooleanAttributeSchemaItem.create(name, schema); 206 | case Date: 207 | return Ember.Resource.DateAttributeSchemaItem.create(name, schema); 208 | default: 209 | instance = this._super.apply(this, arguments); 210 | instance.set('fetchable', name !== 'id'); 211 | instance.set('path', definition.path || name); 212 | return instance; 213 | } 214 | } 215 | else { 216 | instance = this._super.apply(this, arguments); 217 | instance.set('fetchable', name !== 'id'); 218 | instance.set('path', definition.path || name); 219 | return instance; 220 | } 221 | } 222 | }); 223 | 224 | Ember.Resource.NumberAttributeSchemaItem = Ember.Resource.AttributeSchemaItem.extend({ 225 | theType: Number, 226 | typeCast: function(value) { 227 | if (isNaN(value)) { 228 | value = undefined; 229 | } 230 | 231 | if (value === undefined || value === null || Ember.typeOf(value) === 'number') { 232 | return value; 233 | } else { 234 | return Number(value); 235 | } 236 | } 237 | }); 238 | 239 | Ember.Resource.StringAttributeSchemaItem = Ember.Resource.AttributeSchemaItem.extend({ 240 | theType: String, 241 | typeCast: function(value) { 242 | if (value === undefined || value === null || Ember.typeOf(value) === 'string') { 243 | return value; 244 | } else { 245 | return '' + value; 246 | } 247 | } 248 | }); 249 | 250 | Ember.Resource.BooleanAttributeSchemaItem = Ember.Resource.AttributeSchemaItem.extend({ 251 | theType: Boolean, 252 | typeCast: function(value) { 253 | if (value === undefined || value === null || Ember.typeOf(value) === 'boolean') { 254 | return value; 255 | } else { 256 | return value === 'true'; 257 | } 258 | } 259 | }); 260 | 261 | Ember.Resource.DateAttributeSchemaItem = Ember.Resource.AttributeSchemaItem.extend({ 262 | theType: Date, 263 | typeCast: function(value) { 264 | if (value === undefined || value === null || Ember.typeOf(value) === 'date') { 265 | return value; 266 | } else { 267 | return new Date(value); 268 | } 269 | }, 270 | toJSON: function(instance) { 271 | var value = Ember.get(instance, this.name); 272 | return value ? value.toJSON() : value; 273 | } 274 | }); 275 | 276 | Ember.Resource.HasOneSchemaItem = Ember.Resource.AbstractSchemaItem.extend({ 277 | fetchable: true 278 | }); 279 | Ember.Resource.HasOneSchemaItem.reopenClass({ 280 | create: function(name, schema) { 281 | var definition = schema[name]; 282 | if (this === Ember.Resource.HasOneSchemaItem) { 283 | if (definition.nested) { 284 | return Ember.Resource.HasOneNestedSchemaItem.create(name, schema); 285 | } else { 286 | return Ember.Resource.HasOneRemoteSchemaItem.create(name, schema); 287 | } 288 | } 289 | else { 290 | var instance = this._super.apply(this, arguments); 291 | instance.set('theType', definition.type); 292 | if (definition.parse) { 293 | instance.set('parse', definition.parse); 294 | } 295 | return instance; 296 | } 297 | } 298 | }); 299 | 300 | Ember.Resource.HasOneNestedSchemaItem = Ember.Resource.HasOneSchemaItem.extend({ 301 | getValue: function(instance) { 302 | var data = this.data(instance); 303 | if (!data) return; 304 | var type = this.get('type'); 305 | var value = Ember.getPath(data, this.get('path')); 306 | if (value) { 307 | value = (this.get('parse') || type.parse).call(type, Ember.copy(value)); 308 | return type.create({}, value); 309 | } 310 | return value; 311 | }, 312 | 313 | setValue: function(instance, value) { 314 | var data = this.data(instance); 315 | if (!data) return; 316 | 317 | if (value instanceof this.get('type')) { 318 | value = Ember.get(value, 'data'); 319 | } 320 | 321 | Ember.Resource.deepSet(data, this.get('path'), value); 322 | }, 323 | 324 | toJSON: function(instance) { 325 | var value = Ember.get(instance, this.name); 326 | return value ? value.toJSON() : value; 327 | } 328 | }); 329 | Ember.Resource.HasOneNestedSchemaItem.reopenClass({ 330 | create: function(name, schema) { 331 | var definition = schema[name]; 332 | var instance = this._super.apply(this, arguments); 333 | instance.set('path', definition.path || name); 334 | 335 | var id_name = name + '_id'; 336 | if (!schema[id_name]) { 337 | schema[id_name] = {type: Number, association: instance }; 338 | schema[id_name] = Ember.Resource.HasOneNestedIdSchemaItem.create(id_name, schema); 339 | } 340 | 341 | return instance; 342 | } 343 | }); 344 | Ember.Resource.HasOneNestedIdSchemaItem = Ember.Resource.AbstractSchemaItem.extend({ 345 | fetchable: true, 346 | theType: Number, 347 | getValue: function(instance) { 348 | return instance.getPath(this.get('path')); 349 | }, 350 | setValue: function(instance, value) { 351 | Ember.set(instance, this.getPath('association.name'), {id: value}); 352 | } 353 | }); 354 | Ember.Resource.HasOneNestedIdSchemaItem.reopenClass({ 355 | create: function(name, schema) { 356 | var definition = schema[name]; 357 | var instance = this._super.apply(this, arguments); 358 | instance.set('association', definition.association); 359 | instance.set('path', definition.association.get('path') + '.id'); 360 | return instance; 361 | } 362 | }); 363 | 364 | 365 | Ember.Resource.HasOneRemoteSchemaItem = Ember.Resource.HasOneSchemaItem.extend({ 366 | getValue: function(instance) { 367 | var data = this.data(instance); 368 | if (!data) return; 369 | var id = Ember.getPath(data, this.get('path')); 370 | if (id) { 371 | return this.get('type').create({}, {id: id}); 372 | } 373 | }, 374 | 375 | setValue: function(instance, value) { 376 | var data = this.data(instance); 377 | if (!data) return; 378 | var id = Ember.get(value || {}, 'id'); 379 | Ember.Resource.deepSet(data, this.get('path'), id); 380 | } 381 | }); 382 | Ember.Resource.HasOneRemoteSchemaItem.reopenClass({ 383 | create: function(name, schema) { 384 | var definition = schema[name]; 385 | var instance = this._super.apply(this, arguments); 386 | var path = definition.path || name + '_id'; 387 | instance.set('path', path); 388 | 389 | if (!schema[path]) { 390 | schema[path] = Number; 391 | schema[path] = Ember.Resource.SchemaItem.create(path, schema); 392 | } 393 | 394 | return instance; 395 | } 396 | }); 397 | 398 | 399 | Ember.Resource.HasManySchemaItem = Ember.Resource.AbstractSchemaItem.extend({ 400 | itemType: Ember.computed('theItemType', function() { 401 | var type = this.get('theItemType'); 402 | if (isString(type)) { 403 | type = Ember.getPath(type); 404 | if (type) { 405 | this.set('theItemType', type); 406 | } else { 407 | type = this.get('theItemType'); 408 | } 409 | } 410 | return type; 411 | }).cacheable() 412 | }); 413 | 414 | Ember.Resource.HasManySchemaItem.reopenClass({ 415 | create: function(name, schema) { 416 | var definition = schema[name]; 417 | if (this === Ember.Resource.HasManySchemaItem) { 418 | if (definition.url) { 419 | return Ember.Resource.HasManyRemoteSchemaItem.create(name, schema); 420 | } else if (definition.nested) { 421 | return Ember.Resource.HasManyNestedSchemaItem.create(name, schema); 422 | } else { 423 | return Ember.Resource.HasManyInArraySchemaItem.create(name, schema); 424 | } 425 | } else { 426 | var instance = this._super.apply(this, arguments); 427 | instance.set('theType', definition.type); 428 | instance.set('theItemType', definition.itemType); 429 | if (definition.parse) { 430 | instance.set('parse', definition.parse); 431 | } 432 | return instance; 433 | } 434 | } 435 | }); 436 | 437 | Ember.Resource.HasManyRemoteSchemaItem = Ember.Resource.HasManySchemaItem.extend({ 438 | fetchable: false, 439 | dependencies: ['id', 'isInitializing'], 440 | getValue: function(instance) { 441 | if (Ember.get(instance, 'isInitializing')) return; 442 | 443 | var options = { 444 | type: this.get('itemType') 445 | }; 446 | 447 | if (this.get('parse')) options.parse = this.get('parse'); 448 | 449 | var url = this.url(instance); 450 | if (url) { 451 | options.url = url; 452 | } else { 453 | options.content = []; 454 | } 455 | 456 | return this.get('type').create(options); 457 | }, 458 | 459 | setValue: function(instance, value) { 460 | throw('you can not set a remote has many association'); 461 | } 462 | }); 463 | Ember.Resource.HasManyRemoteSchemaItem.reopenClass({ 464 | create: function(name, schema) { 465 | var definition = schema[name]; 466 | 467 | var instance = this._super.apply(this, arguments); 468 | 469 | if (Ember.typeOf(definition.url) === 'function') { 470 | instance.url = definition.url; 471 | } else { 472 | instance.url = function(obj) { 473 | var id = obj.get('id'); 474 | if (id) { 475 | return definition.url.fmt(id); 476 | } 477 | }; 478 | } 479 | 480 | return instance; 481 | } 482 | }); 483 | 484 | Ember.Resource.HasManyNestedSchemaItem = Ember.Resource.HasManySchemaItem.extend({ 485 | fetchable: true, 486 | getValue: function(instance) { 487 | var data = this.data(instance); 488 | if (!data) return; 489 | data = Ember.getPath(data, this.get('path')); 490 | if (data === undefined || data === null) return data; 491 | data = Ember.copy(data); 492 | 493 | var options = { 494 | type: this.get('itemType'), 495 | content: data 496 | }; 497 | 498 | if (this.get('parse')) options.parse = this.get('parse'); 499 | 500 | return this.get('type').create(options); 501 | }, 502 | 503 | setValue: function(instance, value) { 504 | }, 505 | 506 | toJSON: function(instance) { 507 | var value = Ember.get(instance, this.name); 508 | return value ? value.toJSON() : value; 509 | } 510 | }); 511 | Ember.Resource.HasManyNestedSchemaItem.reopenClass({ 512 | create: function(name, schema) { 513 | var definition = schema[name]; 514 | 515 | var instance = this._super.apply(this, arguments); 516 | instance.set('path', definition.path || name); 517 | 518 | return instance; 519 | } 520 | }); 521 | 522 | Ember.Resource.HasManyInArraySchemaItem = Ember.Resource.HasManySchemaItem.extend({ 523 | fetchable: true, 524 | getValue: function(instance) { 525 | var data = this.data(instance); 526 | if (!data) return; 527 | data = Ember.getPath(data, this.get('path')); 528 | if (data === undefined || data === null) return data; 529 | 530 | 531 | return this.get('type').create({ 532 | type: this.get('itemType'), 533 | content: data.map(function(id) { return {id: id}; }) 534 | }); 535 | }, 536 | 537 | setValue: function(instance, value) { 538 | }, 539 | 540 | toJSON: function(instance) { 541 | var value = Ember.get(instance, this.name); 542 | return value ? value.mapProperty('id') : value; 543 | } 544 | }); 545 | Ember.Resource.HasManyInArraySchemaItem.reopenClass({ 546 | create: function(name, schema) { 547 | var definition = schema[name]; 548 | 549 | var instance = this._super.apply(this, arguments); 550 | instance.set('path', definition.path || name + '_ids'); 551 | 552 | return instance; 553 | } 554 | }); 555 | 556 | 557 | // Gives custom error handlers access to the resource object. 558 | // 1. `this` will refer to the Ember.Resource object. 559 | // 2. `resource` will be passed as the last argument 560 | // 561 | // function errorHandler() { 562 | // this; // the Ember.Resource 563 | // } 564 | // 565 | // function errorHandler(jqXHR, textStatus, errorThrown, resource) { 566 | // resource; // another way to reference the resource object 567 | // } 568 | // 569 | var errorHandlerWithContext = function(errorHandler, context) { 570 | return function() { 571 | var args = Array.prototype.slice.call(arguments, 0); 572 | args.push(context); 573 | errorHandler.apply(context, args); 574 | }; 575 | }; 576 | 577 | Ember.Resource.ajax = function(options) { 578 | options.dataType = options.dataType || 'json'; 579 | options.type = options.type || 'GET'; 580 | 581 | if(options.error) { 582 | options.error = errorHandlerWithContext(options.error, options); 583 | } else if(Ember.Resource.errorHandler) { 584 | options.error = errorHandlerWithContext(Ember.Resource.errorHandler, options); 585 | } 586 | 587 | return $.ajax(options); 588 | }; 589 | 590 | Ember.Resource.Lifecycle = { 591 | INITIALIZING: 0, 592 | UNFETCHED: 10, 593 | EXPIRING: 20, 594 | EXPIRED: 30, 595 | FETCHING: 40, 596 | FETCHED: 50, 597 | SAVING: 60, 598 | DESTROYING: 70, 599 | DESTROYED: 80, 600 | 601 | clock: Ember.Object.create({ 602 | now: new Date(), 603 | 604 | tick: function() { 605 | Ember.Resource.Lifecycle.clock.set('now', new Date()); 606 | }, 607 | 608 | start: function() { 609 | this.stop(); 610 | Ember.Resource.Lifecycle.clock.set('timer', setInterval(Ember.Resource.Lifecycle.clock.tick, 10000)); 611 | }, 612 | 613 | stop: function() { 614 | var timer = Ember.Resource.Lifecycle.clock.get('timer'); 615 | if (timer) { 616 | clearInterval(timer); 617 | } 618 | } 619 | }), 620 | 621 | classMixin: Ember.Mixin.create({ 622 | create: function(options, data) { 623 | options = options || {}; 624 | options.resourceState = Ember.Resource.Lifecycle.INITIALIZING; 625 | 626 | var instance = this._super.apply(this, arguments); 627 | 628 | if (Ember.get(instance, 'resourceState') === Ember.Resource.Lifecycle.INITIALIZING) { 629 | Ember.set(instance, 'resourceState', Ember.Resource.Lifecycle.UNFETCHED); 630 | } 631 | 632 | return instance; 633 | } 634 | }), 635 | 636 | prototypeMixin: Ember.Mixin.create({ 637 | expireIn: 60 * 5, 638 | resourceState: 0, 639 | autoFetch: true, 640 | 641 | init: function() { 642 | this._super.apply(this, arguments); 643 | 644 | var self = this; 645 | 646 | if(!Ember.Resource.SUPPORT_AUTOFETCH) { 647 | this.set('autoFetch', false); 648 | } 649 | 650 | var updateExpiry = function() { 651 | var expireAt = new Date(); 652 | expireAt.setSeconds(expireAt.getSeconds() + Ember.get(self, 'expireIn')); 653 | Ember.set(self, 'expireAt', expireAt); 654 | }; 655 | 656 | Ember.addListener(this, 'willFetch', this, function() { 657 | Ember.set(self, 'resourceState', Ember.Resource.Lifecycle.FETCHING); 658 | updateExpiry(); 659 | }); 660 | 661 | Ember.addListener(this, 'didFetch', this, function() { 662 | Ember.set(self, 'resourceState', Ember.Resource.Lifecycle.FETCHED); 663 | updateExpiry(); 664 | }); 665 | 666 | Ember.addListener(this, 'didFail', this, function() { 667 | Ember.set(self, 'resourceState', Ember.Resource.Lifecycle.UNFETCHED); 668 | updateExpiry(); 669 | }); 670 | 671 | var resourceStateBeforeSave; 672 | Ember.addListener(this, 'willSave', this, function() { 673 | resourceStateBeforeSave = Ember.get(self, 'resourceState'); 674 | Ember.set(self, 'resourceState', Ember.Resource.Lifecycle.SAVING); 675 | }); 676 | 677 | Ember.addListener(this, 'didSave', this, function() { 678 | Ember.set(self, 'resourceState', resourceStateBeforeSave || Ember.Resource.Lifecycle.UNFETCHED); 679 | }); 680 | }, 681 | 682 | isFetchable: Ember.computed('resourceState', function() { 683 | var state = Ember.get(this, 'resourceState'); 684 | return state == Ember.Resource.Lifecycle.UNFETCHED || state === Ember.Resource.Lifecycle.EXPIRED; 685 | }).cacheable(), 686 | 687 | isAutoFetchable: Ember.computed('isFetchable', 'autoFetch', function() { 688 | return this.get('isFetchable') && this.get('autoFetch'); 689 | }).cacheable(), 690 | 691 | isInitializing: Ember.computed('resourceState', function() { 692 | return (Ember.get(this, 'resourceState') || Ember.Resource.Lifecycle.INITIALIZING) === Ember.Resource.Lifecycle.INITIALIZING; 693 | }).cacheable(), 694 | 695 | isFetching: Ember.computed('resourceState', function() { 696 | return (Ember.get(this, 'resourceState')) === Ember.Resource.Lifecycle.FETCHING; 697 | }).cacheable(), 698 | 699 | isFetched: Ember.computed('resourceState', function() { 700 | return (Ember.get(this, 'resourceState')) === Ember.Resource.Lifecycle.FETCHED; 701 | }).cacheable(), 702 | 703 | isSavable: Ember.computed('resourceState', function() { 704 | var state = Ember.get(this, 'resourceState'); 705 | var unsavableState = [ 706 | Ember.Resource.Lifecycle.INITIALIZING, 707 | Ember.Resource.Lifecycle.FETCHING, 708 | Ember.Resource.Lifecycle.SAVING, 709 | Ember.Resource.Lifecycle.DESTROYING 710 | ]; 711 | 712 | return state && !unsavableState.contains(state); 713 | }).cacheable(), 714 | 715 | isSaving: Ember.computed('resourceState', function() { 716 | return (Ember.get(this, 'resourceState')) === Ember.Resource.Lifecycle.SAVING; 717 | }).cacheable(), 718 | 719 | scheduleFetch: function() { 720 | if (Ember.get(this, 'isAutoFetchable')) { 721 | Ember.run.next(this, this.fetch); 722 | } 723 | }, 724 | 725 | expire: function() { 726 | Ember.run.next(this, function() { 727 | Ember.set(this, 'expireAt', new Date()); 728 | Ember.Resource.Lifecycle.clock.tick(); 729 | }); 730 | }, 731 | 732 | updateIsExpired: Ember.observer(function() { 733 | var isExpired = Ember.get(this, 'resourceState') === Ember.Resource.Lifecycle.EXPIRED; 734 | if (isExpired) return true; 735 | 736 | var expireAt = Ember.get(this, 'expireAt'); 737 | if (expireAt) { 738 | var now = Ember.Resource.Lifecycle.clock.get('now'); 739 | isExpired = expireAt.getTime() <= now.getTime(); 740 | } 741 | 742 | var oldIsExpired = Ember.get(this, 'isExpired'); 743 | 744 | if (( isExpired && !oldIsExpired ) || 745 | ( (isExpired === false) && oldIsExpired)) { 746 | Ember.set(this, 'isExpired', isExpired); 747 | } 748 | }, 'Ember.Resource.Lifecycle.clock.now', 'expireAt', 'resourceState'), 749 | 750 | isExpired: Ember.computed(function(name, value) { 751 | if (value) { 752 | Ember.set(this, 'resourceState', Ember.Resource.Lifecycle.EXPIRED); 753 | } 754 | return value; 755 | }).cacheable() 756 | }) 757 | }; 758 | Ember.Resource.Lifecycle.clock.start(); 759 | 760 | Ember.Resource.reopen({ 761 | isEmberResource: true, 762 | 763 | updateWithApiData: function(json) { 764 | var data = Ember.get(this, 'data'); 765 | Ember.beginPropertyChanges(data); 766 | Ember.Resource.deepMerge(data, this.constructor.parse(json)); 767 | Ember.endPropertyChanges(data); 768 | }, 769 | 770 | willFetch: function() {}, 771 | didFetch: function() {}, 772 | willSave: function() {}, 773 | didSave: function() {}, 774 | didFail: function() {}, 775 | 776 | fetched: function() { 777 | if(!this._fetchDfd) { 778 | this._fetchDfd = $.Deferred(); 779 | } 780 | return this._fetchDfd; 781 | }, 782 | 783 | fetch: function(ajaxOptions) { 784 | var sideloads; 785 | if (!Ember.get(this, 'isFetchable')) return $.when(); 786 | 787 | var url = this.resourceURL(); 788 | 789 | if (!url) return; 790 | 791 | var self = this; 792 | 793 | if (this.deferedFetch && !Ember.get(this, 'isExpired')) return this.deferedFetch; 794 | 795 | self.willFetch.call(self); 796 | Ember.sendEvent(self, 'willFetch'); 797 | 798 | ajaxOptions = $.extend({}, ajaxOptions, { 799 | url: url, 800 | resource: this, 801 | operation: 'read' 802 | }); 803 | 804 | sideloads = this.constructor.sideloads; 805 | 806 | if(sideloads && sideloads.length !== 0) { 807 | ajaxOptions.data = {include: sideloads.join(",")}; 808 | } 809 | 810 | this.deferedFetch = Ember.Resource.ajax(ajaxOptions).done(function(json) { 811 | self.updateWithApiData(json); 812 | }); 813 | 814 | this.deferedFetch.fail(function() { 815 | self.didFail.call(self); 816 | Ember.sendEvent(self, 'didFail'); 817 | self.fetched().reject(); 818 | }); 819 | 820 | this.deferedFetch.done(function() { 821 | self.didFetch.call(self); 822 | Ember.sendEvent(self, 'didFetch'); 823 | self.fetched().resolve(); 824 | }); 825 | 826 | this.deferedFetch.always(function() { 827 | self.deferedFetch = null; 828 | }); 829 | 830 | return this.deferedFetch; 831 | }, 832 | 833 | resourceURL: function() { 834 | return this.constructor.resourceURL(this); 835 | }, 836 | 837 | // Turn this resource into a JSON object to be saved via AJAX. Override 838 | // this method to produce different syncing behavior. 839 | toJSON: function() { 840 | var json = {}; 841 | var schemaItem, path, value; 842 | for (var name in this.constructor.schema) { 843 | if (this.constructor.schema.hasOwnProperty(name)) { 844 | schemaItem = this.constructor.schema[name]; 845 | if (schemaItem instanceof Ember.Resource.AbstractSchemaItem) { 846 | path = schemaItem.get('path'); 847 | value = schemaItem.toJSON(this); 848 | if (value !== undefined) { 849 | Ember.Resource.deepSet(json, path, value); 850 | } 851 | } 852 | } 853 | } 854 | 855 | return json; 856 | }, 857 | 858 | isNew: Ember.computed('id', function() { 859 | return !Ember.get(this, 'id'); 860 | }).cacheable(), 861 | 862 | save: function(options) { 863 | options = options || {}; 864 | if (!Ember.get(this, 'isSavable')) return false; 865 | 866 | var ajaxOptions = { 867 | contentType: 'application/json', 868 | data: JSON.stringify(this.toJSON()), 869 | resource: this 870 | }; 871 | 872 | if (Ember.get(this, 'isNew')) { 873 | ajaxOptions.type = 'POST'; 874 | ajaxOptions.url = this.constructor.resourceURL(); 875 | ajaxOptions.operation = 'create'; 876 | } else { 877 | ajaxOptions.type = 'PUT'; 878 | ajaxOptions.url = this.resourceURL(); 879 | ajaxOptions.operation = 'update'; 880 | } 881 | 882 | var self = this; 883 | 884 | self.willSave.call(self); 885 | Ember.sendEvent(self, 'willSave'); 886 | 887 | var deferedSave = Ember.Resource.ajax(ajaxOptions); 888 | 889 | deferedSave.done(function(data, status, response) { 890 | var location = response.getResponseHeader('Location'); 891 | if (location) { 892 | var id = self.constructor.idFromURL(location); 893 | if (id) { 894 | Ember.set(self, 'id', id); 895 | } 896 | } 897 | 898 | if (options.update !== false && Ember.typeOf(data) === 'object') { 899 | self.updateWithApiData(data); 900 | } 901 | }); 902 | 903 | deferedSave.always(function() { 904 | self.didSave.call(self); 905 | Ember.sendEvent(self, 'didSave'); 906 | }); 907 | 908 | return deferedSave; 909 | }, 910 | 911 | destroy: function() { 912 | if(this.get('id')) { 913 | this.constructor.identityMap.remove(this.get('id')); 914 | } 915 | this._super(); 916 | }, 917 | 918 | destroyResource: function() { 919 | var previousState = Ember.get(this, 'resourceState'), self = this; 920 | Ember.set(this, 'resourceState', Ember.Resource.Lifecycle.DESTROYING); 921 | return Ember.Resource.ajax({ 922 | type: 'DELETE', 923 | operation: 'destroy', 924 | url: this.resourceURL(), 925 | resource: this 926 | }).done(function() { 927 | Ember.set(self, 'resourceState', Ember.Resource.Lifecycle.DESTROYED); 928 | self.destroy(); 929 | }).fail(function() { 930 | Ember.set(self, 'resourceState', previousState); 931 | }); 932 | } 933 | }, Ember.Resource.Lifecycle.prototypeMixin); 934 | 935 | expandSchema = function(schema) { 936 | for (var name in schema) { 937 | if (schema.hasOwnProperty(name)) { 938 | schema[name] = Ember.Resource.SchemaItem.create(name, schema); 939 | } 940 | } 941 | 942 | return schema; 943 | }; 944 | 945 | mergeSchemas = function(childSchema, parentSchema) { 946 | var schema = Ember.copy(parentSchema || {}); 947 | 948 | for (var name in childSchema) { 949 | if (childSchema.hasOwnProperty(name)) { 950 | if (schema.hasOwnProperty(name)) { 951 | throw("Schema item '" + name + "' is already defined"); 952 | } 953 | 954 | schema[name] = childSchema[name]; 955 | } 956 | } 957 | 958 | return schema; 959 | }; 960 | 961 | createSchemaProperties = function(schema) { 962 | var properties = {}, schemaItem; 963 | 964 | for (var propertyName in schema) { 965 | if (schema.hasOwnProperty(propertyName)) { 966 | properties[propertyName] = schema[propertyName].property(); 967 | } 968 | } 969 | 970 | return properties; 971 | }; 972 | 973 | Ember.Resource.reopenClass({ 974 | isEmberResource: true, 975 | schema: {}, 976 | 977 | baseClass: function() { 978 | if (this === Ember.Resource) { 979 | return null; 980 | } else { 981 | return this.baseResourceClass || this; 982 | } 983 | }, 984 | 985 | subclassFor: function(options, data) { 986 | return this; 987 | }, 988 | 989 | // Create an instance of this resource. If `options` includes an 990 | // `id`, first check the identity map and return the existing resource 991 | // with that ID if found. 992 | create: function(options, data) { 993 | data = data || {}; 994 | options = options || {}; 995 | 996 | var klass = this.subclassFor(options, data), idToRestore = options.id; 997 | 998 | if (klass === this) { 999 | var instance; 1000 | this.identityMap = this.identityMap || new Ember.Resource.IdentityMap(this.identityMapLimit); 1001 | 1002 | var id = data.id || options.id; 1003 | if (id && !options.skipIdentityMap) { 1004 | id = id.toString(); 1005 | instance = this.identityMap.get(id); 1006 | 1007 | if (!instance) { 1008 | instance = this._super.call(this, { data: data }); 1009 | this.identityMap.put(id, instance); 1010 | } else { 1011 | instance.updateWithApiData(data); 1012 | // ignore incoming resourceState and id arguments 1013 | delete options.resourceState; 1014 | delete options.id; 1015 | } 1016 | } else { 1017 | instance = this._super.call(this, { data: data }); 1018 | } 1019 | 1020 | delete options.data; 1021 | 1022 | Ember.beginPropertyChanges(instance); 1023 | var mixin = {}; 1024 | var hasMixin = false; 1025 | for (var name in options) { 1026 | if (options.hasOwnProperty(name)) { 1027 | if (this.schema[name]) { 1028 | instance.set(name, options[name]); 1029 | } else { 1030 | mixin[name] = options[name]; 1031 | hasMixin = true; 1032 | } 1033 | } 1034 | } 1035 | if (hasMixin) { 1036 | instance.reopen(mixin); 1037 | } 1038 | Ember.endPropertyChanges(instance); 1039 | 1040 | options.id = idToRestore; 1041 | return instance; 1042 | } else { 1043 | return klass.create(options, data); 1044 | } 1045 | }, 1046 | 1047 | // Parse JSON -- likely returned from an AJAX call -- into the 1048 | // properties for an instance of this resource. Override this method 1049 | // to produce different parsing behavior. 1050 | parse: function(json) { 1051 | return json; 1052 | }, 1053 | 1054 | // Define a resource class. 1055 | // 1056 | // Parameters: 1057 | // 1058 | // * `schema` -- the properties schema for the resource class 1059 | // * `url` -- either a function that returns the URL for syncing 1060 | // resources or a string. If the latter, a string of the form 1061 | // "/widgets" is turned into a function that returns "/widgets" if 1062 | // the Widget's ID is not present and "/widgets/{id}" if it is. 1063 | // * `parse` -- the function used to parse JSON returned from AJAX 1064 | // calls into the resource properties. By default, simply returns 1065 | // the JSON. 1066 | define: function(options) { 1067 | options = options || {}; 1068 | var schema = expandSchema(options.schema); 1069 | schema = mergeSchemas(schema, this.schema); 1070 | 1071 | var klass = this.extend(createSchemaProperties(schema), Ember.Resource.RemoteExpiry); 1072 | 1073 | var classOptions = { 1074 | schema: schema 1075 | }; 1076 | 1077 | if (this !== Ember.Resource) { 1078 | classOptions.baseResourceClass = this.baseClass() || this; 1079 | } 1080 | 1081 | if (options.url) { 1082 | classOptions.url = options.url; 1083 | } 1084 | 1085 | if (options.parse) { 1086 | classOptions.parse = options.parse; 1087 | } 1088 | 1089 | if (options.identityMapLimit) { 1090 | classOptions.identityMapLimit = options.identityMapLimit; 1091 | } 1092 | 1093 | if(options.sideloads) { 1094 | classOptions.sideloads = options.sideloads; 1095 | } 1096 | 1097 | klass.reopenClass(classOptions); 1098 | 1099 | return klass; 1100 | }, 1101 | 1102 | resourceURL: function(instance) { 1103 | if (Ember.typeOf(this.url) == 'function') { 1104 | return this.url(instance); 1105 | } else if (this.url) { 1106 | if (instance) { 1107 | var id = Ember.get(instance, 'id'); 1108 | if(!id) { 1109 | return this.url; 1110 | } 1111 | 1112 | if (id && (Ember.typeOf(id) !== 'number' || id > 0)) { 1113 | return this.url + '/' + id; 1114 | } 1115 | } else { 1116 | return this.url; 1117 | } 1118 | } 1119 | }, 1120 | 1121 | idFromURL: function(url) { 1122 | var regex; 1123 | if (!this.schema.id) return; 1124 | 1125 | if (this.schema.id.get('type') === Number) { 1126 | regex = /\/(\d+)(\.\w+)?$/; 1127 | } else { 1128 | regex = /\/([^\/\.]+)(\.\w+)?$/; 1129 | } 1130 | 1131 | var match = (url || '').match(regex); 1132 | if (match) { 1133 | return match[1]; 1134 | } 1135 | } 1136 | }, Ember.Resource.Lifecycle.classMixin); 1137 | 1138 | Ember.ResourceCollection = Ember.ArrayProxy.extend(Ember.Resource.RemoteExpiry, { 1139 | isEmberResourceCollection: true, 1140 | type: Ember.required(), 1141 | 1142 | fetched: function() { 1143 | if(!this._fetchDfd) { 1144 | this._fetchDfd = $.Deferred(); 1145 | } 1146 | return this._fetchDfd; 1147 | }, 1148 | 1149 | fetch: function(ajaxOptions) { 1150 | if (!Ember.get(this, 'isFetchable') || Ember.get(this, 'prePopulated')) return $.when(); 1151 | 1152 | var self = this; 1153 | 1154 | if (this.deferedFetch && !Ember.get(this, 'isExpired')) return this.deferedFetch; 1155 | 1156 | Ember.sendEvent(self, 'willFetch'); 1157 | 1158 | this.deferedFetch = this._fetch(function(json) { 1159 | Ember.set(self, 'content', self.parse(json)); 1160 | }, ajaxOptions); 1161 | 1162 | this.deferedFetch.always(function() { 1163 | Ember.sendEvent(self, 'didFetch'); 1164 | self.fetched().resolve(); 1165 | self.deferredFetch = null; 1166 | }); 1167 | return this.deferedFetch; 1168 | }, 1169 | _resolveType: function() { 1170 | if (isString(this.type)) { 1171 | var type = Ember.getPath(this.type); 1172 | if (type) this.type = type; 1173 | } 1174 | }, 1175 | _fetch: function(callback, ajaxOptions) { 1176 | this._resolveType(); 1177 | ajaxOptions = $.extend({}, ajaxOptions, { 1178 | url: this.resolveUrl(), 1179 | resource: this, 1180 | operation: 'read', 1181 | success: callback 1182 | }); 1183 | return Ember.Resource.ajax(ajaxOptions); 1184 | }, 1185 | resolveUrl: function() { 1186 | return this.get('url') || this.type.resourceURL(); 1187 | }, 1188 | instantiateItems: function(items) { 1189 | this._resolveType(); 1190 | return items.map(function(item) { 1191 | if (item instanceof this.type) { 1192 | return item; 1193 | } else { 1194 | return this.type.create({}, item); 1195 | } 1196 | }, this); 1197 | }, 1198 | parse: function(json) { 1199 | this._resolveType(); 1200 | if (Ember.typeOf(this.type.parse) == 'function') { 1201 | return json.map(this.type.parse); 1202 | } 1203 | else { 1204 | return json; 1205 | } 1206 | }, 1207 | 1208 | length: Ember.computed('content.length', 'resourceState', 'isExpired', function() { 1209 | var content = Ember.get(this, 'content'); 1210 | var length = content ? Ember.get(content, 'length') : 0; 1211 | if (length === 0 || Ember.get(this, 'isExpired')) this.scheduleFetch(); 1212 | return length; 1213 | }).cacheable(), 1214 | 1215 | content: Ember.computed(function(name, value) { 1216 | if (arguments.length === 2) { // setter 1217 | return this.instantiateItems(value); 1218 | } 1219 | }).cacheable(), 1220 | 1221 | autoFetchOnExpiry: Ember.observer(function() { 1222 | if (Ember.get(this, 'isAutoFetchable') && Ember.get(this, 'isExpired') && Ember.get(this, 'hasArrayObservers')) { 1223 | this.fetch(); 1224 | } 1225 | }, 'isExpired', 'hasArrayObservers'), 1226 | 1227 | toJSON: function() { 1228 | return this.map(function(item) { 1229 | return item.toJSON(); 1230 | }); 1231 | } 1232 | }, Ember.Resource.Lifecycle.prototypeMixin); 1233 | 1234 | Ember.ResourceCollection.reopenClass({ 1235 | isEmberResourceCollection: true, 1236 | identityMapLimit: Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT * 5, 1237 | create: function(options) { 1238 | options = options || {}; 1239 | var content = options.content; 1240 | delete options.content; 1241 | 1242 | options.prePopulated = !! content; 1243 | 1244 | var instance; 1245 | 1246 | if (!options.prePopulated && options.url) { 1247 | this.identityMap = this.identityMap || new Ember.Resource.IdentityMap(this.identityMapLimit); 1248 | var identity = [options.type, options.url]; 1249 | instance = this.identityMap.get(identity) || this._super.call(this, options); 1250 | this.identityMap.put(identity, instance); 1251 | } 1252 | 1253 | if (!instance) { 1254 | instance = this._super.call(this, options); 1255 | 1256 | if (content) { 1257 | Ember.set(instance, 'content', instance.parse(content)); 1258 | } 1259 | } 1260 | 1261 | return instance; 1262 | } 1263 | }, Ember.Resource.Lifecycle.classMixin); 1264 | }(this)); 1265 | -------------------------------------------------------------------------------- /src/identity_map.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | Ember.Resource.IdentityMap = function(limit) { 3 | this.cache = new LRUCache(limit || Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT); 4 | }; 5 | 6 | Ember.Resource.IdentityMap.prototype = { 7 | get: function() { 8 | return LRUCache.prototype.get.apply(this.cache, arguments); 9 | }, 10 | 11 | put: function() { 12 | return LRUCache.prototype.put.apply(this.cache, arguments); 13 | }, 14 | 15 | remove: function() { 16 | return LRUCache.prototype.remove.apply(this.cache, arguments); 17 | }, 18 | 19 | clear: function() { 20 | return LRUCache.prototype.removeAll.apply(this.cache, arguments); 21 | }, 22 | 23 | size: function() { 24 | return this.cache.size; 25 | }, 26 | 27 | limit: function() { 28 | return this.cache.limit; 29 | } 30 | 31 | }; 32 | 33 | Ember.Resource.IdentityMap.DEFAULT_IDENTITY_MAP_LIMIT = 500; 34 | 35 | }()); 36 | -------------------------------------------------------------------------------- /src/remote_expiry.js: -------------------------------------------------------------------------------- 1 | (function(exports) { 2 | 3 | var Ember = exports.Ember, NullTransport = { 4 | subscribe: Ember.K, 5 | unsubscribe: Ember.K 6 | }; 7 | 8 | Ember.Resource.PushTransport = NullTransport; 9 | 10 | var RemoteExpiry = Ember.Mixin.create({ 11 | init: function() { 12 | var ret = this._super(), 13 | self = this, 14 | remoteExpiryScope = this.get('remoteExpiryKey'); 15 | 16 | this.set('_subscribedForExpiry', false); 17 | 18 | if(!remoteExpiryScope) { 19 | return ret; 20 | } 21 | 22 | Ember.addListener(this, 'didFetch', this, function() { 23 | self.subscribeForExpiry(); 24 | }); 25 | 26 | return ret; 27 | }, 28 | 29 | subscribeForExpiry: function() { 30 | var remoteExpiryScope = this.get('remoteExpiryKey'), 31 | self = this; 32 | 33 | if(!remoteExpiryScope) { 34 | return; 35 | } 36 | 37 | if(this.get('_subscribedForExpiry')) { 38 | return; 39 | } 40 | 41 | Ember.Resource.PushTransport.subscribe(remoteExpiryScope, function(message) { 42 | self.updateExpiry(message); 43 | }); 44 | 45 | this.set('_subscribedForExpiry', true); 46 | }, 47 | 48 | updateExpiry: function(message) { 49 | var updatedAt = message && message.updatedAt; 50 | if(!updatedAt) return; 51 | if(this.stale(updatedAt)) { 52 | this.set('expiryUpdatedAt', updatedAt); 53 | if(this.get('remoteExpiryAutoFetch')) { 54 | this.set('isExpired', true); 55 | this.fetch(); 56 | } else { 57 | this.expire(); 58 | } 59 | } 60 | }, 61 | 62 | stale: function(updatedAt) { 63 | return !this.get('expiryUpdatedAt') || (+this.get('expiryUpdatedAt') < +updatedAt); 64 | } 65 | }); 66 | 67 | Ember.Resource.RemoteExpiry = RemoteExpiry; 68 | 69 | }(this)); 70 | -------------------------------------------------------------------------------- /src/vendor/lru.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most 3 | * recently used items while discarding least recently used items when its limit 4 | * is reached. 5 | * 6 | * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson 7 | * See README.md for details. 8 | * 9 | * Illustration of the design: 10 | * 11 | * entry entry entry entry 12 | * ______ ______ ______ ______ 13 | * | head |.newer => | |.newer => | |.newer => | tail | 14 | * | A | | B | | C | | D | 15 | * |______| <= older.|______| <= older.|______| <= older.|______| 16 | * 17 | * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added 18 | */ 19 | function LRUCache (limit) { 20 | // Current size of the cache. (Read-only). 21 | this.size = 0; 22 | // Maximum number of items this cache can hold. 23 | this.limit = limit; 24 | this._keymap = {}; 25 | } 26 | 27 | /** 28 | * Put into the cache associated with . Returns the entry which was 29 | * removed to make room for the new entry. Otherwise undefined is returned 30 | * (i.e. if there was enough room already). 31 | */ 32 | LRUCache.prototype.put = function(key, value) { 33 | var entry = {key:key, value:value}; 34 | // Note: No protection agains replacing, and thus orphan entries. By design. 35 | this._keymap[key] = entry; 36 | if (this.tail) { 37 | // link previous tail to the new tail (entry) 38 | this.tail.newer = entry; 39 | entry.older = this.tail; 40 | } else { 41 | // we're first in -- yay 42 | this.head = entry; 43 | } 44 | // add new entry to the end of the linked list -- it's now the freshest entry. 45 | this.tail = entry; 46 | if (this.size === this.limit) { 47 | // we hit the limit -- remove the head 48 | return this.shift(); 49 | } else { 50 | // increase the size counter 51 | this.size++; 52 | } 53 | } 54 | 55 | /** 56 | * Purge the least recently used (oldest) entry from the cache. Returns the 57 | * removed entry or undefined if the cache was empty. 58 | * 59 | * If you need to perform any form of finalization of purged items, this is a 60 | * good place to do it. Simply override/replace this function: 61 | * 62 | * var c = new LRUCache(123); 63 | * c.shift = function() { 64 | * var entry = LRUCache.prototype.shift.call(this); 65 | * doSomethingWith(entry); 66 | * return entry; 67 | * } 68 | */ 69 | LRUCache.prototype.shift = function() { 70 | // todo: handle special case when limit == 1 71 | var entry = this.head; 72 | if (entry) { 73 | if (this.head.newer) { 74 | this.head = this.head.newer; 75 | this.head.older = undefined; 76 | } else { 77 | this.head = undefined; 78 | } 79 | // Remove last strong reference to and remove links from the purged 80 | // entry being returned: 81 | entry.newer = entry.older = undefined; 82 | // delete is slow, but we need to do this to avoid uncontrollable growth: 83 | delete this._keymap[entry.key]; 84 | } 85 | return entry; 86 | } 87 | 88 | /** 89 | * Get and register recent use of . Returns the value associated with 90 | * or undefined if not in cache. 91 | */ 92 | LRUCache.prototype.get = function(key, returnEntry) { 93 | // First, find our cache entry 94 | var entry = this._keymap[key]; 95 | if (entry === undefined) return; // Not cached. Sorry. 96 | // As was found in the cache, register it as being requested recently 97 | if (entry === this.tail) { 98 | // Already the most recenlty used entry, so no need to update the list 99 | return entry.value; 100 | } 101 | // HEAD--------------TAIL 102 | // <.older .newer> 103 | // <--- add direction -- 104 | // A B C E 105 | if (entry.newer) { 106 | if (entry === this.head) 107 | this.head = entry.newer; 108 | entry.newer.older = entry.older; // C <-- E. 109 | } 110 | if (entry.older) 111 | entry.older.newer = entry.newer; // C. --> E 112 | entry.newer = undefined; // D --x 113 | entry.older = this.tail; // D. --> E 114 | if (this.tail) 115 | this.tail.newer = entry; // E. <-- D 116 | this.tail = entry; 117 | return returnEntry ? entry : entry.value; 118 | } 119 | 120 | // ---------------------------------------------------------------------------- 121 | // Following code is optional and can be removed without breaking the core 122 | // functionality. 123 | 124 | /** 125 | * Check if is in the cache without registering recent use. Feasible if 126 | * you do not want to chage the state of the cache, but only "peek" at it. 127 | * Returns the entry associated with if found, or undefined if not found. 128 | */ 129 | LRUCache.prototype.find = function(key) { 130 | return this._keymap[key]; 131 | } 132 | 133 | /** 134 | * Update the value of entry with . Returns the old value, or undefined if 135 | * entry was not in the cache. 136 | */ 137 | LRUCache.prototype.set = function(key, value) { 138 | var oldvalue, entry = this.get(key, true); 139 | if (entry) { 140 | oldvalue = entry.value; 141 | entry.value = value; 142 | } else { 143 | oldvalue = this.put(key, value); 144 | if (oldvalue) oldvalue = oldvalue.value; 145 | } 146 | return oldvalue; 147 | } 148 | 149 | /** 150 | * Remove entry from cache and return its value. Returns undefined if not 151 | * found. 152 | */ 153 | LRUCache.prototype.remove = function(key) { 154 | var entry = this._keymap[key]; 155 | if (!entry) return; 156 | delete this._keymap[entry.key]; // need to do delete unfortunately 157 | if (entry.newer && entry.older) { 158 | // relink the older entry with the newer entry 159 | entry.older.newer = entry.newer; 160 | entry.newer.older = entry.older; 161 | } else if (entry.newer) { 162 | // remove the link to us 163 | entry.newer.older = undefined; 164 | // link the newer entry to head 165 | this.head = entry.newer; 166 | } else if (entry.older) { 167 | // remove the link to us 168 | entry.older.newer = undefined; 169 | // link the newer entry to head 170 | this.tail = entry.older; 171 | } else {// if(entry.older === undefined && entry.newer === undefined) { 172 | this.head = this.tail = undefined; 173 | } 174 | 175 | this.size--; 176 | return entry.value; 177 | } 178 | 179 | /** Removes all entries */ 180 | LRUCache.prototype.removeAll = function() { 181 | // This should be safe, as we never expose strong refrences to the outside 182 | this.head = this.tail = undefined; 183 | this.size = 0; 184 | this._keymap = {}; 185 | } 186 | 187 | /** 188 | * Return an array containing all keys of entries stored in the cache object, in 189 | * arbitrary order. 190 | */ 191 | if (typeof Object.keys === 'function') { 192 | LRUCache.prototype.keys = function() { return Object.keys(this._keymap); } 193 | } else { 194 | LRUCache.prototype.keys = function() { 195 | var keys = []; 196 | for (var k in this._keymap) keys.push(k); 197 | return keys; 198 | } 199 | } 200 | 201 | /** 202 | * Call `fun` for each entry. Starting with the newest entry if `desc` is a true 203 | * value, otherwise starts with the oldest (head) enrty and moves towards the 204 | * tail. 205 | * 206 | * `fun` is called with 3 arguments in the context `context`: 207 | * `fun.call(context, Object key, Object value, LRUCache self)` 208 | */ 209 | LRUCache.prototype.forEach = function(fun, context, desc) { 210 | if (context === true) { desc = true; context = undefined; } 211 | else if (typeof context !== 'object') context = this; 212 | if (desc) { 213 | var entry = this.tail; 214 | while (entry) { 215 | fun.call(context, entry.key, entry.value, this); 216 | entry = entry.older; 217 | } 218 | } else { 219 | var entry = this.head; 220 | while (entry) { 221 | fun.call(context, entry.key, entry.value, this); 222 | entry = entry.newer; 223 | } 224 | } 225 | } 226 | 227 | /** Returns a JSON (array) representation */ 228 | LRUCache.prototype.toJSON = function() { 229 | var s = [], entry = this.head; 230 | while (entry) { 231 | s.push({key:entry.key.toJSON(), value:entry.value.toJSON()}); 232 | entry = entry.newer; 233 | } 234 | return s; 235 | } 236 | 237 | /** Returns a String representation */ 238 | LRUCache.prototype.toString = function() { 239 | var s = '', entry = this.head; 240 | while (entry) { 241 | s += String(entry.key)+':'+entry.value; 242 | if (entry = entry.newer) 243 | s += ' < '; 244 | } 245 | return s; 246 | } 247 | 248 | // Export ourselves 249 | if (typeof this === 'object') this.LRUCache = LRUCache; 250 | --------------------------------------------------------------------------------