all files / documents/database/operations/internal/ save.js

100% Statements 25/25
100% Branches 4/4
100% Functions 6/6
100% Lines 23/23
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                                                                       
import Ember from 'ember';
import Operation from './operation';
import DocumentsError from 'documents/util/error';
 
const {
  RSVP: { resolve, reject },
} = Ember;
 
export default class InternalDocumentSaveOperation extends Operation {
 
  validateUniqueness() {
    let internal = this.internal;
    let id = internal.getId();
    let existing = this.db._internalDocumentWithId(id);
    if(!existing || existing === internal) {
      return;
    }
    return reject(new DocumentsError({
      error: 'conflict',
      reason: 'Document update conflict'
    }));
  }
 
  willSave() {
    this.withPropertyChanges(changed => this.state.onSaving(changed));
    return this.internal.serialize('document');
  }
 
  save(doc) {
    return this.docs.save(doc);
  }
 
  didSave(json) {
    this.withPropertyChanges(changed => {
      this.internal.deserializeSaved(json, changed);
      this.state.onSaved(changed);
    });
    this.db._storeSavedInternalDocument(this.internal);
    this.resolve();
  }
 
  saveDidFail(err) {
    this.withPropertyChanges(changed => {
      this.state.onError(err, changed);
    });
    this.reject(err);
  }
 
  invoke() {
    return resolve()
      .then(() => this.validateUniqueness())
      .then(() => this.willSave())
      .then(doc => this.save(doc))
      .then(json => this.didSave(json), err => this.saveDidFail(err));
  }
 
}