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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | 119x 240x 1x 51x 37x 14x 50x 50x 12x 38x 3x 2x 52x 125x 124x 1x 273x 58x 59x 6x 6x 6x 6x 6x 2x 2x 2x 2x 4x 4x 4x 4x 4x 26x 12x 12x 1x 11x 14x 14x 14x 13x 13x 1x 1x 14x 14x 14x 14x 14x 14x 5x 5x 5x 5x 5x 9x 9x 9x 9x 9x 11x 11x 7x 11x 11x 9x 11x 11x 4x 4x 4x 4x 7x 7x 7x 7x 7x 12x 1x 1x 11x 11x 11x 5x 11x 11x 11x 6x 6x 3x 6x 6x 6x 5x 5x 3x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 2x 2x 3x 3x 3x | // @flow import { observable, action, ObservableMap, computed, runInAction, toJS } from 'mobx' import Collection from './Collection' import { uniqueId, isString, debounce } from 'lodash' import apiClient from './apiClient' import Request from './Request' import ErrorObject from './ErrorObject' import type { OptimisticId, Id, Label, DestroyOptions, SaveOptions, CreateOptions } from './types' export default class Model { @observable request: ?Request = null @observable error: ?ErrorObject = null attributes: ObservableMap optimisticId: OptimisticId = uniqueId('i_') collection: ?Collection<*> = null constructor (attributes: { [key: string]: any } = {}) { this.attributes = observable.map(attributes) } /** * Returns a JSON representation * of the model */ toJS () { return toJS(this.attributes) } /** * Determine what attribute do you use * as a primary id * * @abstract */ get primaryKey (): string { return 'id' } /** * Return the base url used in * the `url` method * * @abstract */ urlRoot () { throw new Error('`url` method not implemented') } /** * Return the url for this given REST resource */ url (): string { let urlRoot if (this.collection) { urlRoot = this.collection.url() } else { urlRoot = this.urlRoot() } Iif (!urlRoot) { throw new Error('Either implement `urlRoot` or assign a collection') } if (this.isNew) { return urlRoot } else { return `${urlRoot}/${this.get(this.primaryKey)}` } } /** * 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 resource is new or not * * We determine this asking if it contains * the `primaryKey` attribute (set by the server). */ @computed get isNew (): boolean { return !this.has(this.primaryKey) } /** * Get the attribute from the model. * * Since we want to be sure changes on * the schema don't fail silently we * throw an error if the field does not * exist. * * If you want to deal with flexible schemas * use `has` to check wether the field * exists. */ get (attribute: string): any { if (this.has(attribute)) { return this.attributes.get(attribute) } throw new Error(`Attribute "${attribute}" not found`) } /** * Returns whether the given field exists * for the model. */ has (attribute: string): boolean { return this.attributes.has(attribute) } /** * Get an id from the model. It will use either * the backend assigned one or the client. */ get id (): Id { return this.has(this.primaryKey) ? this.get(this.primaryKey) : this.optimisticId } /** * Merge the given attributes with * the current ones */ @action set (data: {}): void { this.attributes.merge(data) } /** * Fetches the model from the backend. */ @action async fetch (options: { data?: {} } = {}): Promise<void> { const label: Label = 'fetching' const { abort, promise } = apiClient().get(this.url(), options.data) this.request = new Request(label, abort, 0) let data 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) this.request = null this.error = null }) return data } /** * Saves the resource on the backend. * * If the item has a `primaryKey` it updates it, * otherwise it creates the new resource. * * It supports optimistic and patch updates. * * TODO: Add progress */ @action async save ( attributes: {}, { optimistic = true, patch = true }: SaveOptions = {} ): Promise<*> { if (!this.has(this.primaryKey)) { this.set(Object.assign({}, attributes)) if (this.collection) { return this.collection.create(this, { optimistic }) } else { return this._create(attributes, { optimistic }) } } let newAttributes let data const label: Label = 'updating' const originalAttributes = this.attributes.toJS() if (patch) { newAttributes = Object.assign({}, originalAttributes, attributes) data = Object.assign({}, attributes) } else { newAttributes = Object.assign({}, attributes) data = Object.assign({}, originalAttributes, attributes) } const onProgress = debounce(function onProgress (progress) { if (optimistic && this.request) { this.request.progress = progress } }, 300) const { promise, abort } = apiClient().put(this.url(), data, { method: patch ? 'PATCH' : 'PUT', onProgress }) if (optimistic) this.set(newAttributes) this.request = new Request(label, abort, 0) let response try { response = await promise } catch (body) { runInAction('save-fail', () => { this.request = null this.set(originalAttributes) this.error = new ErrorObject(label, body) }) throw isString(body) ? new Error(body) : body } runInAction('save-done', () => { this.request = null this.error = null this.set(response) }) return response } /** * Internal method that takes care of creating a model that does * not belong to a collection */ async _create ( attributes: {}, { optimistic = true }: CreateOptions = {} ): Promise<*> { const label: Label = 'creating' const onProgress = debounce(function onProgress (progress) { Iif (optimistic && this.request) { this.request.progress = progress } }, 300) const { abort, promise } = apiClient().post(this.url(), attributes, { onProgress }) if (optimistic) { this.request = new Request(label, abort, 0) } let data: {} try { data = await promise } catch (body) { runInAction('create-error', () => { this.error = new ErrorObject(label, body) this.request = null }) throw body } runInAction('create-done', () => { this.set(data) this.request = null this.error = null }) return data } /** * Destroys the resurce on the client and * requests the backend to delete it there * too */ @action async destroy ({ optimistic = true }: DestroyOptions = {}): Promise<*> { if (!this.has(this.primaryKey) && this.collection) { this.collection.remove([this.optimisticId]) return Promise.resolve() } const label: Label = 'destroying' const { promise, abort } = apiClient().del(this.url()) if (optimistic && this.collection) { this.collection.remove([this.id]) } this.request = new Request(label, abort, 0) try { await promise } catch (body) { runInAction('destroy-fail', () => { if (optimistic && this.collection) { this.collection.add([this.attributes.toJS()]) } this.error = new ErrorObject(label, body) this.request = null }) throw body } runInAction('destroy-done', () => { if (!optimistic && this.collection) { this.collection.remove([this.id]) } this.request = null this.error = null }) return null } /** * 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 } } |