Best JavaScript code snippet using puppeteer
queries.js
Source:queries.js
...152 queryString = queryString.slice(0, queryString.lastIndexOf(','));153 queryString += ') VALUES (';154 payloadNames.forEach(function (element, index) {155 queryString += '$' + (index + 1) + ', ';156 params.push(parseProperty(payload[payloadNames[index]]));157 });158 queryString = queryString.slice(0, queryString.lastIndexOf(','));159 queryString += ') RETURNING ';160 props.forEach(function (element) {161 queryString += element + ', ';162 });163 queryString = queryString.slice(0, queryString.lastIndexOf(','));164 queryString += ';';165 var queryData = {166 string: queryString,167 params: params168 };169 return queryData;170 // var queryString = 'INSERT INTO client (first_name, last_name, nickname,'171 // + 'person_completing_intake, hmis_consent, first_time,'172 // + 'email, provided_id, state_id) VALUES (';173 // // frontend people are using this for naming standards in their JSON174 // queryString += parseProperty(payload.firstName) + ',';175 // queryString += parseProperty(payload.lastName) + ',';176 // queryString += parseProperty(payload.nickname) + ',';177 // queryString += parseProperty(payload.personCompletingIntake) + ',';178 // // queryString += parseProperty(payload.intakeDate) + ',';179 // queryString += parseProperty(payload.HMISConsent) + ',';180 // queryString += parseProperty(payload.firstTime) + ',';181 // // queryString += parseProperty(payload.caseManager) + ',';182 // // queryString += parseProperty(payload.caseManagerID) + ',';183 // // queryString += parseProperty(payload.phoneNumber) + ',';184 // queryString += parseProperty(payload.email) + ',';185 // // queryString += parseProperty(payload.dob) + ',';186 // // queryString += parseProperty(payload.intakeAge) + ',';187 // queryString += parseProperty(payload.providedID) + ',';188 // queryString += parseProperty(payload.stateID);189 // // queryString += parseProperty(payload.reference) + ',';190 // // queryString += parseProperty(payload.services) + ',';191 // // queryString += parseProperty(payload.disability) + ',';192 // // queryString += parseProperty(payload.lastGradeCompleted) + ',';193 // // queryString += parseProperty(payload.someCompleted) + ',';194 // // queryString += parseProperty(payload.currentlyAttending) + ',';195 // // queryString += parseProperty(payload.graduated) + ',';196 // // queryString += parseProperty(payload.firstLanguage) + ',';197 // // queryString += parseProperty(payload.preferredLanguage) + ',';198 // // queryString += parseProperty(payload.maritalStatus) + ',';199 // // queryString += parseProperty(payload.militaryService) + ',';200 // // queryString += parseProperty(payload.healthInsurance) + ',';201 // // queryString += parseProperty(payload.gender) + ',';202 // // queryString += parseProperty(payload.genderIdentification) + ',';203 // // queryString += parseProperty(payload.preferredPronoun) + ',';204 // // queryString += parseProperty(payload.ethnicity) + ',';205 // // queryString += parseProperty(payload.race) + ',';206 // // queryString += parseProperty(payload.lastSleepingLocation) + ',';207 // // queryString += parseProperty(payload.lastSleepingDuration) + ',';208 // // queryString += parseProperty(payload.firstDayFirstTimeHomeless) + ',';209 // // queryString += parseProperty(payload.currentHomelessStartDate) + ',';210 // // queryString += parseProperty(payload.currentHomelessLength) + ',';211 // // queryString += parseProperty(payload.homelessEpisodeCount) + ',';212 // // queryString += parseProperty(payload.locationBeforeWestLA) + ',';213 // // queryString += parseProperty(payload.durationInWestLA) + ',';214 // // queryString += parseProperty(payload.housingInstabilityCause) + ',';215 // // queryString += parseProperty(payload.stableHousingObstacle) + ',';216 // // queryString += parseProperty(payload.housingInterest) + ',';217 // // queryString += parseProperty(payload.naturalConnection) + ',';218 // // queryString += parseProperty(payload.contactName) + ',';219 // // queryString += parseProperty(payload.contactPhoneNumber) + ',';220 // // queryString += parseProperty(payload.contactRelationship) + ',';221 // // queryString += parseProperty(payload.currentlyPregnant) + ',';222 // // queryString += parseProperty(payload.firstPregnancy) + ',';223 // // queryString += parseProperty(payload.preNatalCareReceived) + ',';224 // // queryString += parseProperty(payload.preNatalCareLocation) + ',';225 // // queryString += parseProperty(payload.preNatalCareDesired) + ',';226 // // queryString += parseProperty(payload.trimester) + ',';227 // // queryString += parseProperty(payload.babyDueDate) + ',';228 // // queryString += parseProperty(payload.hasOtherChildren) + ',';229 // // queryString += parseProperty(payload.dcfsOpenCase) + ',';230 // // queryString += parseProperty(payload.childrenWithFamilyOrFriends) + ',';231 // // queryString += parseProperty(payload.substanceAbuse) + ',';232 // // queryString += parseProperty(payload.choiceSubstance) + ',';233 // // queryString += parseProperty(payload.injectedDrugs) + ',';234 // // queryString += parseProperty(payload.treatmentInterest) + ',';235 // // queryString += parseProperty(payload.mentalServicesReceived) + ',';236 // // queryString += parseProperty(payload.mentalServicesLocation) + ',';237 // // queryString += parseProperty(payload.mentalMedication) + ',';238 // // queryString += parseProperty(payload.helpAcquiringMedicine) + ',';239 // // queryString += parseProperty(payload.internalReferral) + ',';240 // // queryString += parseProperty(payload.externalReferral) + ',';241 // // queryString += parseProperty(payload.income) + ',';242 // // queryString += parseProperty(payload.birthCity) + ',';243 // // queryString += parseProperty(payload.birthState) + ',';244 // // queryString += parseProperty(payload.birthCountry) + ',';245 // // queryString += parseProperty(payload.employed) + ',';246 // // queryString += parseProperty(payload.lookingForEmployment) + ',';247 // // queryString += parseProperty(payload.fosterCare) + ',';248 // // queryString += parseProperty(payload.socialSecurityNumber) + ',';249 // // queryString += parseProperty(payload.caringForAnimals) + ',';250 // // queryString += parseProperty(payload.goodNeighborContract) + ',';251 // // queryString += parseProperty(payload.storyPhotoVideoAudioForm) + ',';252 // // queryString += parseProperty(payload.informationReleaseAuthorized) + ',';253 // // queryString += parseProperty(payload.servicesConsent) + ',';254 // // queryString += parseProperty(payload.showerInstructions) + ',';255 // // queryString += parseProperty(payload.showerGuidelines) + ',';256 // // queryString += parseProperty(payload.dropInGuidelines) + ',';257 // // queryString += parseProperty(payload.intakeConfirmation) + ',';258 // // queryString += parseProperty(payload.immediateNeedsConfirmation) + ',';259 // // queryString += parseProperty(payload.documentsSigned) + ',';260 // // queryString += parseProperty(payload.sleepingBag) + ',';261 // // queryString += parseProperty(payload.backpack) + ')';262 // queryString += ');';263 },264 // ** TODO: paramaterize all of these functions265 // ** parameterize queries!!! Taking user input and using it266 // directly in the query makes the code vulnerable to SQL injection267 // also, apostraphies in names could throw off syntax268 // This gets called in query.js by Queries module269 getAllCaseManagers: function () {270 var queryString = 'SELECT id, first_name, last_name FROM casemanager;';271 return queryString;272 },273 getClient: function (clientID) {274 // var queryString = 'SELECT id, first_name, last_name, intake_date, phone_number, email, ' +275 // 'date_of_birth, age(date_of_birth), status, caseplan FROM client WHERE id = ' +276 // '\'' + clientID + '\'' + ';';277 var queryString = 'SELECT id, first_name, last_name, intake_date, phone_number, email, ' +278 'date_of_birth, age(date_of_birth), caseplan FROM client WHERE id = ' +279 '\'' + clientID + '\'' + ';';280 return queryString;281 },282 searchClient: function (firstName, lastName) {283 // console.log(firstName);284 // console.log(lastName);285 var queryString = 'SELECT id, first_name, last_name FROM client WHERE';286 var setFirstName = false;287 if (firstName) {288 queryString += ' first_name = \'' + firstName + '\'';289 setFirstName = true;290 }291 if (lastName) {292 if (setFirstName) {293 queryString += ' AND';294 }295 queryString += ' last_name = \'' + lastName + '\'';296 }297 queryString += ';';298 return queryString;299 },300 getClients: function () {301 // var queryString = 'SELECT id, first_name, last_name, status, date_of_birth, phone_number, email FROM client;';302 var queryString = 'SELECT id, first_name, last_name, date_of_birth, phone_number, email FROM client;';303 return queryString;304 },305 createDropIn: function (payload) {306 var queryString = 'INSERT INTO drop_in (date) VALUES (\'' + payload.date + '\') RETURNING id, date;';307 return queryString;308 },309 getDropIns: function () {310 var queryString = 'SELECT id, date FROM drop_in;';311 return queryString;312 },313 getLatestDropIns: function (latest) {314 var queryString = 'SELECT * FROM drop_in ORDER BY date DESC LIMIT ' + latest + ';';315 return queryString;316 },317 getDropIn: function (dropin) {318 var queryString = 'SELECT id, date FROM drop_in WHERE id = ' +319 dropin + ';';320 return queryString;321 },322 createDropinActivities: function (payload) {323 var queryString = "";324 payload.forEach(function (element) {325 queryString += 'INSERT INTO match_drop_in_activity (drop_in_id, activity_id) VALUES( ' +326 element.dropinID + ', ' +327 element.activityID + '); ';328 });329 return queryString;330 },331 getDropinActivities: function (dropin) {332 var queryString = 'SELECT activity.id, activity.activity_name, match_drop_in_activity.room, ' +333 'match_drop_in_activity.comments, match_drop_in_activity.start_time, ' +334 'match_drop_in_activity.end_time, program.id AS program_id, program.program_name FROM activity, ' +335 'match_drop_in_activity, program WHERE activity.id = match_drop_in_activity.activity_id ' +336 'AND match_drop_in_activity.drop_in_id = ' + dropin + ' AND activity.program_id = program.id;';337 return queryString;338 },339 addActivitiesToDropIn: function (dropinID, payload) {340 var queryString = '';341 for (var i = 0; i < payload.activities.length; i++) {342 var local = payload.activities[i];343 queryString += 'INSERT INTO match_drop_in_activity (drop_in_id, activity_id';344 if (local.room) {345 queryString += ', room';346 }347 if (local.comments) {348 queryString += ', comments';349 }350 if (local.startTime) {351 queryString += ', start_time';352 }353 if (local.endTime) {354 queryString += ', end_time';355 }356 queryString += ') VALUES (\'' + dropinID + '\', \'' + local.id + '\'';357 if (local.room) {358 queryString += ', \'' + local.room + '\'';359 }360 if (local.comments) {361 queryString += ', \'' + local.comments + '\'';362 }363 if (local.startTime) {364 queryString += ', \'' + local.startTime + '\'';365 }366 if (local.endTime) {367 queryString += ', \'' + local.endTime + '\'';368 }369 queryString += '); ';370 }371 return queryString;372 },373 removeActivitiesFromDropin: function (dropinID, payload) {374 var queryString = '';375 payload.activities.forEach(function (activityID) {376 queryString += 'DELETE FROM enrollment WHERE enrollment.drop_in_activity_id = ' +377 '(SELECT match_drop_in_activity.id FROM match_drop_in_activity WHERE ' +378 'match_drop_in_activity.drop_in_id = ' +379 dropinID + ' AND match_drop_in_activity.activity_id = ' +380 activityID + '); DELETE FROM match_drop_in_activity WHERE ' +381 'match_drop_in_activity.drop_in_id = ' +382 dropinID + ' AND match_drop_in_activity.activity_id = ' +383 activityID + ' RETURNING match_drop_in_activity.activity_id;';384 });385 return queryString;386 },387 getDropinActivity: function (dropinID, activityID) {388 var queryString = 'SELECT activity.id, activity.activity_name, match_drop_in_activity.room, ' +389 'match_drop_in_activity.comments, match_drop_in_activity.start_time, ' +390 'match_drop_in_activity.end_time, program.id AS program_id, program.program_name ' +391 'FROM activity, match_drop_in_activity, program WHERE activity.id = ' +392 'match_drop_in_activity.activity_id AND match_drop_in_activity.drop_in_id = ' +393 dropinID + ' AND match_drop_in_activity.activity_id = ' +394 activityID + ' AND activity.program_id = program.id;';395 return queryString;396 },397 getDropinActivityEnrollment: function (dropinID, activityID) {398 var queryString = 'SELECT client.id, client.first_name, client.last_name FROM client WHERE ' +399 'client.id IN (SELECT enrollment.client_id FROM enrollment, match_drop_in_activity ' +400 'WHERE enrollment.drop_in_activity_id = match_drop_in_activity.id AND ' +401 'match_drop_in_activity.drop_in_id = ' + dropinID +402 ' AND match_drop_in_activity.activity_id = ' + activityID + ');';403 return queryString;404 },405 addEnrollmentToDropinActivity: function (dropinID, activityID, payload) {406 var queryString = '';407 payload.clients.forEach(function (clientID) {408 queryString += 'INSERT INTO enrollment (drop_in_activity_id, client_id) SELECT ' +409 'match_drop_in_activity.id, \'' + clientID + '\' FROM match_drop_in_activity WHERE ' +410 'match_drop_in_activity.drop_in_id = ' +411 dropinID + ' AND match_drop_in_activity.activity_id = ' +412 activityID + ' AND NOT EXISTS (SELECT enrollment.id FROM enrollment, match_drop_in_activity ' +413 'WHERE enrollment.client_id = ' + clientID + ' AND enrollment.drop_in_activity_id = ' +414 'match_drop_in_activity.id AND match_drop_in_activity.drop_in_id = ' +415 dropinID + ' AND match_drop_in_activity.activity_id = ' +416 activityID + ') RETURNING client_id;';417 });418 return queryString;419 },420 removeEnrollmentToDropinActivity: function (dropinID, activityID, payload) {421 var queryString = "";422 payload.clients.forEach(function (clientID) {423 queryString += 'DELETE FROM enrollment WHERE enrollment.drop_in_activity_id = ' +424 '(SELECT match_drop_in_activity.id FROM match_drop_in_activity WHERE ' +425 'match_drop_in_activity.drop_in_id = ' + dropinID + ' AND match_drop_in_activity.activity_id = ' +426 activityID + ') AND enrollment.client_id = ' + clientID + ' RETURNING client_id;';427 });428 return queryString;429 },430 getDropinEnrollment: function (dropinID) {431 var queryString = 'SELECT client_id, activity_id FROM enrollment WHERE drop_in_id =' + dropinID + ';';432 return queryString;433 },434 getAllActivities: function () {435 var queryString = 'SELECT activity.id, activity.activity_name, activity.location, activity.ongoing, ' +436 'activity.start_time, activity.end_time, activity.program_id AS program_id, ' +437 'program.program_name FROM activity, program WHERE activity.program_id = program.id;';438 return queryString;439 },440 getActivity: function (activity) {441 var queryString = 'SELECT activity.id, activity.activity_name, activity.location, activity.ongoing, ' +442 'activity.start_time, activity.end_time, activity.program_id AS program_id, program.program_name ' +443 'FROM activity, program WHERE activity.program_id = program.id AND activity.id = ' + activity + ';';444 return queryString;445 },446 getActivityDropIns: function (activity) {447 var queryString = 'SELECT drop_in.id, drop_in.date, match_drop_in_activity.room, ' +448 'match_drop_in_activity.comments, match_drop_in_activity.start_time, ' +449 'match_drop_in_activity.end_time FROM drop_in, match_drop_in_activity ' +450 'WHERE drop_in.id = match_drop_in_activity.drop_in_id ' +451 'AND match_drop_in_activity.activity_id = ' + activity + ';';452 return queryString;453 },454 editClient: function (payload) {455 var queryString = 'UPDATE client SET ';456 queryString += 'first_name = ' + '\'' + parseProperty(payload.firstName) + '\'' + ', ';457 queryString += 'last_name = ' + '\'' + parseProperty(payload.lastName) + '\'' + ', ';458 // queryString += 'nickname = ' + parseProperty(payload.nickname) + ',';459 if (parseProperty(payload.birthday)) {460 queryString += 'date_of_birth = ' + '\'' + parseProperty(payload.birthday) + '\'' + ', ';461 }462 // queryString += 'intake_age = ' + '\'' + parseProperty(payload.age) + '\'' + ', ';463 queryString += 'phone_number = ' + '\'' + parseProperty(payload.phoneNumber) + '\'' + ', ';464 queryString += 'email = ' + '\'' + parseProperty(payload.email) + '\'' + ', ';465 // queryString += 'last_meeting = ' + '\'' + parseProperty(payload.lastMeeting) + '\'' + ',';466 queryString += 'case_manager = ' + '\'' + parseProperty(payload.caseManager) + '\' '; // + ', ';467 // if (parseProperty(payload.status)) {468 // queryString += 'status = ' + '\'' + parseProperty(payload.status) + '\'' + ' ';469 // } else {470 // queryString += 'status = ' + '\'1\'' + ' ';471 // }472 queryString += 'WHERE id = ' + '\'' + payload.id + '\'' + ' ';473 queryString += 'RETURNING id, first_name, last_name, date_of_birth, ' +474 'age(date_of_birth), phone_number, email, case_manager;'; // , status;';475 return queryString;476 },477 createActivity: function (payload) {478 var queryString = 'INSERT INTO activity (';479 var payloadNames = [];480 var props = [];481 var params = [];482 var activityPropNames = activityProperties.map(function (element) {483 return element.toLowerCase().replace(/_/g, '');484 });485 for (var property in payload) {486 var index = activityPropNames.indexOf(property.toLowerCase());487 if (index !== -1) {488 props.push(activityProperties[index]);489 payloadNames.push(property);490 }491 }492 props.forEach(function (element, index) {493 queryString += props[index] + ', ';494 });495 queryString = queryString.slice(0, queryString.lastIndexOf(','));496 queryString += ') VALUES (';497 payloadNames.forEach(function (element, index) {498 queryString += '$' + (index + 1) + ', ';499 params.push(parseProperty(payload[payloadNames[index]]));500 });501 queryString = queryString.slice(0, queryString.lastIndexOf(','));502 queryString += ') RETURNING ';503 props.forEach(function (element) {504 queryString += element + ', ';505 });506 queryString = queryString.slice(0, queryString.lastIndexOf(','));507 queryString += ';';508 var queryData = {509 string: queryString,510 params: params511 };512 return queryData;513 },514 editActivity: function (payload) {515 var queryString = 'UPDATE activity SET ';516 queryString += 'activity_name = ' + parseProperty(payload.activity_name) + ',';517 queryString += 'ongoing = ' + parseProperty(payload.onGoing) + ',';518 queryString += 'start_date = ' + parseProperty(payload.startDate) + ',';519 queryString += 'end_date = ' + parseProperty(payload.endDate) + ',';520 queryString += 'WHERE id = ' + payload.id;521 return queryString;522 },523 enroll: function (payload) {524 var queryString = "";525 payload.forEach(function (element) {526 queryString += 'INSERT INTO enrollment (drop_in_id, client_id, activity_id) VALUES( ' +527 element.dropinID + ', ' +528 element.clientID + ', ' +529 element.activityID + '); ';530 });531 return queryString;532 },533 getEnrollmentByActivity: function (activityID) {534 var queryString = "SELECT client_id FROM enrollment WHERE activity_id = " + activityID + ";";535 return queryString;536 },537 addCheckinForDropin: function (dropinID, payload) {538 var queryString = "";539 payload.clients.forEach(function (clientID) {540 queryString += 'INSERT INTO check_in (drop_in_id, client_id) SELECT \'' +541 dropinID + '\', \'' +542 clientID + '\' WHERE NOT EXISTS (SELECT id FROM check_in WHERE drop_in_id = \'' +543 dropinID + '\' AND client_id = \'' +544 clientID + '\') RETURNING drop_in_id, client_id;';545 });546 return queryString;547 },548 removeCheckinForDropin: function (dropinID, payload) {549 var queryString = "";550 payload.clients.forEach(function (clientID) {551 queryString += 'DELETE FROM check_in WHERE drop_in_id = ' + dropinID + ' AND ' +552 'client_id = ' + clientID + ' RETURNING client_id;';553 });554 return queryString;555 },556 getCheckInForDropin: function (dropinID) {557 var queryString = 'SELECT client_id FROM check_in WHERE drop_in_id = ' + dropinID + ';';558 return queryString;559 },560 dataBrowserGetClients: function () {561 var queryString = 'SELECT * FROM client;';562 return queryString;563 },564 dataBrowserSearchClients: function (data) {565 var TYPE_STRING = 1043;566 var TYPE_INT = 23;567 var TYPE_BOOL = 16;568 var searchText = "";569 var operators = ["=", "!=", ">", "<"];570 if (data.columnType === TYPE_STRING) {571 searchText = ' LIKE \'' + (data.status === 1 ? data.data : '%' + data.data + '%') + '\'';572 } else if (data.columnType === TYPE_INT) {573 searchText = ' ' + operators[data.status] + ' ' + data.data;574 } else if (data.columnType === TYPE_BOOL) {575 if (data.status === 0 || data.status === 1) {576 searchText = ' = ' + (data.status === 0 ? 'true' : 'false');577 } else {578 searchText = ' IS ' + (data.status === 2 ? 'NOT ' : '') + 'NULL';579 }580 } else { // DATE: 1082581 if (data.status < 4) {582 searchText = operators[data.status] + ' \'' + data.data + '\'';583 } else { 584 searchText = (data.status === 5 ? ' NOT' : '') + ' BETWEEN ' + '\'' + 585 data.data + '\' AND \'' + data.secondData + '\'';586 }587 }588 var queryString = 'SELECT * FROM client WHERE ' +589 data.column + searchText + ';';590 return queryString;591 },592 createCaseNote: function (payload) {593 var queryString = 'INSERT INTO case_note (client_id, case_manager_id, date, category, ' +594 'note, follow_up_needed, due_date, reminder_date) VALUES (' +595 '\'' + parseProperty(payload.clientID) + '\'' + ', ' +596 '\'' + parseProperty(payload.caseManagerID) + '\'' + ', ' +597 '\'' + parseProperty(payload.date) + '\'' + ', ' +598 '\'' + parseProperty(payload.category) + '\'' + ', ' +599 '\'' + parseProperty(payload.note) + '\'' + ', ' +600 '\'' + parseProperty(payload.followUpNeeded) + '\'' + ', ';601 if (parseProperty(payload.dueDate) === null) {602 queryString += 'null, ';603 } else {604 queryString += '\'' + parseProperty(payload.dueDate) + '\'' + ', ';605 }606 if (parseProperty(payload.reminderDate) === null) {607 queryString += 'null);';608 } else {609 queryString += '\'' + parseProperty(payload.reminderDate) + '\'' + ');';610 }611 return queryString;612 },613 getClientCaseNotes: function (clientID) {614 var queryString = 'SELECT n.id, client_id, case_manager_id, date, category, first_name, ' +615 'last_name, note, follow_up_needed, due_date, reminder_date FROM case_note n LEFT JOIN ' +616 'casemanager m ON n.case_manager_id = m.id WHERE client_id = ' + clientID + ';';617 return queryString;618 },619 getCaseNote: function (noteID) {620 var queryString = 'SELECT n.id, client_id, case_manager_id, date, category, first_name, ' +621 'last_name, note, follow_up_needed, due_date, reminder_date FROM case_note n LEFT JOIN ' +622 'casemanager m ON n.case_manager_id = m.id WHERE n.id = ' + noteID + ';';623 return queryString;624 },625 editCaseNote: function (payload) {626 var queryString = 'UPDATE case_note SET ';627 queryString += 'client_id = ' + '\'' + parseProperty(payload.clientID) + '\'' + ',';628 queryString += 'case_manager_id = ' + '\'' + parseProperty(payload.caseManagerID) + '\'' + ',';629 queryString += 'date = ' + '\'' + parseProperty(payload.date) + '\'' + ',';630 queryString += 'note = ' + '\'' + parseProperty(payload.note) + '\'' + ',';631 queryString += 'category = ' + '\'' + parseProperty(payload.category) + '\'' + ',';632 queryString += 'follow_up_needed = ' + '\'' + parseProperty(payload.followUpNeeded) + '\'' + ',';633 if (parseProperty(payload.dueDate) === null) {634 queryString += 'due_date = null, ';635 } else {636 queryString += 'due_date = ' + '\'' + parseProperty(payload.dueDate) + '\'' + ', ';637 }638 if (parseProperty(payload.reminderDate) === null) {639 queryString += 'reminder_date = null ';640 } else {641 queryString += 'reminder_date = ' + '\'' + parseProperty(payload.reminderDate) + '\'' + ' ';642 }643 queryString += 'WHERE id = ' + '\'' + payload.id + '\'' + ' ';644 queryString += 'RETURNING client_id, case_manager_id, date, note, follow_up_needed, due_date, reminder_date;';645 console.log(queryString);646 return queryString;647 },648 getUserList: function () {649 var queryString = 'SELECT id, username FROM users;';650 return queryString;651 },652 getUserByQuery: function (query) {653 var queryString = 'SELECT id, username, hashed_password FROM users WHERE';654 var setId = false;655 if (query.id) {656 queryString += ' id = \'' + query.id + '\'';657 setId = true;658 }659 if (query.username) {660 if (setId) {661 queryString += ' AND';662 }663 queryString += ' username = \'' + query.username + '\'';664 }665 queryString += ';';666 return queryString;667 },668 createUser: function (payload) {669 var queryString = 'INSERT INTO users ("username", "hashed_password") VALUES (\'' +670 payload.username + '\', \'' +671 payload.password + '\');';672 return queryString;673 },674 updateUser: function (userId, payload) {675 var queryString = 'UPDATE users SET username = \'' + payload.username +676 '\' WHERE id = \'' + userId + '\';';677 return queryString;678 },679 getUsersNotifications: function (userId) {680 var queryString = 'SELECT id, type, comment, link, checked FROM notifications WHERE user_id = ' + userId +681 ' AND checked = false ORDER BY id;';682 return queryString;683 },684 createNotification: function (userId, payload) {685 var queryString = 'INSERT INTO notifications (';686 queryString += 'user_id';687 if (payload.type) {688 queryString += ', type';689 }690 if (payload.comment) {691 queryString += ', comment';692 }693 if (payload.link) {694 queryString += ', link';695 }696 if (payload.checked) {697 queryString += ', checked';698 }699 queryString += ') VALUES (' + userId;700 if (payload.type) {701 queryString += ', \'' + payload.type + '\'';702 }703 if (payload.comment) {704 queryString += ', \'' + payload.comment + '\'';705 }706 if (payload.link) {707 queryString += ', \'' + payload.link + '\'';708 }709 if (payload.checked) {710 queryString += ', \'' + payload.checked + '\'';711 }712 queryString += ') RETURNING id, user_id, type, comment, link, checked;';713 return queryString;714 },715 getNotificationById: function (noteId) {716 var queryString = 'SELECT id, user_id, type, comment, link, checked FROM notifications ' +717 'WHERE id = \'' + noteId + '\';';718 return queryString;719 },720 updateUsersNotification: function (noteId, payload) {721 var queryString = 'UPDATE notifications SET ';722 if (payload.type) {723 queryString += 'type = \'' + payload.type + '\',';724 }725 if (payload.comment) {726 queryString += 'comment = \'' + payload.comment + '\',';727 }728 if (payload.link) {729 queryString += 'link = \'' + payload.link + '\',';730 }731 if (typeof payload.checked === 'boolean') {732 queryString += 'checked = \'' + payload.checked + '\',';733 }734 queryString = queryString.substring(0, queryString.length - 1);735 queryString += ' WHERE id = \'' + noteId + '\' RETURNING id, user_id, type, comment, link, checked;';736 return queryString;737 },738 getNotificationTypes: function () {739 var queryString = 'SELECT * FROM notification_types;';740 return queryString;741 },742 getUserSettings: function (userId) {743 var queryString = 'SELECT user_id, settings_data FROM settings WHERE user_id = ' + userId + ';';744 return queryString;745 },746 changeUserPassword: function (userId, hashedPassword) {747 var queryString = 'UPDATE users SET hashed_password = \'' + hashedPassword +748 '\' WHERE id = ' + userId + ';';749 return queryString;750 },751 deleteUser: function (userId) {752 var queryString = 'DELETE FROM users WHERE id = ' + userId + ';';753 return queryString;754 },755 // getStatuses: function () {756 // var queryString = 'SELECT id, name, color FROM status;';757 // return queryString;758 // },759 // createStatus: function (payload) {760 // var queryString = 'INSERT INTO status (name, color) VALUES(\'' +761 // payload.name + '\', \'' +762 // payload.color + '\') RETURNING id, name, color;';763 // return queryString;764 // },765 // editStatus: function (statusID, payload) {766 // // just updating all of them for now?767 // var queryString = 'UPDATE status SET ' +768 // 'name = \'' + payload.name + '\', ' +769 // 'color = \'' + payload.color + '\' ' +770 // 'WHERE id = \'' + statusID + '\'' +771 // 'RETURNING id, name, color;';772 // return queryString;773 // },774 // ** 775 getFlagTypes: function () {776 var queryString = 'SELECT id, name, color, settings FROM flag_type;';777 return queryString;778 },779 getFlags: function () {780 var queryString = 'SELECT id, client_id, type, message, note, settings FROM flag;';781 return queryString;782 },783 createFlagType: function (payload) {784 var queryString = 'INSERT INTO flag_type (name, color, settings) VALUES (\'' +785 payload.name + '\', \'' +786 payload.color + '\', \'' +787 payload.settings + '\' ) RETURNING id, name, color, settings;';788 return queryString;789 },790 editFlagType: function (flagtypeID, payload) {791 // just updating all of them for now?792 var settings = { 793 defaults: { 794 message: payload.message, 795 note: payload.note 796 }797 };798 var queryString = 'UPDATE flag_type SET ' +799 'name = \'' + payload.typeName + '\', ' +800 'color = \'' + payload.color + '\', ' +801 'settings = \'' + JSON.stringify(settings) + '\' ' +802 // 'message = \'' + payload.message + '\', ' +803 // 'note = \'' + payload.note + '\' ' +804 'WHERE id = ' + flagtypeID +805 // ' RETURNING id, type, message, color, note;';806 ' RETURNING id, name, color, settings;';807 return queryString;808 },809 getClientFlags: function (clientID) {810 var queryString = 'SELECT id, type, message, note, settings FROM flag WHERE client_id = ' + clientID + ';';811 return queryString;812 },813 setClientFlag: function (payload) {814 console.log(payload);815 var queryString = 'INSERT INTO flag (client_id, type, message, note, settings) VALUES (' +816 payload.clientID + ', ' + 817 payload.typeID + ', ' +818 '\'' + payload.message + '\', \'' + 819 payload.note + '\', \'' + 820 payload.settings + '\') RETURNING id, client_id, type, message, note, settings;';821 console.log(queryString);822 return queryString;823 },824 editClientFlag: function (payload) {825 var queryString = 'UPDATE flag SET ' +826 'message = \'' + payload.message + '\', ' +827 'note = \'' + payload.note + '\', ' +828 'settings = \'' + payload.settings + '\' ' +829 'WHERE id = ' + payload.flagID + ' ' +830 'RETURNING id, client_id, type, message, note, settings;';831 return queryString;832 },833 // ** 834 uploadFile: function (payload) {835 var queryString = 'INSERT INTO file (client_id, name, type, date, base_64_string) VALUES (\'' +836 payload.clientID + '\', \'' +837 payload.name + '\', \'' +838 payload.type + '\', \'' +839 payload.date + '\', \'' +840 payload.fileString + '\');';841 return queryString;842 },843 deleteFile: function (fileID) {844 var queryString = 'DELETE FROM file WHERE id = ' + fileID + ';';845 return queryString;846 },847 getClientFiles: function (clientID) {848 var queryString = 'SELECT id, name, type, date, base_64_string FROM file WHERE client_id = ' + clientID + ';';849 return queryString;850 },851 getProfilePicture: function (clientID) {852 var queryString = 'SELECT name, type, base_64_string FROM file WHERE client_id = ' + clientID +853 'AND type=\'profile_picture\'' +854 'AND id = (SELECT MAX(id) FROM file WHERE client_id = ' + clientID +855 ' AND type=\'profile_picture\');';856 return queryString;857 },858 createCasePlan: function (payload) {859 var queryString = 'INSERT INTO caseplan (client_id, case_manager_id, date, note, ) VALUES (' +860 '\'' + parseProperty(payload.clientID) + '\'' + ', ' +861 '\'' + parseProperty(payload.caseManagerID) + '\'' + ', ' +862 '\'' + parseProperty(payload.date) + '\'' + ', ' +863 '\'' + parseProperty(payload.note) + '\'' + ', ';864 return queryString;865 },866 editCasePlan: function (payload) {867 var queryString = 'UPDATE client SET ';868 queryString += 'caseplan = ' + '\'' + payload.text + '\'' + ' ';869 queryString += 'WHERE id = ' + '\'' + payload.clientID + '\'' + ' ';870 queryString += 'RETURNING caseplan;';871 return queryString;872 },873 getCasePlan: function (clientID) {874 var queryString = 'SELECT caseplan FROM client WHERE id =' + clientID + ";";875 return queryString;876 },877 getPrograms: function () {878 var queryString = 'SELECT program_name FROM program';879 return queryString;880 },881 getAllFollowUps: function () {882 var queryString = 'SELECT id, timestamp, note, casemanager_id, client_id, location FROM follow_up;';883 return queryString;884 },885 getFollowUp: function (id) {886 var queryString = 'SELECT id, timestamp, note, casemanager_id, ' +887 'client_id, location FROM follow_up WHERE id = ' + id + ';';888 return queryString;889 },890 getCaseManagerFollowUps: function (casemanagerID) {891 var queryString = 'SELECT id, timestamp, note, casemanager_id, ' +892 'client_id, location FROM follow_up WHERE casemanager_id = ' + casemanagerID + ';';893 return queryString;894 },895 editFollowUp: function (payload) {896 var queryString = 'UPDATE follow_up SET ';897 queryString += 'timestamp = \'' + parseProperty(payload.timestamp) + '\', ';898 queryString += 'note = \'' + parseProperty(payload.note) + '\', ';899 queryString += 'casemanager_id = \'' + parseProperty(payload.casemanagerID) + '\', ';900 queryString += 'client_id = \'' + parseProperty(payload.clientID) + '\', ';901 queryString += 'location = \'' + parseProperty(payload.location) + '\' ';902 queryString += 'WHERE id = ' + payload.id + ';';903 return queryString;904 },905 createFollowUp: function (payload) {906 var queryString = 'INSERT INTO follow_up (timestamp, note, casemanager_id, client_id, location) VALUES (';907 queryString += '\'' + parseProperty(payload.timestamp) + '\', ';908 queryString += '\'' + parseProperty(payload.note) + '\', ';909 queryString += '\'' + parseProperty(payload.casemanagerID) + '\', ';910 queryString += '\'' + parseProperty(payload.clientID) + '\', ';911 queryString += '\'' + parseProperty(payload.location) + '\');';912 return queryString;913 },914 deleteFollowUp: function (id) {915 var queryString = 'DELETE FROM follow_up WHERE id = ' + id + ';';916 return queryString;917 },918 uploadSpreadsheet: function (formdata) {919 var removeEmptyArrays = function (data) {920 data = 921 data.filter(function (e) {922 return e.length !== 0;923 });924 return data;925 };...
property-test.js
Source:property-test.js
...23 altDefinitionCollection24 );25};26// parseProperty takes: name, joiObj, parameterType, useDefinitions, isAlt27// i.e. propertiesNoAlt.parseProperty('x', Joi.object(), null, true, false);28// i.e. propertiesAlt.parseProperty('x', Joi.object(), null, true, true);29lab.experiment('property - ', () => {30 lab.test('parse types', () => {31 clearDown();32 expect(propertiesNoAlt.parseProperty('x', null, null, true, false)).to.equal(undefined);33 });34 // parseProperty(name, joiObj, parent, parameterType, useDefinitions, isAlt)35 lab.test('parse types', () => {36 clearDown();37 //console.log(JSON.stringify(propertiesNoAlt.parseProperty('x', Joi.any(), null, null, true, false)));38 expect(propertiesNoAlt.parseProperty('x', Joi.object(), null, 'body', true, false)).to.equal({39 $ref: '#/definitions/x'40 });41 expect(propertiesNoAlt.parseProperty('x', Joi.string(), null, 'body', true, false)).to.equal({42 type: 'string'43 });44 expect(propertiesNoAlt.parseProperty('x', Joi.number(), null, 'body', true, false)).to.equal({45 type: 'number'46 });47 expect(propertiesNoAlt.parseProperty('x', Joi.boolean(), null, 'body', true, false)).to.equal({48 type: 'boolean'49 });50 expect(propertiesNoAlt.parseProperty('x', Joi.date(), null, 'body', true, false)).to.equal({51 type: 'string',52 format: 'date'53 });54 expect(propertiesNoAlt.parseProperty('x', Joi.binary(), null, 'body', true, false)).to.equal({55 type: 'string',56 format: 'binary'57 });58 expect(propertiesNoAlt.parseProperty('x', Joi.array(), null, 'body', true, false)).to.equal({59 $ref: '#/definitions/Model1'60 });61 expect(propertiesNoAlt.parseProperty('x', Joi.any(), null, 'body', true, false)).to.equal({ type: 'string' });62 //expect(propertiesNoAlt.parseProperty('x', Joi.func(), null, 'body', true, false)).to.equal({ 'type': 'string' });63 });64 lab.test('parse types with useDefinitions=false', () => {65 clearDown();66 expect(propertiesNoAlt.parseProperty('x', Joi.object(), null, 'body', false, false)).to.equal({67 type: 'object'68 });69 expect(propertiesNoAlt.parseProperty('x', Joi.string(), null, 'body', false, false)).to.equal({70 type: 'string'71 });72 expect(propertiesNoAlt.parseProperty('x', Joi.number(), null, 'body', false, false)).to.equal({73 type: 'number'74 });75 expect(propertiesNoAlt.parseProperty('x', Joi.boolean(), null, 'body', false, false)).to.equal({76 type: 'boolean'77 });78 expect(propertiesNoAlt.parseProperty('x', Joi.date(), null, 'body', false, false)).to.equal({79 type: 'string',80 format: 'date'81 });82 expect(propertiesNoAlt.parseProperty('x', Joi.binary(), null, 'body', false, false)).to.equal({83 type: 'string',84 format: 'binary'85 });86 expect(propertiesNoAlt.parseProperty('x', Joi.array(), null, 'body', false, false)).to.equal({87 type: 'array',88 name: 'x',89 items: { type: 'string' }90 });91 });92 lab.test('parse simple meta', () => {93 clearDown();94 expect(95 propertiesNoAlt.parseProperty('x', Joi.string().description('this is bob'), null, 'body', true, false)96 ).to.equal({ type: 'string', description: 'this is bob' });97 expect(propertiesAlt.parseProperty('x', Joi.string().example('bob'), null, 'body', true, false)).to.equal({98 type: 'string',99 example: 'bob'100 });101 expect(propertiesAlt.parseProperty('x', Joi.allow('').example(''), null, 'body', true, false)).to.equal({102 type: 'string',103 example: ''104 });105 });106 lab.test('parse meta', () => {107 clearDown();108 // TODO add all meta data properties109 expect(propertiesAlt.parseProperty('x', Joi.string().meta({ x: 'y' }), null, 'body', true, false)).to.equal({110 type: 'string',111 'x-meta': { x: 'y' }112 });113 expect(propertiesNoAlt.parseProperty('x', Joi.string().forbidden(), null, 'body', true, false)).to.equal(undefined);114 expect(propertiesNoAlt.parseProperty('x', Joi.string().required(), null, 'body', true, false)).to.equal({115 type: 'string'116 }); // required in parent117 expect(propertiesNoAlt.parseProperty('x', Joi.any().required(), null, 'body', true, false)).to.equal({118 type: 'string'119 }); // required in parent120 expect(propertiesNoAlt.parseProperty('x', Joi.any().forbidden(), null, 'body', true, false)).to.equal(undefined);121 expect(propertiesNoAlt.parseProperty('x', Joi.string().valid('a', 'b'), null, 'body', true, false)).to.equal({122 type: 'string',123 enum: ['a', 'b']124 });125 expect(propertiesNoAlt.parseProperty('x', Joi.string().valid('a', 'b', ''), null, 'body', true, false)).to.equal({126 type: 'string',127 enum: ['a', 'b']128 });129 expect(130 propertiesNoAlt.parseProperty('x', Joi.string().valid('a', 'b', null), null, 'body', true, false)131 ).to.equal({ type: 'string', enum: ['a', 'b'] });132 expect(133 propertiesNoAlt.parseProperty(134 'x',135 Joi.date()136 .timestamp()137 .default(() => Date.now())138 ).default139 ).to.exist();140 //console.log(JSON.stringify(propertiesAlt.parseProperty('x',Joi.date().timestamp().default(() => Date.now(), 'Current Timestamp'))));141 const nonNegativeWithDropdown = propertiesAlt.parseProperty(142 'x',143 Joi.number()144 .integer()145 .positive()146 .allow(0),147 null,148 'body',149 true,150 false151 );152 const nonNegativeWithoutDropdown = propertiesAlt.parseProperty(153 'x',154 Joi.number()155 .integer()156 .positive()157 .allow(0)158 .meta({ disableDropdown: true }),159 null,160 'body',161 true,162 false163 );164 expect(nonNegativeWithDropdown).to.include({ enum: [0] });165 expect(nonNegativeWithoutDropdown).to.not.include({ enum: [0] });166 });167 lab.test('parse type string', () => {168 clearDown();169 expect(propertiesNoAlt.parseProperty('x', Joi.string(), null, 'body', true, false)).to.equal({170 type: 'string'171 });172 expect(propertiesNoAlt.parseProperty('x', Joi.string().min(5), null, 'body', true, false)).to.equal({173 type: 'string',174 minLength: 5175 });176 expect(propertiesNoAlt.parseProperty('x', Joi.string().max(10), null, 'body', true, false)).to.equal({177 type: 'string',178 maxLength: 10179 });180 expect(181 propertiesNoAlt.parseProperty('x', Joi.string().regex(/^[a-zA-Z0-9]{3,30}/), null, 'body', true, false)182 ).to.equal({183 type: 'string',184 pattern: '^[a-zA-Z0-9]{3,30}'185 });186 // covers https://github.com/glennjones/hapi-swagger/issues/652 -187 // make sure we aren't truncating the regex after an internal '/',188 // and make sure we omit any regex flags (g, i, m) from the189 // resulting pattern190 expect(191 propertiesNoAlt.parseProperty('x', Joi.string().regex(/^https:\/\/test.com/mi), null, 'body', true, false)192 ).to.equal({193 type: 'string',194 pattern: '^https:\\/\\/test.com'195 });196 expect(propertiesAlt.parseProperty('x', Joi.string().length(0, 'utf8'), null, 'body', true, false)).to.equal({197 type: 'string',198 'x-constraint': { length: 0 }199 });200 expect(propertiesAlt.parseProperty('x', Joi.string().length(20, 'utf8'), null, 'body', true, false)).to.equal({201 type: 'string',202 'x-constraint': { length: 20 }203 });204 //expect(propertiesNoAlt.parseProperty('x', Joi.string().insensitive())).to.equal({ 'type': 'string', 'x-constraint': { 'insensitive': true } });205 expect(propertiesAlt.parseProperty('x', Joi.string().creditCard(), null, 'body', true, false)).to.equal({206 type: 'string',207 'x-format': { creditCard: true }208 });209 expect(propertiesAlt.parseProperty('x', Joi.string().alphanum(), null, 'body', true, false)).to.equal({210 type: 'string',211 'x-format': { alphanum: true }212 });213 expect(propertiesAlt.parseProperty('x', Joi.string().token(), null, 'body', true, false)).to.equal({214 type: 'string',215 'x-format': { token: true }216 });217 const result = propertiesAlt.parseProperty(218 'x',219 Joi.string().email({220 tlds: {221 allow: ['example.com']222 },223 minDomainSegments: 2224 }),225 null,226 true,227 true228 );229 expect(result.type).to.equal('string');230 expect(result['x-format'].email.tlds.allow).to.exist();231 expect(result['x-format'].email.minDomainSegments).to.equal(2);232 expect(233 propertiesAlt.parseProperty(234 'x',235 Joi.string().ip({236 version: ['ipv4', 'ipv6'],237 cidr: 'required'238 }),239 null,240 true,241 true242 )243 ).to.equal({244 type: 'string',245 'x-format': {246 ip: {247 version: ['ipv4', 'ipv6'],248 cidr: 'required'249 }250 }251 });252 /* TODO fix this so that regexp work or document the fact it does not work253 expect(propertiesNoAlt.parseProperty('x', Joi.string().uri({254 scheme: [255 'git',256 /git\+https?/257 ]258 }))).to.equal({ 'type': 'string', 'x-format': {259 'uri': {260 'scheme': [261 'git',262 {}263 ]264 }265 } });266 */267 expect(propertiesAlt.parseProperty('x', Joi.string().guid(), null, 'body', true, true)).to.equal({268 type: 'string',269 'x-format': { guid: true }270 });271 expect(propertiesAlt.parseProperty('x', Joi.string().hex(), null, 'body', true, true)).to.equal({272 type: 'string',273 'x-format': { hex: { byteAligned: false } }274 });275 expect(propertiesAlt.parseProperty('x', Joi.string().guid(), null, 'body', true, true)).to.equal({276 type: 'string',277 'x-format': { guid: true }278 });279 expect(propertiesAlt.parseProperty('x', Joi.string().hostname(), null, 'body', true, true)).to.equal({280 type: 'string',281 'x-format': { hostname: true }282 });283 expect(propertiesAlt.parseProperty('x', Joi.string().isoDate(), null, 'body', true, true)).to.equal({284 type: 'string',285 'x-format': { isoDate: true }286 });287 expect(propertiesAlt.parseProperty('x', Joi.string().lowercase(), null, 'body', true, true)).to.equal({288 type: 'string',289 'x-convert': { case: 'lower' }290 });291 expect(propertiesAlt.parseProperty('x', Joi.string().uppercase(), null, 'body', true, true)).to.equal({292 type: 'string',293 'x-convert': { case: 'upper' }294 });295 expect(propertiesAlt.parseProperty('x', Joi.string().trim(), null, 'body', true, true)).to.equal({296 type: 'string',297 'x-convert': { trim: true }298 });299 // test options.xProperties = false300 expect(propertiesNoAlt.parseProperty('x', Joi.string().lowercase(), null, 'body', true, false)).to.equal({301 type: 'string'302 });303 });304 lab.test('parse type date', () => {305 clearDown();306 expect(propertiesNoAlt.parseProperty('x', Joi.date(), null, 'body', true, false)).to.equal({307 type: 'string',308 format: 'date'309 });310 expect(propertiesNoAlt.parseProperty('x', Joi.date().min('1-1-1974'), null, 'body', true, false)).to.equal({311 type: 'string',312 format: 'date'313 });314 expect(propertiesNoAlt.parseProperty('x', Joi.date().min('now'), null, 'body', true, false)).to.equal({315 type: 'string',316 format: 'date'317 });318 expect(propertiesNoAlt.parseProperty('x', Joi.date().min(Joi.ref('y')), null, 'body', true, false)).to.equal({319 type: 'string',320 format: 'date'321 });322 expect(propertiesNoAlt.parseProperty('x', Joi.date().max('1-1-1974'), null, 'body', true, false)).to.equal({323 type: 'string',324 format: 'date'325 });326 expect(propertiesNoAlt.parseProperty('x', Joi.date().max('now'), null, 'body', true, false)).to.equal({327 type: 'string',328 format: 'date'329 });330 expect(propertiesNoAlt.parseProperty('x', Joi.date().max(Joi.ref('y')), null, 'body', true, false)).to.equal({331 type: 'string',332 format: 'date'333 });334 expect(335 propertiesNoAlt.parseProperty(336 'x',337 Joi.date()338 .min('1-1-1974')339 .max('now'),340 null,341 'body',342 true,343 false344 )345 ).to.equal({ type: 'string', format: 'date' });346 /* not yet 'x',347 date.min(date)348 date.max(date)349 date.format(format)350 date.iso()351 */352 });353 lab.test('parse type date timestamp', () => {354 clearDown();355 expect(propertiesNoAlt.parseProperty('x', Joi.date().timestamp(), null, 'body', true, false)).to.equal({356 format: 'date', type: 'string'357 });358 });359 lab.test('parse type number', () => {360 clearDown();361 // mapped direct to openapi362 expect(propertiesNoAlt.parseProperty('x', Joi.number().integer(), null, 'body', true, false)).to.equal({363 type: 'integer'364 });365 expect(propertiesNoAlt.parseProperty('x', Joi.number().min(5), null, 'body', true, false)).to.equal({366 type: 'number',367 minimum: 5368 });369 expect(propertiesNoAlt.parseProperty('x', Joi.number().max(10), null, 'body', true, false)).to.equal({370 type: 'number',371 maximum: 10372 });373 // x-* mappings374 expect(propertiesAlt.parseProperty('x', Joi.number().greater(10), null, 'body', true, true)).to.equal({375 type: 'number',376 'x-constraint': { greater: 10 }377 });378 expect(propertiesAlt.parseProperty('x', Joi.number().less(10), null, 'body', true, true)).to.equal({379 type: 'number',380 'x-constraint': { less: 10 }381 });382 expect(propertiesAlt.parseProperty('x', Joi.number().precision(2), null, 'body', true, true)).to.equal({383 type: 'number',384 'x-constraint': { precision: 2 }385 });386 expect(propertiesAlt.parseProperty('x', Joi.number().multiple(2), null, 'body', true, true)).to.equal({387 type: 'number',388 'x-constraint': { multiple: 2 }389 });390 expect(propertiesAlt.parseProperty('x', Joi.number().positive(), null, 'body', true, true)).to.equal({391 type: 'number',392 'x-constraint': { sign: 'positive' }393 });394 expect(propertiesAlt.parseProperty('x', Joi.number().negative(), null, 'body', true, true)).to.equal({395 type: 'number',396 'x-constraint': { sign: 'negative' }397 });398 // test options.xProperties = false399 expect(propertiesNoAlt.parseProperty('x', Joi.number().greater(10), null, 'body', true, false)).to.equal({400 type: 'number'401 });402 });403 lab.test('parse type array', () => {404 clearDown();405 //console.log(JSON.stringify(propertiesNoAlt.parseProperty('x', Joi.array(), null, false, false)));406 // basic child types407 expect(propertiesNoAlt.parseProperty('x', Joi.array(), null, 'body', false, false)).to.equal({408 type: 'array',409 name: 'x',410 items: { type: 'string' }411 });412 expect(propertiesNoAlt.parseProperty('x', Joi.array().items(), null, 'body', false, false)).to.equal({413 type: 'array',414 name: 'x',415 items: { type: 'string' }416 });417 expect(propertiesNoAlt.parseProperty('x', Joi.array().items(Joi.object()), null, 'body', false, false)).to.equal({418 type: 'array',419 name: 'x',420 items: { type: 'object' }421 });422 expect(propertiesNoAlt.parseProperty('x', Joi.array().items(Joi.string()), null, 'body', false, false)).to.equal({423 type: 'array',424 name: 'x',425 items: { type: 'string' }426 });427 expect(propertiesNoAlt.parseProperty('x', Joi.array().items(Joi.number()), null, 'body', false, false)).to.equal({428 type: 'array',429 name: 'x',430 items: { type: 'number' }431 });432 expect(propertiesNoAlt.parseProperty('x', Joi.array().items(Joi.boolean()), null, 'body', false, false)).to.equal({433 type: 'array',434 name: 'x',435 items: { type: 'boolean' }436 });437 expect(propertiesNoAlt.parseProperty('x', Joi.array().items(Joi.date()), null, 'body', false, false)).to.equal({438 type: 'array',439 name: 'x',440 items: { type: 'string', format: 'date' }441 });442 expect(propertiesNoAlt.parseProperty('x', Joi.array().items(Joi.binary()), null, 'body', false, false)).to.equal({443 type: 'array',444 name: 'x',445 items: { type: 'string', format: 'binary' }446 });447 // complex child types - arrays and objects448 clearDown();449 //console.log(JSON.stringify(propertiesNoAlt.parseProperty('x', Joi.array().items({ 'text': Joi.string() }), null, 'formData', true, false)));450 expect(propertiesNoAlt.parseProperty('x', Joi.array().items(Joi.string()), null, 'formData', true, false)).to.equal(451 {452 $ref: '#/definitions/x'453 }454 );455 //console.log(JSON.stringify(definitionCollection));456 expect(definitionCollection).to.equal({457 x: {458 type: 'array',459 items: {460 type: 'string'461 },462 collectionFormat: 'multi'463 }464 });465 // TODO466 // Joi.array().items(Joi.array().items(Joi.string())467 // make sure type features such as string().min(1)in array items are past into JSON468 expect(469 propertiesNoAlt.parseProperty('x', Joi.array().items(Joi.string().min(1)), null, 'body', false, false)470 ).to.equal({ type: 'array', items: { type: 'string', minLength: 1 }, name: 'x' });471 // mapped direct to openapi472 expect(propertiesNoAlt.parseProperty('x', Joi.array().min(5), null, 'body', false, false)).to.equal({473 type: 'array',474 name: 'x',475 items: { type: 'string' },476 minItems: 5477 });478 expect(propertiesNoAlt.parseProperty('x', Joi.array().max(10), null, 'body', false, false)).to.equal({479 type: 'array',480 name: 'x',481 items: { type: 'string' },482 maxItems: 10483 });484 // x-* mappings485 expect(propertiesAlt.parseProperty('x', Joi.array().sparse(), null, 'body', false, false)).to.equal({486 type: 'array',487 name: 'x',488 items: { type: 'string' },489 'x-constraint': { sparse: true }490 });491 expect(propertiesAlt.parseProperty('x', Joi.array().single(), null, 'body', false, false)).to.equal({492 type: 'array',493 name: 'x',494 items: { type: 'string' },495 'x-constraint': { single: true }496 });497 expect(propertiesAlt.parseProperty('x', Joi.array().length(0), null, 'body', false, false)).to.equal({498 type: 'array',499 name: 'x',500 items: { type: 'string' },501 'x-constraint': { length: 0 }502 });503 expect(propertiesAlt.parseProperty('x', Joi.array().length(2), null, 'body', false, false)).to.equal({504 type: 'array',505 name: 'x',506 items: { type: 'string' },507 'x-constraint': { length: 2 }508 });509 // https://github.com/hapijs/joi/pull/1511510 expect(propertiesAlt.parseProperty('x', Joi.array().unique(), null, 'body', false, false)).to.equal({511 type: 'array',512 name: 'x',513 items: { type: 'string' },514 'x-constraint': { unique: true }515 });516 // test options.xProperties = false517 expect(propertiesNoAlt.parseProperty('x', Joi.array().sparse(), null, 'body', false, false)).to.equal({518 type: 'array',519 name: 'x',520 items: { type: 'string' }521 });522 });523});524lab.test('parse type object', () => {525 clearDown();526 //console.log(JSON.stringify( propertiesNoAlt.parseProperty('x', Joi.object(), {}, {}, 'formData') ));527 expect(propertiesNoAlt.parseProperty('x', Joi.object(), null, 'body', false, false)).to.equal({ type: 'object' });528 expect(propertiesNoAlt.parseProperty('x', Joi.object().keys(), null, 'body', false, false)).to.equal({ type: 'object' });529 expect(530 propertiesNoAlt.parseProperty('x', Joi.object().keys({ a: Joi.string() }), null, 'body', false, false)531 ).to.equal({532 name: 'x',533 type: 'object',534 properties: {535 a: {536 type: 'string'537 }538 }539 });540 expect(propertiesNoAlt.parseProperty('x', Joi.object({ a: Joi.string() }), null, 'body', false, false)).to.equal({541 name: 'x',542 type: 'object',543 properties: {544 a: {545 type: 'string'546 }547 }548 });549 expect(propertiesNoAlt.parseProperty('x', Joi.object({ a: Joi.string() }), null, 'body', false, false)).to.equal({550 name: 'x',551 type: 'object',552 properties: {553 a: {554 type: 'string'555 }556 }557 });558 // test without pattern schema example559 expect(propertiesNoAlt.parseProperty('x', Joi.object().pattern(Joi.string(), Joi.object({560 y: Joi.string()561 })), null, 'body', false, false)).to.equal({562 name: 'x',563 type: 'object',564 properties: {565 string: {566 name: 'string',567 type: 'object',568 properties: {569 'y': {570 type: 'string'571 }572 }573 }574 }575 });576 // test with pattern schema example577 expect(propertiesNoAlt.parseProperty('x', Joi.object().pattern(Joi.string().example('a'), Joi.object({578 y: Joi.string()579 })), null, 'body', false, false)).to.equal({580 name: 'x',581 type: 'object',582 properties: {583 a: {584 name: 'a',585 type: 'object',586 properties: {587 'y': {588 type: 'string'589 }590 }591 }592 }593 });594 // test with regex as pattern595 expect(propertiesNoAlt.parseProperty('x', Joi.object().pattern(/\w\d/, Joi.object({596 y: Joi.string()597 })), null, 'body', false, false)).to.equal({598 name: 'x',599 type: 'object',600 properties: {601 string: {602 name: 'string',603 type: 'object',604 properties: {605 'y': {606 type: 'string'607 }608 }609 }610 }611 });612});613lab.experiment('property deep - ', () => {614 clearDown();615 const deepStructure = Joi.object({616 outer1: Joi.object({617 inner1: Joi.string()618 .description('child description')619 .note('child notes')620 .tag('child', 'api')621 .required()622 .label('inner1')623 }),624 outer2: Joi.object({625 inner2: Joi.number()626 .description('child description')627 .note('child notes')628 .tag('child', 'api')629 .min(5)630 .max(10)631 .required()632 .label('inner2')633 })634 });635 //console.log(JSON.stringify( propertiesNoAlt.parseProperty( deepStructure, {}, {}, null, false ) ));636 lab.test('parse structure with child labels', () => {637 //console.log(JSON.stringify( propertiesNoAlt.parseProperty(null, deepStructure, null, false, false) ));638 expect(propertiesNoAlt.parseProperty(null, deepStructure, null, 'body', false, false)).to.equal({639 type: 'object',640 properties: {641 outer1: {642 name: 'outer1',643 type: 'object',644 properties: {645 inner1: {646 type: 'string',647 description: 'child description',648 notes: ['child notes'],649 tags: ['child', 'api']650 }651 },652 required: ['inner1']653 },654 outer2: {655 name: 'outer2',656 type: 'object',657 properties: {658 inner2: {659 type: 'number',660 description: 'child description',661 notes: ['child notes'],662 tags: ['child', 'api'],663 minimum: 5,664 maximum: 10665 }666 },667 required: ['inner2']668 }669 }670 });671 });672 lab.test('parse structure with child description, notes, name etc', async () => {673 clearDown();674 const routes = [675 {676 method: 'POST',677 path: '/path/two',678 options: {679 tags: ['api'],680 handler: Helper.defaultHandler,681 response: {682 schema: deepStructure683 }684 }685 }686 ];687 const server = await Helper.createServer({}, routes);688 const response = await server.inject({ method: 'GET', url: '/swagger.json' });689 //console.log(JSON.stringify(response.result.definitions));690 expect(response.result.definitions.outer1).to.equal({691 properties: {692 inner1: {693 description: 'child description',694 type: 'string',695 notes: ['child notes'],696 tags: ['child', 'api']697 }698 },699 required: ['inner1'],700 type: 'object'701 });702 });703});704lab.experiment('joi extension - ', () => {705 lab.test('custom joi extension', () => {706 clearDown();707 const extension = Joi.extend({708 base: Joi.string(),709 type: 'myCustomName'710 });711 expect(propertiesNoAlt.parseProperty('x', extension.myCustomName(), null, 'body', true, false)).to.equal({712 type: 'string'713 });714 });...
properties.js
Source:properties.js
...7const expect = Code.expect;8const lab = exports.lab = Lab.script();9lab.experiment('property - ', () => {10 lab.test('parse types', (done) => {11 expect(Properties.parseProperty('x', Joi.string())).to.deep.equal({ 'type': 'string' });12 expect(Properties.parseProperty('x', Joi.number())).to.deep.equal({ 'type': 'number' });13 expect(Properties.parseProperty('x', Joi.boolean())).to.deep.equal({ 'type': 'boolean' });14 expect(Properties.parseProperty('x', Joi.date())).to.deep.equal({ 'type':'string','format':'date' });15 expect(Properties.parseProperty('x', Joi.binary())).to.deep.equal({ 'type':'string','format':'binary' });16 expect(Properties.parseProperty('x', Joi.array())).to.deep.equal({17 'type': 'array',18 'items': {19 'type': 'string'20 }21 });22 done();23 });24 lab.test('parse type string', (done) => {25 expect(Properties.parseProperty('x', Joi.string())).to.deep.equal({ 'type': 'string' });26 /* not yet 'x',27 string.insensitive()28 string.min(limit, [encoding])29 string.max(limit, [encoding])30 string.creditCard()31 string.length(limit, [encoding])32 string.regex(pattern, [name])33 string.replace(pattern, replacement)34 string.alphanum()35 string.token()36 string.email([options])37 string.ip([options])38 string.uri([options])39 string.guid()40 string.hex()41 string.hostname()42 string.lowercase()43 string.uppercase()44 string.trim()45 string.isoDate()46 */47 done();48 });49 lab.test('parse type date', (done) => {50 expect(Properties.parseProperty('x', Joi.date())).to.deep.equal({ 'type': 'string', 'format': 'date' });51 /* not yet 'x',52 date.min(date)53 date.max(date)54 date.format(format)55 date.iso()56 */57 done();58 });59 lab.test('parse type number', (done) => {60 expect(Properties.parseProperty('x', Joi.number().integer())).to.deep.equal({ 'type': 'integer' });61 expect(Properties.parseProperty('x', Joi.number().min(5))).to.deep.equal({ 'type': 'number', 'minimum': 5 });62 expect(Properties.parseProperty('x', Joi.number().max(10))).to.deep.equal({ 'type': 'number', 'maximum': 10 });63 /* not yet 'x',64 expect( Properties.parseProperty('x',Joi.number().greater(10))).to.deep.equal( {'type':'number'} );65 expect( Properties.parseProperty('x',Joi.number().less(10))).to.deep.equal( {'type':'number'} );66 expect( Properties.parseProperty('x',Joi.number().integer())).to.deep.equal( {'type':'integer'} );67 expect( Properties.parseProperty('x',Joi.number().precision(2))).to.deep.equal( {'type':'number'} );68 expect( Properties.parseProperty('x',Joi.number().multiple(2))).to.deep.equal( {'type':'number'} );69 expect( Properties.parseProperty('x',Joi.number().positive())).to.deep.equal( {'type':'number'} );70 expect( Properties.parseProperty('x',Joi.number().negative())).to.deep.equal( {'type':'number'} );71 */72 done();73 });74 lab.test('parse type array', (done) => {75 // basic child types76 expect(Properties.parseProperty('x', Joi.array())).to.deep.equal({ 'type': 'array', 'items': { 'type': 'string' } });77 expect(Properties.parseProperty('x', Joi.array().items())).to.deep.equal({ 'type': 'array', 'items': { 'type': 'string' } });78 expect(Properties.parseProperty('x', Joi.array().items(Joi.string()))).to.deep.equal({ 'type': 'array', 'items': { 'type': 'string' } });79 expect(Properties.parseProperty('x', Joi.array().items(Joi.number()))).to.deep.equal({ 'type': 'array', 'items': { 'type': 'number' } });80 expect(Properties.parseProperty('x', Joi.array().items(Joi.boolean()))).to.deep.equal({ 'type': 'array', 'items': { 'type': 'boolean' } });81 expect(Properties.parseProperty('x', Joi.array().items(Joi.date()))).to.deep.equal({ 'type': 'array', 'items': { 'type': 'string', 'format': 'date' } });82 expect(Properties.parseProperty('x', Joi.array().items(Joi.binary()))).to.deep.equal({ 'type': 'array', 'items': { 'type': 'string', 'format': 'binary' } });83 // complex child types84 expect(Properties.parseProperty('x', Joi.array().items({ 'text': Joi.string() }), {}, 'formData')).to.deep.equal({85 'type': 'array',86 'items': {87 '$ref': '#/definitions/x'88 },89 'collectionFormat': 'multi'90 });91 expect(Properties.parseProperty('x', Joi.array().items(Joi.object({ 'text': Joi.string() })), {}, 'formData')).to.deep.equal({92 'type': 'array',93 'items': {94 '$ref': '#/definitions/x'95 },96 'collectionFormat': 'multi'97 });98 expect(Properties.parseProperty('x', Joi.array().items(Joi.object({ 'text': Joi.string() })), {}, 'query')).to.deep.equal({99 'type': 'array',100 'items': {101 '$ref': '#/definitions/x'102 },103 'collectionFormat': 'multi'104 });105 // expect(Properties.parseProperty('x', Joi.array().items({ 'count': Joi.number() }))).to.deep.equal({ 'type': 'array', 'items': { '$ref': '#/definitions/x' } });106 expect(Properties.parseProperty('x', Joi.array().min(5))).to.deep.equal({ 'type': 'array', 'items': { 'type': 'string' }, 'minItems': 5 });107 expect(Properties.parseProperty('x', Joi.array().max(10))).to.deep.equal({ 'type': 'array', 'items': { 'type': 'string' }, 'maxItems': 10 });108 /* not yet 'x-',109 array.sparse(enabled)110 array.single(enabled)111 array.ordered(type)112 array.length(limit)113 array.unique()114 */115 done();116 });117 lab.test('parse type object', (done) => {118 //console.log(JSON.stringify(Properties.parseProperty('x', Joi.object({ 'text': Joi.string() }), {}, [], 'formData' )));119 /* Change from inline to definiation objects120 expect(Properties.parseProperty('x', Joi.object({ 'text': Joi.string() }))).to.deep.equal({ 'type': 'object', 'name': 'x', 'properties': { 'text': { 'type': 'string' } } });121 expect(Properties.parseProperty('x', Joi.object().keys({ 'text': Joi.string() }))).to.deep.equal({ 'type': 'object', 'name': 'x', 'properties': { 'text': { 'type': 'string' } } });122 */123 expect(Properties.parseProperty('x', Joi.object({ 'text': Joi.string() }), {}, [], 'formData')).to.deep.equal({ 'type': 'object', 'name': 'x', 'schema': { '$ref': '#/definitions/x' } });124 expect(Properties.parseProperty('x', Joi.object().keys({ 'text': Joi.string() }), {}, [], 'formData')).to.deep.equal({ 'type': 'object', 'name': 'x', 'schema': { '$ref': '#/definitions/x' } });125 /* not yet 'x-',126 {}127 object.min(limit)128 object.max(limit)129 object.length(limit)130 object.pattern(regex, schema)131 object.and(peers)132 object.nand(peers)133 object.or(peers)134 object.xor(peers)135 object.with(key, peers)136 object.without(key, peers)137 object.rename(from, to, [options])138 object.assert(ref, schema, [message])139 object.unknown([allow])140 object.type(constructor, [name])141 object.requiredKeys(children)142 object.optionalKeys(children)143 */144 done();145 });146 lab.test('parse description', (done) => {147 expect(Properties.parseProperty('x', Joi.string().description('text description'))).to.deep.equal({ 'type': 'string', 'description': 'text description' });148 done();149 });150 lab.test('parse notes', (done) => {151 expect(Properties.parseProperty('x', Joi.string().notes('text notes'))).to.deep.equal({ 'type': 'string', 'notes': ['text notes'] });152 expect(Properties.parseProperty('x', Joi.string().notes(['text notes', 'text notes']))).to.deep.equal({ 'type': 'string', 'notes': ['text notes', 'text notes'] });153 done();154 });155 lab.test('parse tags', (done) => {156 expect(Properties.parseProperty('x', Joi.string().tags(['api', 'v2']))).to.deep.equal({ 'type': 'string', 'tags': ['api', 'v2'] });157 done();158 });159 lab.test('parse allow', (done) => {160 expect(Properties.parseProperty('x', Joi.string().allow('decimal', 'binary'))).to.deep.equal({ 'type': 'string', 'enum': ['decimal', 'binary'] });161 expect(Properties.parseProperty('x', Joi.number().allow(1,2,3,4,5))).to.deep.equal({ 'type': 'number', 'enum': [1,2,3,4,5] });162 expect(Properties.parseProperty('x', Joi.string().allow('decimal', 'binary', ''))).to.deep.equal({ 'type': 'string', 'enum': ['decimal', 'binary'] });163 expect(Properties.parseProperty('x', Joi.string().allow(''))).to.deep.equal({ 'type': 'string' });164 expect(Properties.parseProperty('x', Joi.string().allow(null))).to.deep.equal({ 'type': 'string' });165 //console.log(JSON.stringify(Properties.parseProperty('x', Joi.array().allow('a','b','c'), {}, 'query')))166 expect(Properties.parseProperty('x', Joi.array().allow('a', 'b', 'c'), {}, 'query')).to.deep.equal({167 'type': 'array',168 'enum': ['a', 'b', 'c'],169 'items': {170 'type': 'string'171 },172 'collectionFormat': 'multi'173 });174 done();175 });176 lab.test('parse valid', (done) => {177 expect(Properties.parseProperty('x', Joi.string().valid('decimal', 'binary'))).to.deep.equal({ 'type': 'string', 'enum': ['decimal', 'binary'] });178 expect(Properties.parseProperty('x', Joi.number().valid(1,2,3,4,5))).to.deep.equal({ 'type': 'number', 'enum': [1,2,3,4,5] });179 expect(Properties.parseProperty('x', Joi.string().valid('decimal', 'binary', ''))).to.deep.equal({ 'type': 'string', 'enum': ['decimal', 'binary'] });180 expect(Properties.parseProperty('x', Joi.string().valid(''))).to.deep.equal({ 'type': 'string' });181 done();182 });183 lab.test('parse required', (done) => {184 expect(Properties.parseProperty('x', Joi.string().required())).to.deep.equal({ 'type': 'string', 'required': true });185 done();186 });187 lab.test('parse optional', (done) => {188 expect(Properties.parseProperty('x', Joi.string().optional())).to.deep.equal({ 'type': 'string', 'required': false });189 done();190 });191 lab.test('parse example', (done) => {192 //console.log(Properties.parseProperty('x', Joi.array().items(Joi.string()).example(['example','value'])));193 expect(Properties.parseProperty('x', Joi.string().example('example value'))).to.deep.equal({ 'type': 'string', 'example': 'example value' });194 expect(Properties.parseProperty('x', Joi.number().example(5))).to.deep.equal({ 'type': 'number', 'example': 5 });195 expect(Properties.parseProperty('x', Joi.array().items(Joi.string()).example(['example','value']))).to.deep.equal({196 type: 'array',197 example: ['example','value'],198 items: {199 type: 'string'200 }201 });202 done();203 });204 lab.test('parse default', (done) => {205 // TODO x- the description ie any.default([value, [description]])206 expect(Properties.parseProperty('x', Joi.string().valid('decimal', 'binary').default('decimal'))).to.deep.equal({ 'type': 'string', 'enum': ['decimal', 'binary'], 'default': 'decimal' });207 done();208 });209 lab.test('parse forbidden', (done) => {210 expect(Properties.parseProperty('x', Joi.string().forbidden())).to.deep.equal(undefined);211 done();212 });213 lab.test('parse label', (done) => {214 // this example has both child object labels and array labels215 let definition = {};216 const parsed = Properties.parseProperties(217 Joi.object().keys( {218 ans_list: Joi.array().items(219 Joi.object().keys( {220 v1: Joi.number(),221 v2: Joi.number()222 } ).label('ans-o')223 ).label('ans-l')224 } ).label('ans-parent'), definition, 'query');225 const parsedExpected = {226 'ans_list': {227 type: 'array',228 items: {229 '$ref': '#/definitions/ans-o'230 },231 collectionFormat: 'multi'232 }233 };234 const definitionExpected = {235 'ans-o': {236 'type': 'object',237 'properties': {238 'v1': {239 'type': 'number'240 },241 'v2': {242 'type': 'number'243 }244 }245 }246 };247 expect(parsed).to.deep.equal(parsedExpected);248 expect(definition).to.deep.equal(definitionExpected);249 done();250 });251 /* not yet 'x',252 any.invalid(value)253 any.strip()254 any.meta(meta)255 any.unit(name)256 any.options(options)257 any.strict(isStrict)258 any.concat(schema)259 any.when(ref, options)260 any.label(name)261 any.raw(isRaw)262 any.empty(schema)263 */264 lab.test('parse default with function', (done) => {265 // TODO review memory issue that may come with this266 const dateStr = new Date().toISOString();267 expect(Properties.parseProperty('x', Joi.string().default(268 function () {269 return dateStr;270 }, 'default date'))).to.deep.equal({ 'type': 'string', 'default': dateStr });271 done();272 });273 lab.test('toParameters', (done) => {274 const joiStructure = Joi.object({275 a: Joi.number()276 .required()277 .description('the first number'),278 b: Joi.number()279 .required()280 .description('the second number'),281 operator: Joi.string()...
utils.js
Source:utils.js
...11import {DEFAULT_LANGUAGE} from './constants';12export function parseActions(node) {13 const actions = {};14 node.actions.forEach((item) => {15 actions.name = parseProperty(actions, item, 'name');16 actions.description = parseProperty(actions, item, 'description');17 actions.executionType = parseProperty(actions, item, 'execution-type');18 actions.priority = parseProperty(actions, item, 'priority');19 actions.script = parseProperty(actions, item, 'script');20 });21 return actions;22}23export function parseAssignments(node) {24 const assignments = {};25 const autoCreateValues = [];26 const roleNames = [];27 const roleTypes = [];28 const users = [];29 node.assignments.forEach((item) => {30 const itemKeys = Object.keys(item);31 if (itemKeys.includes('resource-action')) {32 assignments.assignmentType = ['resourceActions'];33 assignments.resourceAction = item['resource-action'];34 }35 else if (itemKeys.includes('role-id')) {36 assignments.assignmentType = ['roleId'];37 assignments.roleId = parseInt(item['role-id'], 10);38 }39 else if (itemKeys.includes('role-type')) {40 assignments.assignmentType = ['roleType'];41 autoCreateValues.push(item['auto-create']);42 roleNames.push(item.name);43 roleTypes.push(item['role-type']);44 }45 else if (itemKeys.includes('script')) {46 assignments.assignmentType = ['scriptedAssignment'];47 assignments.script = [item.script];48 assignments.scriptLanguage = item['script-language'];49 }50 else if (itemKeys.includes('user')) {51 assignments.assignmentType = ['user'];52 }53 else if (itemKeys.includes('email-address')) {54 assignments.assignmentType = ['user'];55 users.push(item['email-address']);56 }57 });58 if (users.length) {59 assignments.emailAddress = users;60 }61 if (assignments.assignmentType[0] === 'roleType') {62 assignments.autoCreate = autoCreateValues[0];63 assignments.roleName = roleNames[0];64 assignments.roleType = roleTypes[0];65 }66 return assignments;67}68export function parseReassignments(node) {69 const assignments = {};70 const autoCreateValues = [];71 const roleNames = [];72 const roleTypes = [];73 const users = [];74 node.assignments.forEach((item) => {75 const itemKeys = Object.keys(item);76 if (itemKeys.includes('resource-action')) {77 assignments.assignmentType = ['resourceActions'];78 assignments.resourceAction = item['resource-action'];79 }80 else if (itemKeys.includes('role')) {81 assignments.assignmentType = ['roleId'];82 assignments.roleId = parseInt(item['role'], 10);83 }84 else if (itemKeys.includes('role-type')) {85 assignments.assignmentType = ['roleType'];86 autoCreateValues.push(item['auto-create']);87 roleNames.push(item.name);88 roleTypes.push(item['role-type']);89 }90 else if (itemKeys.includes('script')) {91 assignments.assignmentType = ['scriptedAssignment'];92 assignments.script = [item.script];93 assignments.scriptLanguage = item['script-language'];94 }95 else if (itemKeys.includes('user')) {96 assignments.assignmentType = ['user'];97 }98 else if (itemKeys.includes('email-address')) {99 assignments.assignmentType = ['user'];100 users.push(item['email-address']);101 }102 });103 if (users.length) {104 assignments.emailAddress = users;105 }106 if (assignments.assignmentType[0] === 'roleType') {107 assignments.autoCreate = autoCreateValues[0];108 assignments.roleName = roleNames[0];109 assignments.roleType = roleTypes[0];110 }111 return assignments;112}113export function parseNotifications(node) {114 const notifications = {notificationTypes: [], recipients: []};115 node.notifications.forEach((item, index) => {116 notifications.description = parseProperty(117 notifications,118 item,119 'description'120 );121 notifications.executionType = parseProperty(122 notifications,123 item,124 'execution-type'125 );126 notifications.name = parseProperty(notifications, item, 'name');127 let notificationTypes = parseProperty(128 notifications,129 item,130 'notification-type'131 );132 if (Array.isArray(notificationTypes[0])) {133 var typeArray = [];134 notificationTypes[0].forEach((type) => {135 typeArray.push({notificationType: type});136 });137 notificationTypes = typeArray;138 }139 else {140 notificationTypes = [{notificationType: notificationTypes[0]}];141 }142 notifications.notificationTypes[index] = notificationTypes;143 notifications.template = parseProperty(notifications, item, 'template');144 notifications.templateLanguage = parseProperty(145 notifications,146 item,147 'template-language'148 );149 if (item.assignees) {150 notifications.recipients[index] = {151 assignmentType: ['taskAssignees'],152 };153 }154 else if (155 item['user'] &&156 item['user'].some((item) => item['email-address'])157 ) {158 const emailAddress = [];159 item['user'].forEach((item) => {160 emailAddress.push(item['email-address']);161 });162 notifications.recipients[index] = {163 assignmentType: ['user'],164 emailAddress,165 };166 }167 else if (item['role-type']) {168 notifications.recipients[index] = {169 assignmentType: ['roleType'],170 autoCreate: item['auto-create'],171 roleName: item['role-name'],172 roleType: item['role-type'],173 };174 }175 else if (item['role-id']) {176 notifications.recipients[index] = {177 assignmentType: ['roleId'],178 roleId: item['role-id'][0],179 };180 }181 else if (item['scripted-recipient']) {182 const script = item['scripted-recipient'][0].script;183 notifications.recipients[index] = {184 assignmentType: ['scriptedRecipient'],185 script: [script],186 scriptLanguage: [DEFAULT_LANGUAGE],187 };188 }189 else {190 notifications.recipients[index] = {191 assignmentType: ['user'],192 };193 }194 });195 return notifications;196}197function parseProperty(data, item, property) {198 let newProperty = property;199 if (property === 'execution-type') {200 newProperty = 'executionType';201 }202 else if (property === 'template-language') {203 newProperty = 'templateLanguage';204 }205 if (Array.isArray(data[newProperty])) {206 data[newProperty].push(item[property]);207 return data[newProperty];208 }209 return new Array(item[property]);210}211export function parseTimers(node) {212 const taskTimers = {};213 taskTimers.delay = [];214 taskTimers.reassignments = [];215 taskTimers.timerActions = [];216 taskTimers.timerNotifications = [];217 node.taskTimers.forEach((item, index) => {218 taskTimers.delay.push({219 duration: node.taskTimers[index].duration,220 scale: node.taskTimers[index].scale,221 });222 taskTimers.reassignments.push(223 node.taskTimers[index]['reassignments']224 ? parseReassignments({225 assignments: node.taskTimers[index]['reassignments'],226 })227 : {}228 );229 taskTimers.timerActions.push(230 node.taskTimers[index]['timer-action']231 ? parseActions({232 actions: node.taskTimers[index]['timer-action'],233 })234 : {}235 );236 taskTimers.timerNotifications.push({});237 taskTimers.name = parseProperty(taskTimers, item, 'name');238 taskTimers.description = parseProperty(taskTimers, item, 'description');239 taskTimers.blocking = parseProperty(taskTimers, item, 'blocking');240 });241 return taskTimers;...
schema.test.js
Source:schema.test.js
...39 });40 suite('parseProperty', function () {41 test('can parse using built-in property type', function () {42 var schemaPropDef = processSchema({type: 'vec3'});43 var parsed = parseProperty('1 2 3', schemaPropDef);44 assert.shallowDeepEqual(parsed, {x: 1, y: 2, z: 3});45 });46 test('uses default value if value is falsy', function () {47 var schemaPropDef = processSchema({type: 'int', default: 2});48 assert.equal(parseProperty(null, schemaPropDef), 2);49 assert.equal(parseProperty('', schemaPropDef), 2);50 assert.equal(parseProperty(undefined, schemaPropDef), 2);51 assert.equal(parseProperty(0, schemaPropDef), 0);52 });53 test('can parse using inline parse', function () {54 var schemaPropDef = {55 default: 'xyz',56 parse: function (val) { return val.toUpperCase(); }57 };58 var parsed = parseProperty('abc', schemaPropDef);59 assert.equal(parsed, 'ABC');60 });61 test('returns already-parsed value', function () {62 var schemaPropDef = processSchema({type: 'vec3'});63 var parsed = parseProperty({x: 0, y: 0, z: 0}, schemaPropDef);64 assert.shallowDeepEqual(parsed, {x: 0, y: 0, z: 0});65 });66 test('allows undefined default', function () {67 var schemaPropDef = processSchema({type: 'vec3', default: undefined});68 var parsed = parseProperty(undefined, schemaPropDef);69 assert.shallowDeepEqual(parsed, undefined);70 });71 });72 suite('parseProperties', function () {73 test('parses multiple properties', function () {74 var schema = processSchema({75 position: {type: 'vec3', default: {x: 0, y: 0, z: 0}},76 scale: {type: 'vec3', default: '0 0 0'},77 src: {type: 'asset'},78 visible: {type: 'boolean'},79 width: {type: 'int', default: 2}80 });81 var parsed = parseProperties({82 position: '1 2 3',...
parseProperty.test.js
Source:parseProperty.test.js
...6describe('test parseProperty', () => {7 it('should be off market', () => {8 const htmlPath = path.join(__dirname, 'resources', 'property.html');9 const html = fs.readFileSync(htmlPath);10 const propertyDetails = parseProperty(html);11 expect(propertyDetails).toEqual({12 brokerage: "",13 dateUpdated: "01/17/2018",14 daysOnMarket: "",15 latestEvent: "Estimated",16 latestEventDate: "Today",17 latestEventPrice: "$120,000",18 latestEventPriceSqft: "â",19 latestEventSource: "",20 phone: "",21 realtor: "",22 realtorLink: "",23 status: 'Off Market',24 });25 });26});27describe('test parseProperty', () => {28 it('should be just sold', () => {29 const htmlPath = path.join(__dirname, 'resources', 'sold.html');30 const html = fs.readFileSync(htmlPath);31 const propertyDetails = parseProperty(html);32 expect(propertyDetails).toEqual({33 brokerage: "Total Real Estate Services, LLC",34 dateUpdated: "01/17/2018",35 daysOnMarket: "57",36 latestEvent: "Sold",37 latestEventDate: "09/08/2017",38 latestEventPrice: "-",39 latestEventPriceSqft: "â",40 latestEventSource: "Houston",41 phone: "",42 realtor: "Diane Hermis Schrakamp",43 realtorLink: "/realestateagents/Diane-Hermis-Schrakamp_Houston_TX_1414591_796744491",44 status: 'Just sold',45 });46 });47});48describe('test parseProperty', () => {49 it('all price history fields should be blank', () => {50 const htmlPath = path.join(__dirname, 'resources', 'noHistory.html');51 const html = fs.readFileSync(htmlPath);52 const propertyDetails = parseProperty(html);53 expect(propertyDetails).toEqual({54 brokerage: "",55 dateUpdated: "01/31/2018",56 daysOnMarket: "",57 latestEvent: "",58 latestEventDate: "",59 latestEventPrice: "",60 latestEventPriceSqft: "",61 latestEventSource: "",62 phone: "",63 realtor: "",64 realtorLink: "",65 status: "Off Market",66 });67 });68});69describe('test parseProperty', () => {70 it('should get listing info', () => {71 const htmlPath = path.join(__dirname, 'resources', 'listed.html');72 const html = fs.readFileSync(htmlPath);73 const propertyDetails = parseProperty(html);74 expect(propertyDetails).toEqual({75 brokerage: "Keller Williams Realty Katy",76 dateUpdated: null,77 daysOnMarket: "",78 latestEvent: "",79 latestEventDate: "",80 latestEventPrice: "",81 latestEvent: "Price Changed",82 latestEventDate: "02/17/2018",83 latestEventPrice: "$365,000",84 latestEventPriceSqft: "$124",85 latestEventSource: "Houston",86 phone: "(281) 220-2100",87 realtor: "Amy Kristynik",88 realtorLink: null,89 status: "For Sale",90 });91 });92});93describe('test parseProperty', () => {94 it('should get listing info', () => {95 const htmlPath = path.join(__dirname, 'resources', 'listed2.html');96 const html = fs.readFileSync(htmlPath);97 const propertyDetails = parseProperty(html);98 expect(propertyDetails).toEqual({99 brokerage: "Keller Williams Realty Katy",100 dateUpdated: null,101 daysOnMarket: "",102 latestEvent: "",103 latestEventDate: "",104 latestEventPrice: "",105 latestEvent: "Listed",106 latestEventDate: "02/13/2018",107 latestEventPrice: "$140,000",108 latestEventPriceSqft: "$93",109 latestEventSource: "Houston",110 phone: "(281) 220-2100",111 realtor: "Lance Loken",...
string.js
Source:string.js
...21 equal(string.firstToUpperCase("Aabbccdd"), "Aabbccdd", "function firstToUpperCase(Aabbccdd) returns value Aabbccdd");22 equal(string.firstToUpperCase("-aabbccdd"), "-aabbccdd", "function firstToUpperCase(-aabbccdd) returns value -aabbccdd");23 });24 test("parseProperty", function () {25 equal(typeof string.parseProperty(""), "object", "function parseProperty returns number value");26 deepEqual(string.parseProperty("1,2,3"), [1, 2, 3], "function parseProperty(1,2,3) returns value [1, 2, 3]");27 deepEqual(string.parseProperty("1,2,a"), [1, 2, null], "function parseProperty(1,2,a) returns value [1, 2, null]");28 deepEqual(string.parseProperty("34%,35%"), ["34%", "35%"], "function parseProperty(34%,35%) returns value [34%, 35%]");29 deepEqual(string.parseProperty([2, 3, 4]), [2, 3, 4], "function parseProperty([2, 3, 4]) returns value [2, 3, 4]");30 });31 }32 if (typeof define === "function") {33 define(function () {34 return runTests;35 });36 } else {37 runTests(tau.util.string,38 window.helpers);39 }...
parse-property.js
Source:parse-property.js
1"use strict";2var map = require('./map')3function parseProperty (str) {4 var prop = {5 name: '',6 descriptors: []7 }8 var list = str.split(' ')9 var m, d10 while (list.length) {11 d = list.shift()12 if ( !d ) continue13 m = parseProperty.propertyDescriptor.exec(d)14 if (m) {15 map.set(prop.descriptors, {16 name: m[1],17 value: m[2]18 })19 continue20 }21 m = parseProperty.typeDescriptor.exec(d)22 if (m) {23 map.set(prop.descriptors, {24 name: 'type',25 value: m[1]26 })27 continue28 }29 prop.name = d30 break31 }32 prop.description = list.join(' ')33 return prop34}35parseProperty.propertyDescriptor = /^(.+):(.+)$/36parseProperty.typeDescriptor = /^\{(.+)\}$/...
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!!