How to use the fast-json-patch.observe function in fast-json-patch

To help you get started, we’ve selected a few fast-json-patch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github FabricLabs / fabric / types / transition.js View on Github external
_applyTo (state) {
    if (!state) throw new Error('State must be provided.');
    if (!(state instanceof Entity)) throw new Error('State not of known Entity type.');

    let instance = Object.assign({}, state);
    let observer = monitor.observe(instance);

    try {
      monitor.applyPatch(instance, this._state.changes);
    } catch (E) {
      console.error('Could not apply changes:', E);
    }

    let changes = monitor.generate(observer);
    // console.log('changes:', changes);
    return instance;
  }
github freeCodeCamp / meeting-for-good / client / components / AvailabilityGrid / AvailabilityGrid.js View on Github external
async submitAvailability() {
    const { curUser } = this.props;
    const { grid, event } = this.state;
    // construct the avaqilabily for the cur user from grid
    const availabilityCurUserinQuarters = AvaliabilityCurUserFromGrid(grid, curUser);
    // need to call the full event to edit... since he dosn't have the
    // info that maybe have a guest "deleted"
    try {
      const eventFull = await loadEvent(event._id, true);
      const observerEvent = jsonpatch.observe(eventFull);
      // find for curUser at the array depends if is a participant
      // yet or not
      const curParticipant =
        isCurParticipantUpsert(curUser, eventFull, availabilityCurUserinQuarters.length);
      // because the patch jsonpatch dosent work as espected when you have a arrays of arrays
      // we need to generate a patch to delete all availability and then add ther availability again
      // then merge both patchs arrays.
      curParticipant.availability = [];
      const patchforDelete = jsonpatch.generate(observerEvent);
      curParticipant.availability = availabilityReducer(availabilityCurUserinQuarters);
      const patchesforAdd = jsonpatch.generate(observerEvent);
      const patches = _.concat(patchforDelete, patchesforAdd);
      await this.props.submitAvail(patches);
    } catch (err) {
      console.log('err at submit avail', err);
    }
github colyseus / colyseus / test / benchmark / patch.js View on Github external
var obj2 = new ComplexState();
var state2 = JSON.parse(JSON.stringify(obj2.toJSON()))
suite.add('using json', function() {
  for (var i=0; i<4; i++) {
    obj2.objs[0].hp--;
    obj2.objs[2].hp--;
    obj2.teams[i].score++;
    var newState = JSON.parse(JSON.stringify(obj2.toJSON()))
    var diff = msgpack.encode( jsonpatch.compare(state2, newState) )
    state2 = newState
  }
  this.bytes = diff.length;
});

var obj3 = new PlainState();
var observer = jsonpatch.observe(obj3)
suite.add('using plain + observe', function() {
  for (var i=0; i<4; i++) {
    obj3.objs[0].hp--;
    obj3.objs[2].hp--;
    obj3.teams[i].score++;
    var diff = msgpack.encode( jsonpatch.generate(observer) )
  }
  this.bytes = diff.length;
})

var obj4 = new ComplexState();
var obj4state = JSON.parse(JSON.stringify(obj4.toJSON()))
var observer2 = jsonpatch.observe(obj4state);
suite.add('using complex + observe', function() {
  for (var i=0; i<4; i++) {
    obj4.objs[0].hp--;
github DefinitelyTyped / DefinitelyTyped / types / fast-json-patch / fast-json-patch-tests.ts View on Github external
var myobj: {
  firstName: string,
  contactDetails: {
    phoneNumbers: string[]
  }
} = { firstName: "Albert", contactDetails: { phoneNumbers: [] } };
var patches: jsonpatch.Patch[] = [
  { op: "replace", path: "/firstName", value: "Joachim" },
  { op: "add", path: "/lastName", value: "Wester" },
  { op: "add", path: "/contactDetails/phoneNumbers/0", value: { number: "555-123" } }
];
jsonpatch.apply(myobj, patches);

var myobj2 = { firstName: "Joachim", lastName: "Wester", contactDetails: { phoneNumbers: [{ number: "555-123" }] } };
var observer = jsonpatch.observe(myobj2);
myobj2.firstName = "Albert";
myobj2.contactDetails.phoneNumbers[0].number = "123";
myobj2.contactDetails.phoneNumbers.push({ number: "456" });
var patches2 = jsonpatch.generate(observer);

var objA = { user: { firstName: "Albert", lastName: "Einstein" } };
var objB = { user: { firstName: "Albert", lastName: "Collins" } };
var diff = jsonpatch.compare(objA, objB);

var obj = { user: { firstName: "Albert" } };
var patches3 = [{ op: "replace", path: "/user/firstName", value: "Albert" }, { op: "replace", path: "/user/lastName", value: "Einstein" }];
var errors = jsonpatch.validate(patches, obj);
if (errors.length === 0) {
  //there are no errors!
} else {
  for (var i = 0; i < errors.length; i++) {
github freeCodeCamp / meeting-for-good / client / components / CalendarIntegrationSettings / CalendarIntegrationSettings.js View on Github external
static checkPrimaryCalendar = async (props, selectedCalendarList) => {
    const { curUser, cbEditCurUser } = props;
    try {
      const selectedCalendars = _.cloneDeep(curUser.GoogleSelectedCalendars) || [];
      const primaryCal = selectedCalendarList.filter(cal => cal.primary === true)[0].summary;
      const hasPrimaryCal = _.find(selectedCalendars, { calendarId: primaryCal });
      if (!hasPrimaryCal
        && curUser.enablePrimaryCalendar) {
        selectedCalendars.push({ calendarId: primaryCal });
        const nCurUser = _.cloneDeep(curUser);
        const observeCurUser = jsonpatch.observe(nCurUser);
        nCurUser.GoogleSelectedCalendars = selectedCalendars;
        nCurUser.enablePrimaryCalendar = false;
        const patchesForAdd = jsonpatch.generate(observeCurUser);
        await cbEditCurUser(patchesForAdd);
      }
      return selectedCalendars;
    } catch (err) {
      console.error('err at componentWillReceiveProps CalendarIntegrationSettings', err);
      return err;
    }
  };
github rjanicek / bos / scripts / bos.js View on Github external
loadOrCreateData(storePath, options, function (error, data) {
		if (error) {
			error.stacktrace = new Error().stack;
			store.emit('error', error);
			returnErrorAndStore && returnErrorAndStore(error);
			return;
		}

		store.data = data;

		var observer = jsonpatch.observe(data, function (patches) {
			update(storePath, patches, store);
		});

		store.close = function close(returnError) {
			jsonpatch.unobserve(store.data, observer);

			lockFile.unlock(storePath + LOCK_FILE_EXTENSION, function (error) {
				if (error) {
					error.stacktrace = new Error().stack;
					store.emit('error', error);
					if (returnError) { returnError(error); } else { throw error; }
					return;
				}

				store.emit('closed');
github colyseus / colyseus / src / State / Observer.js View on Github external
constructor (state) {
    this.state = state

    if (typeof(state.toJSON)!=="function") {
      this.patchObserver = jsonpatch.observe(state)

    } else {
      this.previousState = JSON.parse(JSON.stringify(this.toJSON(this.state)))
      this.patchObserver = jsonpatch.observe(this.previousState)
    }
  }
github rjanicek / bos / scripts / index.js View on Github external
loadOrCreate(path, options, function (error, object) {
			if (error) {
				returnErrorAndObject(error);
				return;
			}

			var store = {
				data: object
			};

			var observer = jsonpatch.observe(object, function (patches) {
				update(path, patches, emitter, store);
			});

			store.close = function close(returnError) {
				
				jsonpatch.unobserve(store.data, observer);

				lockFile.unlock(path + LOCK_FILE_EXTENSION, function (error) {
					if (error) {
						if (returnError) { returnError(error); } else { throw error; }
						return;
					}
					returnError && returnError();
				});
			};
github FabricLabs / fabric / types / observer.js View on Github external
constructor (target) {
    this.observer = monitor.observe(target);
    return this;
  }
}
github colyseus / colyseus / src / State / Observer.js View on Github external
constructor (state) {
    this.state = state

    if (typeof(state.toJSON)!=="function") {
      this.patchObserver = jsonpatch.observe(state)

    } else {
      this.previousState = JSON.parse(JSON.stringify(this.toJSON(this.state)))
      this.patchObserver = jsonpatch.observe(this.previousState)
    }
  }