1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 | 93x 48x 3x 2x 2x 100x 68x 128x 2x 2x 2x 2x 111x 111x 111x 13x 13x 13x 13x 102x 106x 100x 100x 101x 107x 107x 107x 111x 111x 111x 111x 8x 8x 8x 5x 4x 5x 8x 8x 6x 6x 8x 8x 8x 3x 3x 2x 3x 3x 3x 5x 5x 4x 4x 1x 5x 5x 5x 4x 4x 4x 4x 4x 1x 1x 1x 1x 3x 3x 2x 2x 2x 4x 4x 4x 4x 4x 1x 1x 1x 1x 3x 3x 3x | // @flow import { observable, action, IObservableArray, runInAction, toJS } from 'mobx' import Model from './Model' import { isEmpty, filter, isMatch, find, difference, debounce, map, last } from 'lodash' import ErrorObject from './ErrorObject' import Request from './Request' import apiClient from './apiClient' import type { Label, CreateOptions, SetOptions, Id } from './types' export default class Collection<T: Model> { @observable request: ?Request = null @observable error: ?ErrorObject = null @observable models: IObservableArray<T> = [] constructor (data: Array<{ [key: string]: any }> = []) { this.set(data) } /** * Returns the URL where the model's resource would be located on the server. * * @abstract */ url (): string { throw new Error('You must implement this method') } /** * Specifies the model class for that collection */ model (): Class<*> { return Model } /** * Returns a JSON representation * of the collection */ toJS () { return toJS(this.models) } /** * Returns a shallow array representation * of the collection */ toArray () { return this.models.slice() } /** * Questions whether the request exists * and matches a certain label */ isRequest (label: Label): boolean { if (!this.request) return false return this.request.label === label } /** * Wether the collection is empty */ isEmpty (): boolean { return isEmpty(this.models) } /** * Gets the ids of all the items in the collection */ _ids (): Array<Id> { return map(this.models, item => item.id).filter(Boolean) } /** * Get a resource at a given position */ at (index: number): ?T { return this.models[index] } /** * Get a resource with the given id or uuid */ get (id: Id): ?T { return this.models.find(item => item.id === id) } /** * The whinny version of the `get` method */ mustGet (id: Id): T { const model = this.get(id) if (!model) throw Error(`Invariant: Model must be found with id: ${id}`) return model } /** * Get resources matching criteria */ filter (query: { [key: string]: any } = {}): Array<T> { return filter(this.models, ({ attributes }) => { return isMatch(attributes.toJS(), query) }) } /** * Finds an element with the given matcher */ find (query: { [key: string]: mixed }): ?T { return find(this.models, ({ attributes }) => { return isMatch(attributes.toJS(), query) }) } /** * The whinny version of `find` */ mustFind (query: { [key: string]: mixed }): T { const model = this.find(query) if (!model) { const conditions = JSON.stringify(query) throw Error(`Invariant: Model must be found with: ${conditions}`) } return model } /** * Adds a collection of models. * Returns the added models. */ @action add (data: Array<{ [key: string]: any }>): Array<T> { const models = data.map(d => this.build(d)) this.models.push(...models) return models } /** * Removes the model with the given ids or uuids */ @action remove (ids: Array<Id>): void { ids.forEach(id => { const model = this.get(id) Iif (!model) return this.models.splice(this.models.indexOf(model), 1) }) } /** * Sets the resources into the collection. * * You can disable adding, changing or removing. */ @action set ( resources: Array<{ [key: string]: any }>, { add = true, change = true, remove = true }: SetOptions = {} ): void { if (remove) { const ids = resources.map(r => r.id) const toRemove = difference(this._ids(), ids) if (toRemove.length) this.remove(toRemove) } resources.forEach(resource => { const model = this.get(resource.id) if (model && change) model.set(resource) if (!model && add) this.add([resource]) }) } /** * Creates a new model instance with the given attributes */ build (attributes: { [key: string]: any } = {}): T { const ModelClass = this.model() const model = new ModelClass(attributes) model.collection = this return model } /** * Creates the model and saves it on the backend * * The default behaviour is optimistic but this * can be tuned. */ @action async create ( attributesOrModel: { [key: string]: any } | Model, { optimistic = true }: CreateOptions = {} ): Promise<*> { let model let attributes = attributesOrModel instanceof Model ? attributesOrModel.attributes.toJS() : attributesOrModel const label: Label = 'creating' const onProgress = debounce(function onProgress (progress) { if (optimistic && model.request) { model.request.progress = progress } Iif (this.request) { this.request.progress = progress } }, 300) const { abort, promise } = apiClient().post(this.url(), attributes, { onProgress }) if (optimistic) { model = attributesOrModel instanceof Model ? attributesOrModel : last(this.add([attributesOrModel])) model.request = new Request(label, abort, 0) } this.request = new Request(label, abort, 0) let data: {} try { data = await promise } catch (body) { runInAction('create-error', () => { if (model) { this.remove([model.id]) } this.error = new ErrorObject(label, body) this.request = null }) throw body } runInAction('create-done', () => { if (model) { model.set(data) model.request = null } else { this.add([data]) } this.request = null this.error = null }) return data } /** * Fetches the models from the backend. * * It uses `set` internally so you can * use the options to disable adding, changing * or removing. */ @action async fetch (options: SetOptions = {}): Promise<void> { const label: Label = 'fetching' const { abort, promise } = apiClient().get(this.url(), options.data) this.request = new Request(label, abort, 0) let data: Array<{ [key: string]: any }> try { data = await promise } catch (body) { runInAction('fetch-error', () => { this.error = new ErrorObject(label, body) this.request = null }) throw body } runInAction('fetch-done', () => { this.set(data, options) this.request = null this.error = null }) return data } /** * Call an RPC action for all those * non-REST endpoints that you may have in * your API. */ @action async rpc (method: string, body?: {}): Promise<*> { const label: Label = 'updating' // TODO: Maybe differentiate? const { promise, abort } = apiClient().post( `${this.url()}/${method}`, body || {} ) this.request = new Request(label, abort, 0) let response try { response = await promise } catch (body) { runInAction('accept-fail', () => { this.request = null this.error = new ErrorObject(label, body) }) throw body } this.request = null this.error = null return response } } |