Best JavaScript code snippet using storybook-root
relationship_load.js
Source:relationship_load.js
1var map = Em.ArrayPolyfills.map;2var filter = Em.ArrayPolyfills.filter;3var reduce = EG.ArrayPolyfills.reduce;4var forEach = Em.ArrayPolyfills.forEach;5var HAS_ONE_KEY = EG.Model.HAS_ONE_KEY;6var HAS_MANY_KEY = EG.Model.HAS_MANY_KEY;7var CLIENT_STATE = EG.Relationship.CLIENT_STATE;8var SERVER_STATE = EG.Relationship.SERVER_STATE;9var DELETED_STATE = EG.Relationship.DELETED_STATE;10// TODO: This can probably be moved into the store to be more model-agnostic11// Idea: load attributes into records directly, but load relationships into store12// Split the data apart in `pushPayload`13EG.Model.reopen({14 /**15 * Sets up relationships given to the constructor for this record.16 * Equivalent to calling the relationship functions individually.17 *18 * @private19 */20 initializeRelationships: function(json) {21 this.constructor.eachRelationship(function(name, meta) {22 var value = json[name];23 if (value === undefined) {24 return;25 }26 this.set('initializedRelationships.' + name, true);27 if (meta.kind === HAS_MANY_KEY) {28 forEach.call(value, function(v) {29 switch (Em.typeOf(v)) {30 case 'string':31 this.addToRelationship(name, v);32 break;33 case 'instance':34 this.addToRelationship(name, v.get('id'), v.get('typeKey'));35 break;36 default:37 this.addToRelationship(name, v.id, v.type);38 break;39 }40 }, this);41 } else {42 switch (Em.typeOf(value)) {43 case 'string':44 this.setHasOneRelationship(name, value);45 break;46 case 'null':47 // It's already null48 break;49 case 'instance':50 this.setHasOneRelationship(name, value.get('id'), value.get('typeKey'));51 break;52 default:53 this.setHasOneRelationship(name, value.id, value.type);54 break;55 }56 }57 }, this);58 },59 /**60 * Merges relationship data from the server into the relationships61 * already connected to this record. Any absolutely correct choices62 * are made automatically, while choices that come down to preference63 * are decided based on the configurable store properties.64 *65 * @param {Object} json66 * @private67 */68 loadRelationshipsFromServer: function(json) {69 this.constructor.eachRelationship(function(name, meta) {70 var otherKind = null;71 if (meta.inverse) {72 otherKind = this.get('store').modelFor(meta.relatedType).metaForRelationship(meta.inverse).kind;73 }74 // TODO: I don't much like this here. Same for the attributes one.75 if (meta.isRequired && json[name] === undefined) {76 throw new Em.Error('Your JSON is missing the required `' + name + '` relationship.');77 }78 if (json[name] === undefined) {79 json[name] = meta.getDefaultValue();80 }81 if (meta.kind === HAS_MANY_KEY) {82 switch (otherKind) {83 case HAS_ONE_KEY:84 this.connectHasManyToHasOne(name, meta, json[name]);85 break;86 case HAS_MANY_KEY:87 this.connectHasManyToHasMany(name, meta, json[name]);88 break;89 default:90 this.connectHasManyToNull(name, meta, json[name]);91 break;92 }93 } else {94 if (json[name]) {95 switch (otherKind) {96 case HAS_ONE_KEY:97 this.connectHasOneToHasOne(name, meta, json[name]);98 break;99 case HAS_MANY_KEY:100 this.connectHasOneToHasMany(name, meta, json[name]);101 break;102 default:103 this.connectHasOneToNull(name, meta, json[name]);104 break;105 }106 } else {107 switch (otherKind) {108 case HAS_ONE_KEY:109 this.disconnectHasOneFromHasOne(name, meta);110 break;111 case HAS_MANY_KEY:112 this.disconnectHasOneFromHasMany(name, meta);113 break;114 default:115 this.disconnectHasOneFromNull(name, meta);116 break;117 }118 }119 }120 }, this);121 },122 disconnectHasOneFromNull: Em.aliasMethod('disconnectHasOneFromHasMany'),123 disconnectHasOneFromHasOne: Em.aliasMethod('disconnectHasOneFromHasMany'),124 disconnectHasOneFromHasMany: function(name, meta) {125 var store = this.get('store');126 var relationships = store.sortHasOneRelationships(this.typeKey, this.get('id'), name);127 if (relationships[DELETED_STATE].length > 0) {128 forEach.call(relationships[DELETED_STATE], function (relationship) {129 store.deleteRelationship(relationship);130 }, this);131 }132 if (!relationships[SERVER_STATE] && !relationships[CLIENT_STATE]) {133 return;134 }135 if (relationships[SERVER_STATE] && !relationships[CLIENT_STATE]) {136 store.deleteRelationship(relationships[SERVER_STATE]);137 return;138 }139 if (!relationships[SERVER_STATE] && relationships[CLIENT_STATE]) {140 if (!store.get('sideWithClientOnConflict')) {141 store.deleteRelationship(relationships[CLIENT_STATE]);142 }143 }144 },145 connectHasOneToNull: Em.aliasMethod('connectHasOneToHasMany'),146 connectHasOneToHasOne: function(name, meta, value) {147 // TODO: This is going to be LONG. But make it right, then make it good148 var thisType = this.typeKey;149 var thisId = this.get('id');150 var store = this.get('store');151 var sideWithClientOnConflict = store.get('sideWithClientOnConflict');152 var theseValues = store.sortHasOneRelationships(thisType, thisId, name);153 var otherValues = store.sortHasOneRelationships(value.type, value.id, meta.inverse);154 var thisCurrent = theseValues[SERVER_STATE] || theseValues[CLIENT_STATE] || null;155 var otherCurrent = otherValues[SERVER_STATE] || otherValues[CLIENT_STATE] || null;156 if (thisCurrent === otherCurrent) {157 store.changeRelationshipState(thisCurrent, SERVER_STATE);158 return;159 }160 // Hehe, I'm going to look back on this one day...161 /* jshint ignore:start */162 var handled;163 if (!theseValues[SERVER_STATE] && !theseValues[CLIENT_STATE] && theseValues[DELETED_STATE].length <= 0) {164 if (!otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {165 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);166 return;167 }168 if (otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {169 store.deleteRelationship(otherValues[SERVER_STATE]);170 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);171 return;172 }173 if (!otherValues[SERVER_STATE] && otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {174 if (sideWithClientOnConflict) {175 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);176 } else {177 store.deleteRelationship(otherValues[CLIENT_STATE]);178 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);179 }180 return;181 }182 if (!otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length > 0) {183 handled = false;184 forEach.call(otherValues[DELETED_STATE], function(relationship) {185 if (relationship.otherType(this) === value.type && relationship.otherId(this) === value.id) {186 if (sideWithClientOnConflict) {187 // NOOP188 } else {189 store.changeRelationshipState(relationship, SERVER_STATE);190 }191 handled = true;192 } else {193 store.deleteRelationship(relationship);194 }195 }, this);196 if (!handled) {197 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);198 }199 return;200 }201 if (!otherValues[SERVER_STATE] && otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length > 0) {202 handled = false;203 forEach.call(otherValues[DELETED_STATE], function(relationship) {204 if (relationship.otherType(this) === value.type && relationship.otherId(this) === value.id) {205 if (sideWithClientOnConflict) {206 // NOOP207 } else {208 store.deleteRelationship(otherValues[CLIENT_STATE]);209 store.changeRelationshipState(relationship, SERVER_STATE);210 }211 handled = true;212 } else {213 store.deleteRelationship(relationship);214 }215 }, this);216 if (!handled) {217 if (sideWithClientOnConflict) {218 store.createRelationship(thisType, thisId, name,219 value.type, value.id, meta.inverse, DELETED_STATE);220 } else {221 store.deleteRelationship(otherValues[CLIENT_STATE]);222 store.createRelationship(thisType, thisId, name,223 value.type, value.id, meta.inverse, SERVER_STATE);224 }225 }226 return;227 }228 }229 if (theseValues[SERVER_STATE] && !theseValues[CLIENT_STATE] && theseValues[DELETED_STATE].length <= 0) {230 store.deleteRelationship(theseValues[SERVER_STATE]);231 if (!otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {232 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);233 return;234 }235 if (otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {236 store.deleteRelationship(otherValues[SERVER_STATE]);237 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);238 return;239 }240 if (!otherValues[SERVER_STATE] && otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {241 if (sideWithClientOnConflict) {242 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);243 } else {244 store.deleteRelationship(otherValues[CLIENT_STATE]);245 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);246 }247 return;248 }249 if (!otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length > 0) {250 handled = false;251 forEach.call(otherValues[DELETED_STATE], function(relationship) {252 if (relationship.otherType(this) === value.type && relationship.otherId(this) === value.id) {253 if (sideWithClientOnConflict) {254 // NOOP255 } else {256 store.changeRelationshipState(relationship, SERVER_STATE);257 }258 handled = true;259 } else {260 store.deleteRelationship(relationship);261 }262 }, this);263 if (!handled) {264 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);265 }266 return;267 }268 if (!otherValues[SERVER_STATE] && otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length > 0) {269 handled = false;270 forEach.call(otherValues[DELETED_STATE], function(relationship) {271 if (relationship.otherType(this) === value.type && relationship.otherId(this) === value.id) {272 if (sideWithClientOnConflict) {273 // NOOP274 } else {275 store.deleteRelationship(otherValues[CLIENT_STATE]);276 store.changeRelationshipState(relationship, SERVER_STATE);277 }278 handled = true;279 } else {280 store.deleteRelationship(relationship);281 }282 }, this);283 if (!handled) {284 if (sideWithClientOnConflict) {285 store.createRelationship(thisType, thisId, name,286 value.type, value.id, meta.inverse, DELETED_STATE);287 } else {288 store.deleteRelationship(otherValues[CLIENT_STATE]);289 store.createRelationship(thisType, thisId, name,290 value.type, value.id, meta.inverse, SERVER_STATE);291 }292 }293 return;294 }295 }296 if (!theseValues[SERVER_STATE] && theseValues[CLIENT_STATE] && theseValues[DELETED_STATE].length <= 0) {297 if (!otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {298 if (sideWithClientOnConflict) {299 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);300 } else {301 store.deleteRelationship(theseValues[CLIENT_STATE]);302 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);303 }304 return;305 }306 if (otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {307 store.deleteRelationship(otherValues[SERVER_STATE]);308 if (sideWithClientOnConflict) {309 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);310 } else {311 store.deleteRelationship(theseValues[CLIENT_STATE]);312 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);313 }314 return;315 }316 if (!otherValues[SERVER_STATE] && otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {317 if (sideWithClientOnConflict) {318 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);319 } else {320 store.deleteRelationship(theseValues[CLIENT_STATE]);321 store.deleteRelationship(otherValues[CLIENT_STATE]);322 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);323 }324 return;325 }326 if (!otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length > 0) {327 forEach.call(otherValues[DELETED_STATE], function(relationship) {328 store.deleteRelationship(relationship);329 });330 if (sideWithClientOnConflict) {331 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);332 } else {333 store.deleteRelationship(theseValues[CLIENT_STATE]);334 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);335 }336 return;337 }338 if (!otherValues[SERVER_STATE] && otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length > 0) {339 forEach.call(otherValues[DELETED_STATE], function(relationship) {340 store.deleteRelationship(relationship);341 });342 if (sideWithClientOnConflict) {343 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);344 } else {345 store.deleteRelationship(theseValues[CLIENT_STATE]);346 store.deleteRelationship(otherValues[CLIENT_STATE]);347 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);348 }349 return;350 }351 }352 if (!theseValues[SERVER_STATE] && !theseValues[CLIENT_STATE] && theseValues[DELETED_STATE].length > 0) {353 if (!otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {354 forEach.call(theseValues[DELETED_STATE], function(relationship) {355 store.deleteRelationship(relationship);356 });357 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);358 return;359 }360 if (otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {361 forEach.call(theseValues[DELETED_STATE], function(relationship) {362 store.deleteRelationship(relationship);363 });364 store.deleteRelationship(otherValues[SERVER_STATE]);365 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);366 return;367 }368 if (!otherValues[SERVER_STATE] && otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {369 forEach.call(theseValues[DELETED_STATE], function(relationship) {370 store.deleteRelationship(relationship);371 });372 if (sideWithClientOnConflict) {373 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);374 } else {375 store.deleteRelationship(otherValues[CLIENT_STATE]);376 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);377 }378 return;379 }380 if (!otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length > 0) {381 handled = null;382 forEach.call(theseValues[DELETED_STATE], function(relationship) {383 if (relationship.otherType(this) === value.type && relationship.otherId(this) === value.id) {384 if (sideWithClientOnConflict) {385 // NOOP386 } else {387 store.changeRelationshipState(relationship, SERVER_STATE);388 }389 handled = relationship;390 } else {391 store.deleteRelationship(relationship);392 }393 }, this);394 forEach.call(theseValues[DELETED_STATE], function(relationship) {395 if (relationship !== handled) {396 store.deleteRelationship(relationship);397 }398 });399 if (handled === null) {400 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);401 }402 return;403 }404 if (!otherValues[SERVER_STATE] && otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length > 0) {405 handled = null;406 forEach.call(theseValues[DELETED_STATE], function(relationship) {407 if (relationship.otherType(this) === value.type && relationship.otherId(this) === value.id) {408 if (sideWithClientOnConflict) {409 // NOOP410 } else {411 store.deleteRelationship(otherValues[CLIENT_STATE]);412 store.changeRelationshipState(relationship, SERVER_STATE);413 }414 handled = relationship;415 } else {416 store.deleteRelationship(relationship);417 }418 }, this);419 forEach.call(theseValues[DELETED_STATE], function(relationship) {420 if (relationship !== handled) {421 store.deleteRelationship(relationship);422 }423 });424 if (handled === null) {425 if (sideWithClientOnConflict) {426 store.createRelationship(thisType, thisId, name,427 value.type, value.id, meta.inverse, DELETED_STATE);428 } else {429 store.deleteRelationship(otherValues[CLIENT_STATE]);430 store.createRelationship(thisType, thisId, name,431 value.type, value.id, meta.inverse, SERVER_STATE);432 }433 }434 return;435 }436 }437 if (!theseValues[SERVER_STATE] && theseValues[CLIENT_STATE] && theseValues[DELETED_STATE].length > 0) {438 forEach.call(theseValues[DELETED_STATE], function(relationship) {439 store.deleteRelationship(relationship);440 });441 if (!otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {442 if (sideWithClientOnConflict) {443 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);444 } else {445 store.deleteRelationship(theseValues[CLIENT_STATE]);446 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);447 }448 return;449 }450 if (otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {451 store.deleteRelationship(otherValues[SERVER_STATE]);452 if (sideWithClientOnConflict) {453 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);454 } else {455 store.deleteRelationship(theseValues[CLIENT_STATE]);456 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);457 }458 return;459 }460 if (!otherValues[SERVER_STATE] && otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length <= 0) {461 if (sideWithClientOnConflict) {462 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);463 } else {464 store.deleteRelationship(theseValues[CLIENT_STATE]);465 store.deleteRelationship(otherValues[CLIENT_STATE]);466 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);467 }468 return;469 }470 if (!otherValues[SERVER_STATE] && !otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length > 0) {471 forEach.call(otherValues[DELETED_STATE], function(relationship) {472 store.deleteRelationship(relationship);473 });474 if (sideWithClientOnConflict) {475 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);476 } else {477 store.deleteRelationship(theseValues[CLIENT_STATE]);478 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);479 }480 return;481 }482 if (!otherValues[SERVER_STATE] && otherValues[CLIENT_STATE] && otherValues[DELETED_STATE].length > 0) {483 forEach.call(otherValues[DELETED_STATE], function(relationship) {484 store.deleteRelationship(relationship);485 });486 if (sideWithClientOnConflict) {487 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);488 } else {489 store.deleteRelationship(theseValues[CLIENT_STATE]);490 store.deleteRelationship(otherValues[CLIENT_STATE]);491 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);492 }493 return;494 }495 }496 /* jshint ignore:end */497 },498 connectHasOneToHasMany: function(name, meta, value) {499 var thisType = this.typeKey;500 var thisId = this.get('id');501 var store = this.get('store');502 var relationships = store.sortHasOneRelationships(thisType, thisId, name);503 var sideWithClientOnConflict = store.get('sideWithClientOnConflict');504 // TODO: Make it right, then make it good505 if (relationships[SERVER_STATE] && relationships[SERVER_STATE].otherType(this) === value.type &&506 relationships[SERVER_STATE].otherId(this) === value.id) {507 return;508 }509 if (relationships[CLIENT_STATE] && relationships[CLIENT_STATE].otherType(this) === value.type &&510 relationships[CLIENT_STATE].otherId(this) === value.id) {511 store.changeRelationshipState(relationships[CLIENT_STATE], SERVER_STATE);512 return;513 }514 if (!relationships[SERVER_STATE] && !relationships[CLIENT_STATE] && relationships[DELETED_STATE].length <= 0) {515 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);516 return;517 }518 if (relationships[SERVER_STATE] && !relationships[CLIENT_STATE] && relationships[DELETED_STATE].length <= 0) {519 store.deleteRelationship(relationships[SERVER_STATE]);520 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);521 return;522 }523 if (!relationships[SERVER_STATE] && relationships[CLIENT_STATE] && relationships[DELETED_STATE].length <= 0) {524 if (sideWithClientOnConflict) {525 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);526 } else {527 store.deleteRelationship(relationships[CLIENT_STATE]);528 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);529 }530 return;531 }532 var handled;533 if (!relationships[SERVER_STATE] && !relationships[CLIENT_STATE] && relationships[DELETED_STATE].length >= 0) {534 handled = false;535 forEach.call(relationships[DELETED_STATE], function(relationship) {536 if (relationship.otherType(this) === value.type && relationship.otherId(this) === value.id) {537 if (sideWithClientOnConflict) {538 // NOOP539 } else {540 store.changeRelationshipState(relationship, SERVER_STATE);541 }542 handled = true;543 } else {544 store.deleteRelationship(relationship);545 }546 }, this);547 if (!handled) {548 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);549 }550 return;551 }552 if (!relationships[SERVER_STATE] && relationships[CLIENT_STATE] && relationships[DELETED_STATE].length >= 0) {553 handled = false;554 forEach.call(relationships[DELETED_STATE], function(relationship) {555 if (relationship.otherType(this) === value.type && relationship.otherId(this) === value.id) {556 if (sideWithClientOnConflict) {557 // NOOP558 } else {559 store.deleteRelationship(relationships[CLIENT_STATE]);560 store.changeRelationshipState(relationship, SERVER_STATE);561 }562 handled = true;563 } else {564 store.deleteRelationship(relationship);565 }566 }, this);567 if (!handled) {568 if (sideWithClientOnConflict) {569 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);570 } else {571 store.deleteRelationship(relationships[CLIENT_STATE]);572 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);573 }574 }575 return;576 }577 },578 connectHasManyToNull: Em.aliasMethod('connectHasManyToHasMany'),579 connectHasManyToHasOne: function(name, meta, values) {580 var thisType = this.typeKey;581 var thisId = this.get('id');582 var store = this.get('store');583 var sideWithClientOnConflict = store.get('sideWithClientOnConflict');584 var valueMap = reduce.call(values, function(map, value) {585 map[value.type + ':' + value.id] = value;586 return map;587 }, {});588 var relationships = store.relationshipsForRecord(thisType, thisId, name);589 forEach.call(relationships, function(relationship) {590 var valueKey = relationship.otherType(this) + ':' + relationship.otherId(this);591 if (valueMap[valueKey]) {592 switch (relationship.get('state')) {593 case SERVER_STATE:594 // NOOP595 break;596 case DELETED_STATE:597 if (sideWithClientOnConflict) {598 // NOOP599 } else {600 store.changeRelationshipState(relationship, SERVER_STATE);601 }602 break;603 case CLIENT_STATE:604 store.changeRelationshipState(relationship, SERVER_STATE);605 break;606 }607 } else {608 switch (relationship.get('state')) {609 case SERVER_STATE:610 case DELETED_STATE:611 store.deleteRelationship(relationship);612 break;613 case CLIENT_STATE:614 if (sideWithClientOnConflict) {615 // NOOP616 } else {617 store.deleteRelationship(relationship);618 }619 break;620 }621 }622 delete valueMap[valueKey];623 }, this);624 // We've narrowed it down to relationships that have to be created from scratch. (Possibly with conflicts.)625 EG.values(valueMap, function(key, value) {626 var conflicts = store.sortHasOneRelationships(value.type, value.id, meta.inverse);627 if (!conflicts[SERVER_STATE] && !conflicts[CLIENT_STATE] && conflicts[DELETED_STATE].length <= 0) {628 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);629 return;630 }631 if (conflicts[SERVER_STATE] && !conflicts[CLIENT_STATE] && conflicts[DELETED_STATE].length <= 0) {632 store.deleteRelationship(conflicts[SERVER_STATE]);633 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);634 return;635 }636 if (!conflicts[SERVER_STATE] && conflicts[CLIENT_STATE] && conflicts[DELETED_STATE].length <= 0) {637 if (sideWithClientOnConflict) {638 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);639 } else {640 store.deleteRelationship(conflicts[CLIENT_STATE]);641 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);642 }643 return;644 }645 if (!conflicts[SERVER_STATE] && !conflicts[CLIENT_STATE] && conflicts[DELETED_STATE].length > 0) {646 forEach.call(conflicts[DELETED_STATE], function(relationship) {647 store.deleteRelationship(relationship);648 });649 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);650 return;651 }652 if (!conflicts[SERVER_STATE] && conflicts[CLIENT_STATE] && conflicts[DELETED_STATE].length > 0) {653 forEach.call(conflicts[DELETED_STATE], function(relationship) {654 store.deleteRelationship(relationship);655 });656 if (sideWithClientOnConflict) {657 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, DELETED_STATE);658 } else {659 store.deleteRelationship(conflicts[CLIENT_STATE]);660 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);661 }662 return;663 }664 }, this);665 },666 connectHasManyToHasMany: function(name, meta, values) {667 var thisType = this.typeKey;668 var thisId = this.get('id');669 var store = this.get('store');670 var sideWithClientOnConflict = store.get('sideWithClientOnConflict');671 var valueMap = reduce.call(values, function(map, value) {672 map[value.type + ':' + value.id] = value;673 return map;674 }, {});675 var relationships = store.relationshipsForRecord(thisType, thisId, name);676 forEach.call(relationships, function(relationship) {677 var valueKey = relationship.otherType(this) + ':' + relationship.otherId(this);678 if (valueMap[valueKey]) {679 switch (relationship.get('state')) {680 case SERVER_STATE:681 // NOOP682 break;683 case DELETED_STATE:684 if (sideWithClientOnConflict) {685 // NOOP686 } else {687 store.changeRelationshipState(relationship, SERVER_STATE);688 }689 break;690 case CLIENT_STATE:691 store.changeRelationshipState(relationship, SERVER_STATE);692 break;693 }694 } else {695 switch (relationship.get('state')) {696 case SERVER_STATE:697 case DELETED_STATE:698 store.deleteRelationship(relationship);699 break;700 case CLIENT_STATE:701 if (sideWithClientOnConflict) {702 // NOOP703 } else {704 store.deleteRelationship(relationship);705 }706 break;707 }708 }709 delete valueMap[valueKey];710 }, this);711 // We've narrowed it down to relationships that have to be created from scratch.712 EG.values(valueMap, function(key, value) {713 store.createRelationship(thisType, thisId, name, value.type, value.id, meta.inverse, SERVER_STATE);714 });715 }...
createSandwich.js
Source:createSandwich.js
1import React from 'react';2import withStyles from '@material-ui/core/styles/withStyles';3import { AppContext } from '../../context/appContext.js';4import CloseIcon from '@material-ui/icons/Close';5import Button from "@material-ui/core/Button";6import SandwichSizeRadioButtons from './sandwichSizeRadioButtons.js';7import SandwichBreadRadioButtons from './sandwichBreadRadioButtons.js';8import SandwichCheeseCheckboxes from './sandwichCheeseCheckboxes.js';9import SandwichDefaultsCheckboxes from './sandwichDefaultsCheckboxes.js';10import SandwichMeatCheckboxes from './sandwichMeatCheckboxes.js';11import SandwichToastedCheckbox from './sandwichToastedCheckbox.js';12import SandwichVeggiesCheckboxes from './sandwichVeggiesCheckboxes.js';13import SandwichSaucesCheckboxes from './sandwichSaucesCheckboxes.js';14import SandwichSeasoningsCheckboxes from './sandwichSeasoningsCheckboxes.js';15const styles = theme => ({16 addToCartButton: {17 backgroundColor: '#7600A8',18 fontWeight: 500,19 height: 50,20 fontSize: '2.5rem',21 color: 'white',22 padding: '0px 15px',23 border: '3px solid# 7600A8',24 borderRadius: '10px',25 width: '200px',26 textTransform: 'none',27 marginLeft: '10%',28 marginTop: '10px',29 marginBottom: '10px',30 "&:hover": {31 color: '#7600A8',32 backgroundColor: 'white',33 },34 "&:disabled": {35 color: '#7600A8',36 backgroundColor: 'white',37 },38 [theme.breakpoints.down(550)]: {39 width: '100%',40 marginLeft: 0,41 marginTop: '10px',42 marginBottom: '10px',43 },44 },45 categoryBar: {46 width: '100%',47 backgroundColor: '#0087A8',48 color: 'white',49 marginTop: 0,50 textAlign: 'center',51 },52 categoryInfoBar: {53 width: '100%',54 backgroundColor: '#CDCDCD',55 color: 'black',56 marginTop: 0,57 textAlign: 'center',58 fontSize: '1.7rem',59 },60 closeIconStyling: {61 width: '25px',62 height: '25px',63 cursor: "pointer",64 marginLeft: 'auto',65 marginRight: '2%',66 alignSelf: 'flex-end',67 marginBottom: 10,68 },69 container: {70 position: 'fixed',71 zIndex: 1,72 left: 0,73 top: 0,74 width: '100%',75 height: '100%',76 overflow: 'auto',77 backgroundColor: 'rgba(43, 43, 43, 0.3)',78 },79 finalInfo: {80 width: '100%',81 display: 'flex',82 flexWrap: 'wrap',83 justifyContent: 'center',84 alignItems: 'center',85 fontWeight: 500,86 backgroundColor: '#CDCDCD',87 },88 header: {89 display: 'flex',90 width: '100%',91 justifyContent: 'flex-end',92 },93 headerText: {94 fontSize: '3.5rem',95 marginLeft: 'auto',96 paddingLeft: '42px',97 marginBottom: 10,98 textAlign: 'center',99 [theme.breakpoints.down(550)]: {100 fontSize: '3.0rem',101 paddingLeft: '34px'102 },103 },104 holderDiv: {105 width: '100%',106 },107 infoText: {108 fontSize: '3.0rem',109 marginTop: 10,110 width: '100%',111 padding: '0px 10px',112 textAlign: 'center',113 [theme.breakpoints.down(800)]: {114 fontSize: '2.5rem',115 },116 [theme.breakpoints.down(550)]: {117 fontSize: '2.0rem',118 },119 },120 menuSpacingDiv: {121 margin: '0 auto',122 marginTop: '15vh',123 width: '100%',124 maxWidth: 1000,125 borderRadius: '4px',126 backgroundColor: '#f8fbfd',127 minHeight: 100,128 display: 'flex',129 justifyContent: 'center',130 alignItems: 'center',131 flexDirection: 'column',132 padding: '20px 0px',133 fontSize: '2.0rem',134 lineHeight: 1.25,135 },136});137class CreateSandwich extends React.Component {138 state={139 sandwich: {},140 breads: {},141 meats: {},142 cheeses: {},143 veggies: {},144 seasonings: {},145 sauces: {},146 otherValues: {},147 sandwichDefaults: {},148 render: false,149 disableCartButton: false,150 }151 componentDidMount() {152 let sandwich = this.props.sandwich;153 let breads = {};154 let meats = {};155 let cheeses = {};156 let veggies = {};157 let seasonings = {};158 let sauces = {};159 let otherValues = {};160 let sandwichDefaults = {};161 for (const [key, value] of Object.entries(sandwich)) {162 if(value === true && !key.includes('Sandwich')) {163 sandwichDefaults[key] = value164 }165 if(key.includes('Bread') || key === 'hasWrap') {166 breads[key] = value167 }168 if(key === 'hasBacon' || key === 'hasChicken' || key === 'hasHam' || key === 'hasMeatball' || key === 'hasSteak' || key === 'hasTurkey') {169 meats[key] = value170 }171 if(key.includes('Cheese')) {172 cheeses[key] = value173 }174 if(key.includes('Lettuce') || key.includes('Peppers') || key === 'hasCucumbers' || key.includes('Onions') || key === 'hasJalapenos' || key === 'hasPickles' || key === 'hasSpinach' || key === 'hasTomatoes') {175 veggies[key] = value176 }177 if(key.includes('Salt') || key === 'hasOregano' || key === 'hasPepper') {178 seasonings[key] = value179 }180 if(key.includes('Sauce') || key === 'hasMarinara' || key === 'hasMayo' || key.includes('Mustard') || key === 'hasOil' || key.includes('Dressing')) {181 sauces[key] = value182 }183 if (key === 'name' || key === 'isToasted' || key.includes('Sandwich') || key.includes('Price') || key.includes('type')) {184 otherValues[key] = value185 }186 }187 otherValues['finalPrice'] = otherValues['startingPrice']188 this.setState({189 sandwichDefaults,190 sandwich,191 breads,192 meats,193 cheeses,194 veggies,195 seasonings,196 sauces,197 otherValues,198 render: true,199 })200 }201 UpdateSandwichSizeRadios = (small, medium, large, largerSandwichPrice) => {202 let otherValues = this.state.otherValues203 if(small || medium || large) {204 if(small === true) {205 otherValues['name'] = `Small ${otherValues['type']}`206 }207 if(medium === true) {208 otherValues['name'] = `Medium ${otherValues['type']}`209 }210 if(large === true) {211 otherValues['name'] = `Large ${otherValues['type']}`212 }213 otherValues['isSmallSandwich'] = small;214 otherValues['isMediumSandwich'] = medium;215 otherValues['isLargeSandwich'] = large;216 217 otherValues['largerSandwichPrice'] = largerSandwichPrice;218 let finalPrice = Number(this.state.otherValues['startingPrice'] + largerSandwichPrice + this.state.otherValues['extraCheesePrice'] + this.state.otherValues['extraMeatPrice']).toFixed(2)219 otherValues['finalPrice'] = Number(finalPrice)220 this.setState({221 otherValues,222 })223 }224 else {225 otherValues['isSmallSandwich'] = true;226 otherValues['isMediumSandwich'] = false;227 otherValues['isLargeSandwich'] = false;228 otherValues['largerSandwichPrice'] = 0.00;229 otherValues['name'] = `Small ${otherValues['type']}`;230 this.setState({231 otherValues,232 })233 }234 }235 UpdateSandwichBreadRadios = (italian, parm, wheat, white, wrap, none) => {236 let breads = this.state.breads237 if(italian || parm || wheat || white || wrap) {238 breads['hasItalianBread'] = italian;239 breads['hasParmesanOreganoBread'] = parm;240 breads['hasWheatBread'] = wheat;241 breads['hasWhiteBread'] = white;242 breads['hasWrap'] = wrap;243 breads['hasNoBread'] = none244 this.setState({245 breads,246 })247 }248 else {249 breads['hasItalianBread'] = true;250 breads['hasParmesanOreganoBread'] = false;251 breads['hasWheatBread'] = false;252 breads['hasWhiteBread'] = false;253 breads['hasWrap'] = false;254 breads['hasNoBread'] = false;255 this.setState({256 breads,257 })258 }259 }260 UpdateSandwichCheeseCheckboxes = (american, cheddar, mozzarella, pepperjack, provolone, swiss) => {261 let cheeses = this.state.cheeses;262 let otherValues = this.state.otherValues;263 let extraCheesePrice = -0.40264 if(american || cheddar || mozzarella || pepperjack || provolone || swiss) {265 cheeses['hasAmericanCheese'] = american;266 cheeses['hasCheddarCheese'] = cheddar;267 cheeses['hasMozzarellaCheese'] = mozzarella;268 cheeses['hasPepperjackCheese'] = pepperjack;269 cheeses['hasProvoloneCheese'] = provolone;270 cheeses['hasSwissCheese'] = swiss;271 Object.values(cheeses).forEach(function (cheeseValue) {272 if(cheeseValue === true) {273 extraCheesePrice += .40274 }275 })276 if(extraCheesePrice > 0){277 otherValues['extraCheesePrice'] = extraCheesePrice;278 let finalPrice = Number(this.state.otherValues['startingPrice'] + this.state.otherValues['largerSandwichPrice'] + extraCheesePrice + this.state.otherValues['extraMeatPrice']).toFixed(2)279 otherValues['finalPrice'] = Number(finalPrice)280 }281 else {282 otherValues['extraCheesePrice'] = 0.00283 }284 this.setState({285 cheeses,286 otherValues,287 })288 }289 else {290 cheeses['hasAmericanCheese'] = false;291 cheeses['hasCheddarCheese'] = false;292 cheeses['hasMozzarellaCheese'] = false;293 cheeses['hasPepperjackCheese'] = false;294 cheeses['hasProvoloneCheese'] = false;295 cheeses['hasSwissCheese'] = false;296 otherValues['extraCheesePrice'] = 0.00;297 this.setState({298 cheeses,299 otherValues,300 })301 }302 }303 UpdateSandwichDefaultsCheckboxes = (sandwichDefault) => {304 if (sandwichDefault) {305 this.setState({306 sandwichDefaults: sandwichDefault307 })308 }309 }310 UpdateSandwichMeatCheckboxes = (meats, extraMeatPrice) => {311 if (meats) {312 let otherValues = this.state.otherValues;313 otherValues['extraMeatPrice'] = extraMeatPrice;314 let finalPrice = Number(this.state.otherValues['startingPrice'] + this.state.otherValues['largerSandwichPrice'] + this.state.otherValues['extraCheesePrice'] + extraMeatPrice).toFixed(2)315 otherValues['finalPrice'] = Number(finalPrice)316 this.setState({317 meats,318 otherValues319 })320 }321 }322 UpdateSandwichToastedCheckbox = (toasted) => {323 if(toasted) {324 let otherValues = this.state.otherValues;325 otherValues['isToasted'] = toasted;326 this.setState({327 otherValues328 })329 }330 else {331 let otherValues = this.state.otherValues;332 otherValues['isToasted'] = false;333 this.setState({334 otherValues335 })336 }337 }338 UpdateSandwichVeggiesCheckboxes = (veggies) => {339 if (veggies) {340 this.setState({341 veggies,342 })343 }344 }345 UpdateSandwichSaucesCheckboxes = (sauces) => {346 if (sauces) {347 this.setState({348 sauces,349 })350 }351 }352 UpdateSandwichSeasoningsCheckboxes = (seasonings) => {353 if (seasonings) {354 this.setState({355 seasonings356 })357 }358 }359 AddSandwichToCart = () => {360 this.setState({361 disableCartButton: true,362 })363 let newSandwich = {364 ...this.state.sandwichDefaults,365 ...this.state.breads,366 ...this.state.meats,367 ...this.state.cheeses,368 ...this.state.veggies,369 ...this.state.seasonings,370 ...this.state.sauces,371 ...this.state.otherValues,372 }373 this.props.itemAddedToCart();374 this.context.addSandwichToCart(newSandwich);375 }376 render() {377 const { classes } = this.props;378 if(this.state.render) {379 return (380 <div className={classes.container}>381 {this.context.state.orderItemCount >= 25 || this.context.state.orderSandwichCount >= 10 ? 382 <div className={classes.menuSpacingDiv}>383 <div className={classes.header}>384 <h1 className={classes.headerText}>{this.props.title}</h1>385 <CloseIcon onClick={this.props.close} className={classes.closeIconStyling} />386 </div>387 <div>This order is getting too large. Please call the store for large orders.</div>388 </div>389 : 390 <div className={classes.menuSpacingDiv}>391 <div className={classes.header}>392 <h1 className={classes.headerText}>{this.props.title}</h1>393 <CloseIcon onClick={this.props.close} className={classes.closeIconStyling} />394 </div>395 <div className={classes.categoryBar}>Choose Size:</div>396 <SandwichSizeRadioButtons updateButtons={this.UpdateSandwichSizeRadios} price={this.state.otherValues['startingPrice']} largerSandwichPrice={this.state.otherValues['largerSandwichPrice']} />397 <div className={classes.categoryBar}>Choose Bread:</div>398 <SandwichBreadRadioButtons updateButtons={this.UpdateSandwichBreadRadios} />399 <div className={classes.categoryBar}>Choose Cheese:</div>400 <div className={classes.categoryInfoBar}>One cheese comes with the sandwich. Extra cheeses $.40 each.</div>401 <SandwichCheeseCheckboxes updateButtons={this.UpdateSandwichCheeseCheckboxes} cheeses={this.state.cheeses} extraCheesePrice={this.state.otherValues['extraCheesePrice']} />402 {(Object.keys(this.state.sandwichDefaults).length > 0) ? <div className={classes.holderDiv}><div className={classes.categoryBar}>Comes With:</div>403 <SandwichDefaultsCheckboxes updateButtons={this.UpdateSandwichDefaultsCheckboxes} defaults={this.state.sandwichDefaults} /></div> : null }404 <div className={classes.categoryBar}>Add Meat:</div>405 <div className={classes.categoryInfoBar}>Extra meats $.80 each.</div>406 <SandwichMeatCheckboxes updateButtons={this.UpdateSandwichMeatCheckboxes} defaults={this.state.sandwichDefaults} meats={this.state.meats} extraMeatPrice={this.state.otherValues['extraMeatPrice']} />407 <div className={classes.categoryBar}>Toasted:</div>408 <SandwichToastedCheckbox updateButton={this.UpdateSandwichToastedCheckbox} toasted={this.state.otherValues['isToasted']} />409 <div className={classes.categoryBar}>Add Veggies:</div>410 <SandwichVeggiesCheckboxes updateButtons={this.UpdateSandwichVeggiesCheckboxes} defaults={this.state.sandwichDefaults} veggies={this.state.veggies} />411 <div className={classes.categoryBar}>Add Sauces:</div>412 <SandwichSaucesCheckboxes updateButtons={this.UpdateSandwichSaucesCheckboxes} defaults={this.state.sandwichDefaults} sauces={this.state.sauces} />413 <div className={classes.categoryBar}>Add Seasonings:</div>414 <SandwichSeasoningsCheckboxes updateButtons={this.UpdateSandwichSeasoningsCheckboxes} seasonings={this.state.seasonings} />415 <div className={classes.finalInfo}>Price: ${ this.state.otherValues['finalPrice']}<Button className={classes.addToCartButton} onClick={this.AddSandwichToCart} disabled={this.state.disableCartButton || (this.state.breads['hasItalianBread'] === false && this.state.breads['hasParmesanOreganoBread'] === false && this.state.breads['hasWheatBread'] === false && this.state.breads['hasWhiteBread'] === false && this.state.breads['hasWrap'] === false && this.state.breads['hasNoBread'] === false) || this.context.state.orderItemCount >= 25 || this.context.state.orderSandwichCount >= 10 }>Add to Cart</Button></div>416 </div>417 }418 </div>419 )420 }421 else {422 return null423 }424 }425}426CreateSandwich.contextType = AppContext;...
BaseValidator.js
Source:BaseValidator.js
1import PropTypes from 'prop-types';2import {getFieldValueFromKeyString} from '../helpers/generalHelpers';3/**4 * The validator that all validators extend.5 * Probably should not be used on its own6 */7class BaseValidator {8 defaultInputType = 'text';9 requiredError;10 validateFuncs = [];11 isRequired = false;12 defaultErrorMsg = '';13 dependent = false;14 defaultValue = '';15 propType = PropTypes.any;16 onError;17 mutationFunc;18 /**19 * @param [defaultValue]20 * @param {String} [defaultErrorMsg]21 * @param {Function} [mutationFunc]22 * @param {Function} [onError]23 * @param {Array|Boolean} [dependent]24 */25 constructor(defaultValue = '', defaultErrorMsg = null, mutationFunc, onError, dependent = false) {26 this.defaultErrorMsg = defaultErrorMsg ?? 'There is an error within this field';27 this.mutationFunc = mutationFunc;28 this.onError = onError;29 this.dependent = dependent;30 this.defaultValue = defaultValue;31 }32 /**33 * Sets the input type that will be passed to fields that this validator validates34 * @param {String} newDefaultInputType35 */36 setDefaultInputType(newDefaultInputType) {37 this.defaultInputType = newDefaultInputType;38 }39 /**40 * Sets the default value for this validator41 * @param {any} newDefaultValue42 */43 setDefaultValue(newDefaultValue) {44 this.defaultValue = newDefaultValue;45 }46 /**47 * Sets the default error message for this validator48 * @param {String} newDefaultErrorMsg49 */50 setDefaultErrorMsg(newDefaultErrorMsg) {51 this.defaultErrorMsg = newDefaultErrorMsg;52 }53 /**54 * Set the validators mutation function55 * @param {function} newMutationFunc56 */57 setMutationFunc(newMutationFunc) {58 this.mutationFunc = newMutationFunc;59 }60 /**61 * Set the validators onError handler62 * @param {function} newOnError63 */64 setOnError(newOnError) {65 this.onError = newOnError;66 }67 /**68 * Set the validators dependent field69 * @param {Array|boolean} newDependent70 */71 setDependent(newDependent) {72 this.dependent = newDependent;73 }74 validateRequired(value) {75 return (value !== '' && value !== null && value !== undefined && (!(value instanceof Array) || value.length > 0));76 }77 /**78 * Enforces a value to be set79 * @param [msg] - The error message that is displayed when the value is invalid80 * @return {this}81 */82 required(msg = 'This field is required') {83 this.isRequired = true;84 this.requiredError = msg;85 return this;86 }87 /**88 * Makes the validation fail in all cases.89 * This may be useful for dependent validators.90 * @param [msg] - The error message that is displayed91 * @return {this}92 */93 alwaysFalse(msg = 'This validator will never return true') {94 this.validateFuncs.push([() => false, msg]);95 return this;96 }97 validateDependentStep(step, value, otherValues, siblings) {98 const dependentValue = getFieldValueFromKeyString(step[0], otherValues);99 if (step[1](dependentValue, value)) {100 return [true, step[2].validate(value, otherValues, siblings)];101 } else {102 return [false];103 }104 }105 validateDependent(value, otherValues, siblings) {106 if (Array.isArray(this.dependent[0])) {107 for (const step of this.dependent[0]) {108 const validated = this.validateDependentStep(step, value, otherValues, siblings);109 if (validated[0]) {110 return (validated[1]);111 }112 }113 } else {114 const validated = this.validateDependentStep(this.dependent, value, otherValues, siblings);115 if (validated[0]) {116 return validated[1];117 }118 }119 return this.validateIndependent(value, otherValues, siblings);120 }121 validateIndependent(value, otherValues, siblings) {122 if (!this.validateRequired(value)) {123 if (this.isRequired) {124 return [false, this.requiredError ?? this.defaultErrorMsg];125 }126 } else {127 for (const entry of this.validateFuncs) {128 const func = entry[0];129 const test = func(value, otherValues, siblings);130 if (test === false) {131 return [false, entry[1]];132 } else if (test !== true) {133 // Allows validators to modify the value134 value = test;135 }136 }137 }138 return [true, value];139 }140 /**141 * Check if the fields value is greater than another value142 * @param {String} name143 * @param {String} [msg]144 * @return {this}145 */146 greaterThan(name, msg) {147 if (msg === undefined) {148 msg = 'This value must be greater than the value of ' + name;149 }150 this.validateFuncs.push([151 (value, otherValues) => {152 const otherVal = getFieldValueFromKeyString(name, otherValues);153 return value > otherVal;154 },155 msg,156 ]);157 return this;158 }159 /**160 * Check if the fields value is less than another value161 * @param {String} name162 * @param {String} [msg]163 * @return {this}164 */165 lessThan(name, msg) {166 if (msg === undefined) {167 msg = 'This value must be less than the value of ' + name;168 }169 this.validateFuncs.push([170 (value, otherValues) => {171 const otherVal = getFieldValueFromKeyString(name, otherValues);172 return value < otherVal;173 },174 msg,175 ]);176 return this;177 }178 /**179 * Check if the fields value is greater than or equal to another value180 * @param {String} name181 * @param {String} [msg]182 * @return {this}183 */184 greaterOrEqualTo(name, msg) {185 if (msg === undefined) {186 msg = 'This value must be greater than or equal to the value of ' + name;187 }188 this.validateFuncs.push([189 (value, otherValues) => {190 const otherVal = getFieldValueFromKeyString(name, otherValues);191 return value >= otherVal;192 },193 msg,194 ]);195 return this;196 }197 /**198 * Check if the fields value is less than or equal to another value199 * @param {String} name200 * @param {String} [msg]201 * @return {this}202 */203 lessOrEqualTo(name, msg) {204 if (msg === undefined) {205 msg = 'This value must be less than or equal to the value of ' + name;206 }207 this.validateFuncs.push([208 (value, otherValues) => {209 const otherVal = getFieldValueFromKeyString(name, otherValues);210 return value <= otherVal;211 },212 msg,213 ]);214 return this;215 }216 /**217 * Check if the fields value is greater than the value of one of its siblings218 * @param {String|Number} key219 * @param {String} [msg]220 * @return {this}221 */222 greaterThanSibling(key, msg) {223 if (msg === undefined) {224 msg = 'This value must be greater than the value of its sibling ' + key;225 }226 this.validateFuncs.push([227 (value, otherValues, siblings) => {228 const otherVal = getFieldValueFromKeyString(key, siblings);229 return value > otherVal;230 },231 msg,232 ]);233 return this;234 }235 /**236 * Check if the fields value is less than the value of one of its siblings237 * @param {String|Number} key238 * @param {String} [msg]239 * @return {this}240 */241 lessThanSibling(key, msg) {242 if (msg === undefined) {243 msg = 'This value must be less than the value of its sibling ' + key;244 }245 this.validateFuncs.push([246 (value, otherValues, siblings) => {247 const otherVal = getFieldValueFromKeyString(key, siblings);248 return value < otherVal;249 },250 msg,251 ]);252 return this;253 }254 /**255 * Check if the fields value is greater or equal to the value of one of its siblings256 * @param {String|Number} key257 * @param {String} [msg]258 * @return {this}259 */260 greaterOrEqualToSibling(key, msg) {261 if (msg === undefined) {262 msg = 'This value must be greater than or equal to the value of its sibling ' + key;263 }264 this.validateFuncs.push([265 (value, otherValues, siblings) => {266 const otherVal = getFieldValueFromKeyString(key, siblings);267 return value >= otherVal;268 },269 msg,270 ]);271 return this;272 }273 /**274 * Check if the fields value is less than or equal to the value of one of its siblings275 * @param {String|Number} key276 * @param {String} [msg]277 * @return {this}278 */279 lessOrEqualToSibling(key, msg) {280 if (msg === undefined) {281 msg = 'This value must be less than or equal to the value of its sibling ' + key;282 }283 this.validateFuncs.push([284 (value, otherValues, siblings) => {285 const otherVal = getFieldValueFromKeyString(key, siblings);286 return value <= otherVal;287 },288 msg,289 ]);290 return this;291 }292 /**293 * Checks if the field's value is included within the values of an array field294 * @param {String} key295 * @param {function} [checkFn]296 * @param {String} [msg]297 * @return {this}298 */299 oneOfArrayFieldValues(key, checkFn, msg) {300 if (msg === undefined) {301 msg = 'This value is not allowed.';302 }303 if (checkFn === undefined) {304 checkFn = (compare, value) => compare.includes(value);305 }306 this.validateFuncs.push([307 (value, otherValues) => {308 const compare = getFieldValueFromKeyString(key, otherValues);309 if (Array.isArray(compare)) {310 return checkFn(compare, value);311 } else {312 console.warn('Attempted to use oneOfArrayFieldValues validator on a non array field. This is not possible.');313 return false;314 }315 },316 msg,317 ]);318 return this;319 }320 /**321 * Checks if the field's value is included within the values of an array field that is a sibling322 * @param {String} key323 * @param {function} [checkFn]324 * @param {String} [msg]325 * @return {this}326 */327 oneOfArraySiblingFieldValues(key, checkFn, msg) {328 if (msg === undefined) {329 msg = 'This value is not allowed.';330 }331 if (checkFn === undefined) {332 checkFn = (compare, value) => compare.includes(value);333 }334 this.validateFuncs.push([335 (value, otherValues, siblings) => {336 const compare = getFieldValueFromKeyString(key, siblings);337 if (Array.isArray(compare)) {338 return checkFn(compare, value);339 } else {340 console.warn('Attempted to use oneOfArraySiblingFieldValues validator on a non array field. This is not possible.');341 return false;342 }343 },344 msg,345 ]);346 return this;347 }348 /**349 * Checks if the value is one included in the provided array350 * @param {Array} values351 * @param {String} [msg]352 * @return {this}353 */354 oneOf(values, msg) {355 if (msg === undefined) {356 msg = 'This value must be one of these: ' + values.join(', ');357 }358 this.validateFuncs.push([359 (value) => {360 return values.includes(value);361 },362 msg,363 ]);364 return this;365 }366 /**367 * Validates a value368 * @param value369 * @param otherValues370 * @param siblings371 * @return {*}372 */373 validate(value, otherValues = {}, siblings = {}) {374 let ret;375 if (this.dependent) {376 ret = this.validateDependent(value, otherValues, siblings);377 } else {378 ret = this.validateIndependent(value, otherValues, siblings);379 }380 if (!ret[0] && typeof this.onError === 'function') {381 this.onError(value, otherValues);382 } else if (ret[0] && typeof this.mutationFunc === 'function') {383 ret[1] = this.mutationFunc(ret[1], otherValues, siblings);384 }385 return ret;386 }387 /**388 * Returns the validator's default value389 * @return {any}390 */391 getDefaultValue() {392 return this.defaultValue;393 }394 /**395 * Returns the validator's PropTypes representation396 * @return {Validator<NonNullable<any>>|Requireable<any>}397 */398 getPropType() {399 return this.isRequired ? this.propType.isRequired : this.propType;400 }401}...
Using AI Code Generation
1import { OtherValues } from 'storybook-root';2const otherValues = new OtherValues();3otherValues.otherValues();4import OtherValues from './OtherValues';5export { OtherValues };6export default class OtherValues {7 otherValues() {8 console.log('other values');9 }10}
Using AI Code Generation
1import { OtherValues } from 'storybook-root'2const result = OtherValues('hello', 'world')3import { OtherValues } from 'storybook-root'4const result = OtherValues('hello', 'world')5import { OtherValues } from 'storybook-root'6const result = OtherValues('hello', 'world')7import { OtherValues } from 'storybook-root'8const result = OtherValues('hello', 'world')9import { OtherValues } from 'storybook-root'10const result = OtherValues('hello', 'world')11import { OtherValues } from 'storybook-root'12const result = OtherValues('hello', 'world')13import { OtherValues } from 'storybook-root'14const result = OtherValues('hello', 'world')15import { OtherValues } from 'storybook-root'16const result = OtherValues('hello', 'world')17import { OtherValues } from 'storybook-root'18const result = OtherValues('hello', 'world')19import { OtherValues } from 'storybook-root'20const result = OtherValues('hello', 'world')21import { OtherValues } from 'storybook-root'22const result = OtherValues('hello', 'world')
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!