Best JavaScript code snippet using playwright-internal
PatientRepo.js
Source:PatientRepo.js
...3const { requestOTP, validateOTP, cancelOTP, sendVerifyEmail } = require("./AuthenticationRepo")4const { patientScheme } = require("../Models/PatientModel")5const moment = require("moment");6const login = async (citizenId, password) => {7 const res = await contract.Login(convertString(citizenId), convertString(password));8 if (res) { return { status: true, message: "SUCCESS" } }9 return { status: false, message: "ERROR : Incorrect citizen Id or password" };10}11const get = citizenId => {12 const byteCitizenId = convertString(citizenId)13 const info1 = contract.getInfoPatientPart1(byteCitizenId, defaultAccount)14 const info2 = contract.getInfoPatientPart2(byteCitizenId, defaultAccount)15 const info3 = contract.getInfoPatientPart3(byteCitizenId, defaultAccount)16 const info4 = contract.getInfoPatientPart4(byteCitizenId, defaultAccount)17 const combindedInfoData = bindData(patientScheme, [info1, info2, info3, info4], 'info')18 const addressPatient = contract.getAddressPatient(byteCitizenId, defaultAccount)19 const combindedAddressData = bindData(patientScheme, [addressPatient], 'address')20 const allergyPatient = contract.getPatientAllergy(byteCitizenId, defaultAccount);21 const combindedAllergyData = bindData(patientScheme, [allergyPatient], 'allery')22 const emer1 = contract.getEmergencyContactPart1(byteCitizenId, defaultAccount);23 const emer2 = contract.getEmergencyContactPart2(byteCitizenId, defaultAccount);24 const combindedEmerData = bindData(patientScheme, [emer1, emer2], 'emerContact')25 const patientParent = contract.getPatientParent(byteCitizenId, defaultAccount);26 const combindedParentData = bindData(patientScheme, [patientParent], 'parent')27 let patient = { ...combindedInfoData, ...combindedAddressData, ...combindedAllergyData, ...combindedEmerData, ...combindedParentData }28 return { status: true, message: "SUCCESS", data: patient }29}30const getBasicData = citizenId => {31 const byteCitizenId = convertString(citizenId)32 const info1 = contract.getInfoPatientPart1(byteCitizenId, defaultAccount)33 const info2 = contract.getInfoPatientPart2(byteCitizenId, defaultAccount)34 const info3 = contract.getInfoPatientPart3(byteCitizenId, defaultAccount)35 const info4 = contract.getInfoPatientPart4(byteCitizenId, defaultAccount)36 const combindedInfoData = bindData(patientScheme, [info1, info2, info3, info4], 'info')37 const allergyPatient = contract.getPatientAllergy(byteCitizenId, defaultAccount);38 const combindedAllergyData = bindData(patientScheme, [allergyPatient], 'allery')39 let patient = { ...combindedInfoData, ...combindedAllergyData }40 return { status: true, message: "SUCCESS", data: patient }41}42const insert = async (patient) => {43 if (unlockAccount()) {44 console.log("insert")45 let arrTx = []46 arrTx.push(await contract.setInfoPatientPart1(convertString(patient.citizenId), convertString(moment().format("L")), convertString(patient.password), defaultAccount))47 // arrTx.push(infoPart1)48 arrTx.push(await contract.setInfoPatientPart2(convertString(patient.citizenId), convertString(patient.dob), convertString(patient.nametitle), convertString(patient.firstname), convertString(patient.lastname), convertString(patient.gender), defaultAccount))49 arrTx.push(await contract.setInfoPatientPart3(convertString(patient.citizenId), convertString(patient.congenitalDisease), convertString(patient.bloodgroup), convertString(patient.religion), convertString(patient.nationality), convertString(patient.country), defaultAccount))50 arrTx.push(await contract.setInfoPatientPart4(51 convertString(patient.citizenId),52 convertString(patient.status),53 convertString(!patient.occupartion ? "-" : patient.occupartion),54 convertString(!patient.homePhonenumber ? "-" : patient.homePhonenumber),55 convertString(patient.mobileNumber),56 convertString(patient.email),57 defaultAccount))58 // contract.setEmail(convertString(patient.email), defaultAccount);59 arrTx.push(await contract.setAddressPatient(convertString(patient.citizenId), convertString(patient.typeofHouse), convertString(patient.address), convertString(patient.province), convertString(patient.district), convertString(patient.subDistrict), convertString(patient.zipcode), defaultAccount))60 arrTx.push(await contract.setPatientAllergy(convertString(patient.citizenId), convertString(patient.allergy), convertString(patient.privilege), defaultAccount))61 // arrTx.push(await contract.setVerifyEmail(convertString(patient.citizenId),false))62 if (patient.emerTitle || patient.emerFirstname || patient.emerLastname) {63 // console.log("มี emer")64 arrTx.push(await contract.setEmergencyContactPart1(65 convertString(patient.citizenId),66 convertString(patient.emerTitle),67 convertString(patient.emerFirstname),68 convertString(patient.emerLastname),69 convertString(patient.emerRelationship),70 convertString(!patient.emerHomePhonenumber ? "-" : patient.emerHomePhonenumber),71 convertString(patient.emerMobileNumber),72 defaultAccount))73 arrTx.push(await contract.setEmergencyContactPart2(74 convertString(patient.citizenId),75 convertString(patient.typeofHouse),76 convertString(patient.address),77 convertString(patient.province),78 convertString(patient.district),79 convertString(patient.subDistrict),80 convertString(patient.zipcode),81 defaultAccount))82 }83 if ((patient.fatherFirstname && patient.fatherLastname) || (patient.motherFirstname && patient.motherLastname)) {84 // console.log("มี à¸à¹à¸à¹à¸¡à¹")85 arrTx.push(await contract.setPatientParent(86 convertString(patient.citizenId),87 convertString(!patient.fatherFirstname ? "-" : patient.fatherFirstname),88 convertString(!patient.fatherLastname ? "-" : patient.fatherLastname),89 convertString(!patient.motherFirstname ? "-" : patient.motherFirstname),90 convertString(!patient.motherLastname ? "-" : patient.motherLastname), defaultAccount))91 }92 // console.log("Success")93 lockAccount()94 // await sendVerifyEmail(patient)95 console.log("arrTx",arrTx)96 97 if (arrTx.length>5){98 // required field 6 transaction99 return { status: true, message: "SUCCESS", data: { transaction : arrTx } };100 }101 } else {102 return { status: false, message: "ERROR"};103 }104}105const isPatient = citizenId => {106 console.log(citizenId)107 const byteCitizenId = convertString(citizenId)108 console.log(byteCitizenId)109 return contract.haveCitizenId(byteCitizenId);110}111const isEmail = (email) => {112 console.log("email", email)113 const byteEmail = convertString(email)114 return contract.haveEmail(byteEmail)115}116const edit = async (data) => {117 console.log("edit", data)118 let arrTx = [];119 if (unlockAccount()) {120 if (data.editInfoPart1) {121 arrTx.push(await contract.setInfoPatientPart1(convertString(data.citizenId), convertString(moment().format("L")), convertString(data.password), defaultAccount))122 }123 if (data.editInfoPart2) {124 arrTx.push(await contract.setInfoPatientPart2(convertString(data.citizenId), convertString(data.dob), convertString(data.nametitle), convertString(data.firstname), convertString(data.lastname), convertString(data.gender), defaultAccount))125 }126 if (data.editInfoPart3) {127 arrTx.push(await contract.setInfoPatientPart3(convertString(data.citizenId), convertString(data.congenitalDisease), convertString(data.bloodgroup), convertString(data.religion), convertString(data.nationality), convertString(data.country), defaultAccount))128 }129 if (data.editInfoPart4) {130 arrTx.push(await contract.setInfoPatientPart4(131 convertString(data.citizenId),132 convertString(data.status),133 convertString(!data.occupartion ? "-" : data.occupartion),134 convertString(!data.homePhonenumber ? "-" : data.homePhonenumber),135 convertString(data.mobileNumber),136 convertString(data.email),137 defaultAccount))138 }139 if (data.editEmail) {140 console.log("EDIT EMAIL!!")141 arrTx.push(await contract.setEmail(convertString(data.email),convertString(data.newEmail), defaultAccount))142 arrTx.push(await contract.setInfoPatientPart4(143 convertString(data.citizenId),144 convertString(data.status),145 convertString(!data.occupartion ? "-" : data.occupartion),146 convertString(!data.homePhonenumber ? "-" : data.homePhonenumber),147 convertString(data.mobileNumber),148 convertString(data.newEmail),149 defaultAccount))150 }151 if (data.editAddress) {152 arrTx.push(await contract.setAddressPatient(convertString(data.citizenId), convertString(data.typeofHouse), data.address, convertString(data.province), convertString(data.district), convertString(data.subDistrict), convertString(data.zipcode), defaultAccount))153 }154 if (data.editAllergy) {155 arrTx.push(await contract.setPatientAllergy(convertString(data.citizenId), convertString(data.allergy), convertString(data.privilege), defaultAccount))156 }157 if (data.editEmerContact1) {158 arrTx.push(await contract.setEmergencyContactPart1(159 convertString(data.citizenId),160 convertString(data.emerTitle),161 convertString(data.emerFirstname),162 convertString(data.emerLastname),163 convertString(data.emerRelationship),164 convertString(!data.emerHomePhonenumber ? "-" : data.emerHomePhonenumber),165 convertString(data.emerMobileNumber),166 defaultAccount))167 }168 if (data.editEmerContact2) {169 arrTx.push(await contract.setEmergencyContactPart2(170 convertString(data.citizenId),171 convertString(data.typeofHouse),172 convertString(data.address),173 convertString(data.province),174 convertString(data.district),175 convertString(data.subDistrict),176 convertString(data.zipcode),177 defaultAccount))178 }179 if (data.editParent) {180 arrTx.push(await contract.setPatientParent(181 convertString(data.citizenId),182 convertString(!data.fatherFirstname ? "-" : data.fatherFirstname),183 convertString(!data.fatherLastname ? "-" : data.fatherLastname),184 convertString(!data.motherFirstname ? "-" : data.motherFirstname),185 convertString(!data.motherLastname ? "-" : data.motherLastname), defaultAccount))186 }187 lockAccount()188 if (arrTx.length > 0) {189 // required field 6 transaction190 return { status: true, message: "SUCCESS", data: { transaction: arrTx } };191 }192 // let check = false193 // while (check === false) {194 // check = await isPatient(data.citizenId);195 // if (check) {196 // return { status: true, message: "SUCCESS" };197 // }198 // }199 } else {200 return { status: false, message: "ERROR" };201 }202}203const checkPassword = (citizenId, password) => {204 console.log("checkPassword",citizenId, password)205 const byteCitizenId = convertString(citizenId)206 const bytePassword = convertString(password)207 return contract.checkPassword(byteCitizenId, bytePassword)208}209const verifiedByCitizenId = async (citizenId) => {210 const byteCitizenId = convertString(citizenId)211 const byteMobileNumber = contract.getMobileNumber(byteCitizenId)212 let stringMobileNumber = convertToAscii(byteMobileNumber);213 return requestOTPwithMobile(stringMobileNumber)214 // let mobileNumber = "66" + stringMobileNumber.substring(1)215 // console.log(mobileNumber)216 // let hideNumber = stringMobileNumber.substring(0, 3) + "-xxx-xx" + stringMobileNumber.substring(stringMobileNumber.length - 2)217 // try {218 // const res = await requestOTP(mobileNumber)219 // console.log("verifiedByCitizenId", res)220 // return ({ status: true, message: "SUCCESS", data: { requestId: res.requestId, mobileNumber: hideNumber } });221 // } catch (err) {222 // return ({ status: false, statusCode: err.message.status, message: err.message.error_text, data: { requestId: err.requestId } });223 // }224}225const getPatientWithOTP = async (data) => {226 //validate227 console.log("getPatientWithOTP", data)228 try {229 await validateOTP(data.requestId, data.pin)230 const byteCitizenId = convertString(data.citizenId)231 const info1 = contract.getInfoPatientPart1(byteCitizenId, defaultAccount)232 const info2 = contract.getInfoPatientPart2(byteCitizenId, defaultAccount)233 const info3 = contract.getInfoPatientPart3(byteCitizenId, defaultAccount)234 const info4 = contract.getInfoPatientPart4(byteCitizenId, defaultAccount)235 const combindedInfoData = bindData(patientScheme, [info1, info2, info3, info4], 'info')236 const addressPatient = contract.getAddressPatient(byteCitizenId, defaultAccount)237 const combindedAddressData = bindData(patientScheme, [addressPatient], 'address')238 const allergyPatient = contract.getPatientAllergy(byteCitizenId, defaultAccount);239 const combindedAllergyData = bindData(patientScheme, [allergyPatient], 'allery')240 const emer1 = contract.getEmergencyContactPart1(byteCitizenId, defaultAccount);241 const emer2 = contract.getEmergencyContactPart2(byteCitizenId, defaultAccount);242 const combindedEmerData = bindData(patientScheme, [emer1, emer2], 'emerContact')243 const patientParent = contract.getPatientParent(byteCitizenId, defaultAccount);244 const combindedParentData = bindData(patientScheme, [patientParent], 'parent')245 let patient = { ...combindedInfoData, ...combindedAddressData, ...combindedAllergyData, ...combindedEmerData, ...combindedParentData }246 return ({ status: true, message: "SUCCESS", data: patient })247 } catch (err) {248 return ({ status: false, statusCode: err.message.status, message: err.message.error_text, data: { requestId: err.requestId } });249 }250}251const cancelRequestOTP = async (requestId) => {252 try {253 const res = await cancelOTP(requestId)254 return ({ status: true, message: "SUCCESS" });255 } catch (err) {256 return ({ status: false, statusCode: err.message.status, message: err.message.error_text });257 }258}259const forgotPasswordVerify = async (citizenId, dob) => {260 const byteCitizenId = convertString(citizenId)261 const byteDob = convertString(dob)262 console.log("forgotPasswordVerify",citizenId, dob) 263 return contract.forgotPasswordVerify(byteCitizenId, byteDob);264}265const confirmChangePassword = async (citizenId, newPassword, oldPassword=null ) => {266 console.log("confirmChangePassword")267 const byteCitizenId = convertString(citizenId)268 const bytePassword = convertString(newPassword)269 let arrTx = []270 if(oldPassword){271 console.log("oldPassword // à¹à¸à¸¥à¸µà¹à¸¢à¸à¸£à¸«à¸±à¸ªà¸à¹à¸²à¸")272 if (checkPassword(citizenId, oldPassword)) {273 // à¸à¸£à¸à¸µà¸£à¸¹à¹à¸£à¸«à¸±à¸ªà¹à¸à¹à¸² >> à¹à¸à¸¥à¸µà¹à¸¢à¸ pass274 if (!checkPassword(citizenId, newPassword)) {275 // à¹à¸à¸à¸§à¹à¸² รหัสà¹à¸«à¸¡à¹ à¸à¸£à¸à¸à¸±à¸à¹à¸à¸£à¸°à¸à¸à¹à¸«à¸¡ >> à¸à¹à¸²à¹à¸¡à¹à¸à¸£à¸à¸à¸¶à¸à¹à¸à¸¥à¸µà¹à¸¢à¸à¸£à¸«à¸±à¸ªà¹à¸à¹276 if (unlockAccount()) {277 arrTx.push(await contract.setPassword(byteCitizenId, bytePassword))278 lockAccount()279 }280 if(arrTx.length>0){281 return { status: true, message: "SUCCESS", data: { transaction: arrTx } };282 }283 // let check = false284 // while (check === false) {285 // check = await checkPassword(citizenId, newPassword);286 // if (check) {287 // return { status: true, message: "SUCCESS" };288 // }289 // }290 } else {291 return { status: false, message: "Password must differ from old password!" };292 }293 }294 return { status: false, message: "Your password was incorrect. Please re-enter your password" };295 }else{296 // à¸à¸£à¸à¸µà¸¥à¸·à¸¡à¸£à¸«à¸±à¸ªà¸à¹à¸²à¸297 if (!checkPassword(citizenId, newPassword)) {298 // à¹à¸à¸à¸§à¹à¸² รหัสà¹à¸«à¸¡à¹ à¸à¸£à¸à¸à¸±à¸à¹à¸à¸£à¸°à¸à¸à¹à¸«à¸¡ >> à¸à¹à¸²à¹à¸¡à¹à¸à¸£à¸à¸à¸¶à¸à¹à¸à¸¥à¸µà¹à¸¢à¸à¸£à¸«à¸±à¸ªà¹à¸à¹299 if (unlockAccount()) {300 arrTx.push(await contract.setPassword(byteCitizenId, bytePassword))301 lockAccount()302 }303 if (arrTx.length > 0) {304 return { status: true, message: "SUCCESS", data: { transaction: arrTx } };305 }306 // let check = false307 // while (check === false) {308 // check = await checkPassword(citizenId, newPassword);309 // if (check) {310 // return { status: true, message: "SUCCESS" };311 // }312 // }313 } else {314 return { status: false, message: "Password must differ from old password!" };315 }316 }317}318requestOTPwithMobile = async (mobileNumber) => {319 // let mobileNumberConvert = "66" + mobileNumber.substring(1)320 let mobileNumberConvert = mobileNumber321 let hideNumber = mobileNumber.substring(0, 5) + "-xxx-xx" + mobileNumber.substring(mobileNumber.length - 2)322 try {323 const res = await requestOTP(mobileNumberConvert)324 return ({ status: true, message: "SUCCESS", data: { requestId: res.requestId, mobileNumber: hideNumber } });325 } catch (err) {326 if (err.message.status == '3'){327 err.message.error_text = "Invalid phone number"328 }329 if (err.message.status == '10'){330 let result = await cancelRequestOTP(err.requestId)331 if(result.status){332 try {333 const res = await requestOTP(mobileNumberConvert)334 return ({ status: true, message: "SUCCESS", data: { requestId: res.requestId, mobileNumber: hideNumber } });335 } catch (err) {336 return ({ status: false, statusCode: err.message.status, message: err.message.error_text, data: { requestId: err.requestId } });337 }338 }else{339 return result340 }341 }342 return ({ status: false, statusCode: err.message.status, message: err.message.error_text, data: { requestId: err.requestId } });343 }344}345validateOTPvalue = async (requestId, pin) => {346 try{347 const res = await validateOTP(requestId, pin)348 return { status: true, message: "SUCCESS" };349 }catch(err){350 return ({ status: false, statusCode: err.message.status, message: err.message.error_text, data: { requestId: err.requestId } });351 }352}353getEmailUser = async(citizenId) => {354 const byteCitizenId = convertString(citizenId)355 let nameAndEmail = await contract.getPatientNameAndEmail(byteCitizenId)356 const combindedData = bindData(patientScheme, [nameAndEmail], 'patientAndEmail')357 return combindedData358}359module.exports = {360 isPatient,361 login,362 isEmail,363 get,364 insert,365 getBasicData,366 edit,367 checkPassword,368 // requestOTP,...
convert.js
Source:convert.js
1var convertChildren = function(children, param, namespace, myBatisMapper) {2 if (!param) {3 param = {};4 }5 if (!isDict(param)){6 throw new Error("Parameter argument should be Key-Value type or Null.");7 }8 9 if (children.type == 'text') {10 // Convert Parameters11 return convertParameters(children, param);12 } else if (children.type == 'tag') {13 switch (children.name.toLowerCase()) {14 case 'if':15 return convertIf(children, param, namespace, myBatisMapper);16 case 'choose':17 return convertChoose(children, param, namespace, myBatisMapper);18 case 'trim':19 case 'where':20 return convertTrimWhere(children, param, namespace, myBatisMapper);21 case 'set':22 return convertSet(children, param, namespace, myBatisMapper);23 case 'foreach':24 return convertForeach(children, param, namespace, myBatisMapper);25 case 'bind':26 param = convertBind(children, param);27 return '';28 case 'include':29 return convertInclude(children, param, namespace, myBatisMapper);30 default:31 throw new Error("XML is not well-formed character or markup. Consider using CDATA section.");32 }33 } else {34 return '';35 }36}37var convertParameters = function(children, param) {38 var convertString = children.content;39 try{40 convertString = convertParametersInner('#', convertString, param);41 convertString = convertParametersInner('$', convertString, param);42 } catch (err) {43 throw new Error("æ¿æ¢åæ°åºé!");44 }45 46 try{47 // convert CDATA string48 convertString = convertString.replace(/(\&\;)/g,'&');49 convertString = convertString.replace(/(\<\;)/g,'<');50 convertString = convertString.replace(/(\>\;)/g,'>');51 convertString = convertString.replace(/(\"\;)/g,'"');52 } catch (err) {53 throw new Error("解æCDATAé¨ååºé!");54 }55 56 return convertString;57}58var isObject = function (variable) {59 return typeof variable === 'object' && variable !== null;60}61var isArray = function (variable) {62 return isObject(variable) && variable.hasOwnProperty('length');63}64var convertParametersInner = function(change, convertString, param) {65 var stringReg = new RegExp('(\\' + change + '\\{[a-zA-Z0-9._\\$]+\\})', 'g');66 var stringTarget = convertString.match(stringReg);67 if (stringTarget && stringTarget.length){68 stringTarget = uniqueArray(stringTarget);69 var target = null;70 for (var i=0; i<stringTarget.length; i++) {71 target = stringTarget[i];72 var t = target.replace(change + '{', '').replace('}','');73 var tempParamKey = eval('param.' + t);74 75 if (tempParamKey !== undefined){76 var reg = new RegExp('\\' + change + '{' + t + '}', 'g');77 if (tempParamKey === null) {78 tempParamKey = 'NULL';79 convertString = convertString.replace(reg, tempParamKey);80 } else {81 if (change == '#') {82 // processing JSON fields structures83 if (isObject(tempParamKey) || isArray(tempParamKey)) {84 tempParamKey = JSON.stringify(tempParamKey);85 } else {86 tempParamKey = tempParamKey.toString().replace(/"/g, '\\\"');87 }88 tempParamKey = tempParamKey.replace(/'/g, '\\\'');89 convertString = convertString.replace(reg, "'" + tempParamKey + "'");90 } else if (change == '$') {91 convertString = convertString.replace(reg, tempParamKey);92 }93 }94 }95 }96 }97 return convertString;98}99var convertIf = function(children, param, namespace, myBatisMapper) {100 try{101 var evalString = children.attrs.test;102 103 // Create Evaluate string104 evalString = replaceEvalString(evalString, param);105 106 evalString = evalString.replace(/ and /gi, ' && ');107 evalString = evalString.replace(/ or /gi, ' || ');108 109 // replace == to === for strict evaluate110 evalString = evalString.replace(/==/g, "===");111 evalString = evalString.replace(/!=/g, "!==");112 113 } catch (err) {114 throw new Error("Error occurred during convert <if> element.");115 }116 117 // Execute Evaluate string118 try {119 if (eval(evalString)) {120 var convertString = '';121 for (var i=0, nextChildren; nextChildren=children['children'][i]; i++){122 convertString += convertChildren(nextChildren, param, namespace, myBatisMapper);123 }124 return convertString;125 } else {126 return '';127 }128 } catch (e) {129 return '';130 }131}132var convertForeach = function (children, param, namespace, myBatisMapper) {133 try{134 console.log(children);135 var collection = eval('param.' + children.attrs.collection);136 var item = children.attrs.item;137 var open = (children.attrs.open == null)? '' : children.attrs.open;138 var close = (children.attrs.close == null)? '' : children.attrs.close;139 var separator = (children.attrs.separator == null)? '' : children.attrs.separator;140 var foreachTexts = [];141 var coll = null;142 for (var j=0; j<collection.length; j++){143 coll = collection[j];144 var foreachParam = param;145 foreachParam[item] = coll;146 147 var foreachText = '';148 for (var k=0, nextChildren; nextChildren=children.children[k]; k++){149 var fText = convertChildren(nextChildren, foreachParam, namespace, myBatisMapper);150 fText = fText.replace(/^\s*$/g, '');151 152 if (fText != null && fText.length){153 foreachText += fText;154 }155 }156 if (foreachText != null && foreachText.length){157 foreachTexts.push(foreachText);158 }159 }160 161 return (open + foreachTexts.join(separator) + close);162 } catch (err) {163 throw new Error("Error occurred during convert <foreach> element.");164 }165}166var convertChoose = function (children, param, namespace, myBatisMapper) {167 try{168 for (var i=0, whenChildren; whenChildren=children.children[i];i++){169 if (whenChildren.type == 'tag' && whenChildren.name.toLowerCase() == 'when'){170 var evalString = whenChildren.attrs.test;171 172 // Create Evaluate string173 evalString = replaceEvalString(evalString, param);174 175 evalString = evalString.replace(/ and /gi, ' && ');176 evalString = evalString.replace(/ or /gi, ' || ');177 // Execute Evaluate string178 try {179 if (eval(evalString)) {180 // If <when> condition is true, do it.181 var convertString = '';182 for (var k=0, nextChildren; nextChildren=whenChildren.children[k]; k++){183 convertString += convertChildren(nextChildren, param, namespace, myBatisMapper);184 }185 return convertString;186 } else {187 continue;188 }189 } catch (e) {190 continue;191 }192 } else if (whenChildren.type == 'tag' && whenChildren.name.toLowerCase() == 'otherwise') {193 // If reached <otherwise> tag, do it.194 var convertString = '';195 for (var k=0, nextChildren; nextChildren=whenChildren.children[k]; k++){196 convertString += convertChildren(nextChildren, param, namespace, myBatisMapper);197 }198 return convertString;199 }200 }201 202 // If there is no suitable when and otherwise, just return null.203 return '';204 205 } catch (err) {206 throw new Error("Error occurred during convert <choose> element.");207 }208}209var convertTrimWhere = function(children, param, namespace, myBatisMapper) { 210 console.log('è¿å
¥!!!!!!!!!!!!!');211 var convertString = '';212 var prefix = null;213 var prefixOverrides = null;214 var suffix = null;215 var suffixOverrides = null;216 var globalSet = null;217 218 try{219 switch (children.name.toLowerCase()) {220 case 'trim':221 prefix = children.attrs.prefix;222 suffix = children.attrs.suffix;223 prefixOverrides = children.attrs.prefixOverrides;224 suffixOverrides = children.attrs.suffixOverrides;225 globalSet = 'g';226 break;227 case 'where': 228 prefix = 'WHERE';229 prefixOverrides = 'and|or';230 globalSet = 'gi';231 break;232 default:233 throw new Error("Error occurred during convert <trim/where> element.");234 }235 236 // Convert children first.237 for (var j=0, nextChildren; nextChildren=children.children[j]; j++){238 convertString += convertChildren(nextChildren, param, namespace, myBatisMapper);239 }240 241 // Remove prefixOverrides242 var trimRegex = new RegExp('(^)([\\s]*?)(' + prefixOverrides + ')', globalSet);243 convertString = convertString.replace(trimRegex, '');244 // Remove suffixOverrides245 var trimRegex = new RegExp('(' + suffixOverrides + ')([\\s]*?)($)', globalSet);246 convertString = convertString.replace(trimRegex, '');247 248 if (children.name.toLowerCase() != 'trim'){249 var trimRegex = new RegExp('(' + prefixOverrides + ')([\\s]*?)($)', globalSet);250 convertString = convertString.replace(trimRegex, '');251 } 252 253 // Add Prefix if String is not empty.254 if (convertString.length) {255 convertString = prefix + ' '+ convertString + ' '+ suffix;256 }257 258 // Remove comma(,) before WHERE259 if (children.name.toLowerCase() != 'where'){260 var regex = new RegExp('(,)([\\s]*?)(where)', 'gi');261 convertString = convertString.replace(regex, ' WHERE ');262 }263 console.log('å½åç¶æ',convertString);264 return convertString;265 } catch (err) {266 throw new Error("Error occurred during convert <" + children.name.toLowerCase() + "> element.");267 }268}269var convertSet = function(children, param, namespace, myBatisMapper) {270 var convertString = '';271 272 try{273 // Convert children first.274 for (var j=0, nextChildren; nextChildren=children.children[j]; j++){275 convertString += convertChildren(nextChildren, param, namespace, myBatisMapper);276 }277 278 // Remove comma repeated more than 2.279 var regex = new RegExp('(,)(,|\\s){2,}', 'g');280 convertString = convertString.replace(regex, ',\n');281 282 // Remove first comma if exists.283 var regex = new RegExp('(^)([\\s]*?)(,)', 'g');284 convertString = convertString.replace(regex, '');285 286 // Remove last comma if exists.287 regex = new RegExp('(,)([\\s]*?)($)', 'g');288 convertString = convertString.replace(regex, '');289 290 convertString = ' SET ' + convertString;291 return convertString;292 } catch (err) {293 throw new Error("Error occurred during convert <set> element.");294 }295}296var convertBind = function(children, param) {297 var evalString = children.attrs.value;298 299 // Create Evaluate string300 evalString = replaceEvalString(evalString, param);301 302 param[children.attrs.name] = eval(evalString);303 return param;304}305var convertInclude = function(children, param, namespace, myBatisMapper) { 306 try{307 // Add Properties to param308 for (var j=0, nextChildren; nextChildren=children.children[j]; j++){309 if (nextChildren.type == 'tag' && nextChildren.name == 'property'){310 param[nextChildren.attrs['name']] = nextChildren.attrs['value'];311 }312 }313 } catch (err) {314 throw new Error("Error occurred during read <property> element in <include> element.");315 }316 317 try{ 318 var refid = convertParametersInner('#', children['attrs']['refid'], param); 319 refid = convertParametersInner('$', refid, param);320 321 var statement = '';322 for (var i=0, children; children = myBatisMapper[namespace][refid][i]; i++) { 323 statement += convertChildren(children, param, namespace, myBatisMapper);324 } 325 } catch (err) {326 throw new Error("Error occurred during convert 'refid' attribute in <include> element.");327 }328 329 return statement;330}331var isDict = function(v) {332 return typeof v==='object' && v!==null && !(v instanceof Array) && !(v instanceof Date);333}334var replaceEvalString = function(evalString, param) {335 var keys = Object.keys(param);336 for (var i=0; i<keys.length; i++){337 var replacePrefix = '';338 var replacePostfix = '';339 var paramRegex = null;340 341 if (isDict(param[keys[i]])) {342 replacePrefix = ' param.';343 replacePostfix = '';344 345 paramRegex = new RegExp('(^|[^a-zA-Z0-9])(' + keys[i] + '\\.)([a-zA-Z0-9]+)', 'g');346 } else { 347 replacePrefix = ' param.';348 replacePostfix = ' ';349 350 paramRegex = new RegExp('(^|[^a-zA-Z0-9])(' + keys[i] + ')($|[^a-zA-Z0-9])', 'g');351 }352 353 evalString = evalString.replace(paramRegex, ("$1" + replacePrefix + "$2" + replacePostfix + "$3"));354 }355 356 return evalString;357}358var uniqueArray = function(a){359 var seen = {};360 var out = [];361 var len = a.length;362 var j = 0;363 for(var i=0; i<len; i++) {364 var item = a[i];365 if(seen[item] !== 1) {366 seen[item] = 1;367 out[j++] = item;368 }369 }370 return out;371}372module.exports = {373 convertChildren,374 convertParameters,375 convertIf,376 convertTrimWhere,377 convertSet,378 convertForeach,379 convertChoose,380 convertBind...
MedicalRecordRepo.js
Source:MedicalRecordRepo.js
...13}14const setMedicalRecordForNurse = async (medicalRecord) => {15 // let medicalRecordId = (+contract.getLengthMedicalRecords() + 1) + "";16 let arrTx = []17 let key = convertString(medicalRecord.patientCitizenId + "" + medicalRecord.date + "" + medicalRecord.time)18 if (unlockAccount()) {19 arrTx.push(await contract.setMedicalRecordForNursePart1(20 convertString(medicalRecord.patientCitizenId),21 key,22 convertString(medicalRecord.clinic),23 convertString(medicalRecord.height),24 convertString(medicalRecord.bodyWeight),25 convertString(medicalRecord.bmi),26 convertString(medicalRecord.temperature),27 convertString(medicalRecord.date),28 convertString(medicalRecord.time),29 medicalRecord.treatmentYear,30 defaultAccount31 ))32 let medicalRecordId = await contract.getMedicalRecordId(key).toString()33 arrTx.push(await contract.setMedicalRecordForNursePart2(34 medicalRecordId,35 convertString(medicalRecord.pulseRate),36 convertString(medicalRecord.respiratoryRate),37 convertString(notRequiredField(medicalRecord.BP1)),38 convertString(notRequiredField(medicalRecord.BP2)),39 convertString(notRequiredField(medicalRecord.BP3)),40 convertString(notRequiredField(medicalRecord.chiefComplaint)),41 convertString(notRequiredField(medicalRecord.nurseName)),42 defaultAccount43 ))44 lockAccount()45 if (arrTx.length > 1) {46 return { status: true, message: "SUCCESS", data: { medicalRecordId: medicalRecordId, transaction: arrTx } };47 }48 } else {49 return { status: false, message: "ERROR" };50 }51}52const setMedicalRecordForDoctor = async medicalRecord => {53 let arrTx = [];54 if (unlockAccount()) {55 arrTx.push(await contract.setMedicalRecordForDoctor(56 medicalRecord.medicalRecordId,57 convertString(medicalRecord.presentIllness),58 convertString(medicalRecord.physicalExem),59 convertString(medicalRecord.diagnosis),60 convertString(medicalRecord.treatment),61 convertString(medicalRecord.recommendation),62 convertString(notRequiredField(medicalRecord.appointment)),63 convertString(medicalRecord.doctorName),64 defaultAccount65 ))66 arrTx.push(await contract.addHistoryMedicalRecord(67 convertString(medicalRecord.patientCitizenId),68 medicalRecord.medicalRecordId,69 defaultAccount70 ))71 // send Email72 let patientNameAndEmail = contract.getPatientNameAndEmail(convertString(medicalRecord.patientCitizenId))73 const combindedData = bindData(patientScheme, [patientNameAndEmail], 'patientAndEmail')74 getMedicalRecordForNurse(medicalRecord.medicalRecordId).then(async (res) => {75 let tmp = { ...res.data, ...medicalRecord, ...combindedData }76 await sendEmail(tmp)77 })78 lockAccount()79 if (arrTx.length > 1) {80 return { status: true, message: "SUCCESS", data: { transaction: arrTx } };81 }82 } else {83 return { status: false, message: "ERROR" };84 }85};86const getMedicalRecordForNurse = async (medicalRecordId) => {87 // const byteMedicalRecordId = convertString(medicalRecordId)88 const nurse1 = await contract.getMedicalRecordForNursePart1(medicalRecordId);89 const nurse2 = await contract.getMedicalRecordForNursePart2(medicalRecordId);90 const mdrInfo = await contract.getMedicalRecordInfo(medicalRecordId);91 const combindedNurseData = bindData(medicalRecordScheme, [nurse1, nurse2], 'nurse')92 const combindedInfoData = bindData(medicalRecordScheme, [mdrInfo], 'info')93 let medicalRecord = { ...combindedNurseData, ...combindedInfoData }94 medicalRecord.medicalRecordId = medicalRecordId;95 return { status: true, message: "SUCCESS", data: medicalRecord };96};97const getMedicalRecordForDoctor = async (medicalRecordId) => {98 const doctor = await contract.getMedicalRecordForDoctor(medicalRecordId);99 const mdrInfo = await contract.getMedicalRecordInfo(medicalRecordId);100 const combindedDortorData = bindData(medicalRecordScheme, [doctor], 'doctor')101 const combindedInfoData = bindData(medicalRecordScheme, [mdrInfo], 'info')102 let medicalRecord = { ...combindedDortorData, ...combindedInfoData }103 medicalRecord.medicalRecordId = medicalRecordId;104 return { status: true, message: "SUCCESS", data: medicalRecord };105};106const getMedicalRecordForPharmacy = async (medicalRecordId) => {107 const nurse = await contract.getMedicalRecordForNursePart1(medicalRecordId);108 const pharmacy = await contract.getMedicalRecordForPharmacy(medicalRecordId);109 const combindedPharmacyData = bindData(medicalRecordScheme, [nurse, pharmacy], 'pharmacy')110 let medicalRecord = combindedPharmacyData111 return { status: true, message: "SUCCESS", data: medicalRecord };112};113const getMedicalRecord = async medicalRecordId => {114 let nurse = await getMedicalRecordForNurse(medicalRecordId);115 let doctor = await getMedicalRecordForDoctor(medicalRecordId);116 return { status: true, message: "SUCCESS", data: { ...nurse.data, ...doctor.data } };117}118const getHistoryMedicalRecord = async (citizenId, length, year = null) => {119 const byteCitizenId = convertString(citizenId)120 let medicalRecord = []121 // Sort by last122 for (let i = length - 1; i >= 0; i--) {123 if (year) {124 let statusSort = await contract.checkTreatmentYear(byteCitizenId, i, year)125 if (statusSort) {126 // ภi à¸à¸±à¹à¸à¸¡à¸µ treatmentYear = year >> get à¸à¸à¸à¸¡à¸²127 let historyData = await getHistoryData(byteCitizenId, i)128 medicalRecord.push(historyData)129 }130 } else {131 // à¹à¸¡à¹à¹à¸à¹à¹à¸¥à¸·à¸à¸à¸à¸µà¹à¸«à¹ sort132 let historyData = await getHistoryData(byteCitizenId, i)133 medicalRecord.push(historyData)134 }135 }136 if (medicalRecord.length === 0) {137 return msg.getMsgSuccess(msg.msgVariable.nothaveHistoryMDR)138 }139 return { status: true, message: "SUCCESS", data: medicalRecord };140}141const getHistoryData = async (byteCitizenId, index) => {142 let medicalRecordId = await contract.getHistoryMedicalRecordPatient(byteCitizenId, index);143 // let stringMedicalRecordId = convertToAscii(byteMedicalRecordId)144 const data = await contract.getMedicalRecordForShowHistory(medicalRecordId.toString())145 const combindedHistoryData = bindData(medicalRecordScheme, [data], 'history')146 combindedHistoryData.medicalRecordId = medicalRecordId.toString();147 return combindedHistoryData148}149const isMedicalRecord = medicalRecordId => {150 // const byteMedicalRecordId = convertString(medicalRecordId)151 return contract.haveMedicalRecords(medicalRecordId)152}153const alreadyMedicalRecord = medicalRecordId => {154 // const byteMedicalRecordId = convertString(medicalRecordId)155 return contract.alreadyDataInMedicalRecordsId(medicalRecordId)156}157const haveMedicalRecordsOfPatient = (patientCitizenId, medicalRecordId) => {158 // const byteMedicalRecordId = convertString(medicalRecordId)159 const bytePatientCitizenId = convertString(patientCitizenId)160 return contract.haveMedicalRecordsOfPatient(bytePatientCitizenId, medicalRecordId)161}162const haveMDRinPatientHistory = (patientCitizenId, medicalRecordId) => {163 // const byteMedicalRecordId = convertString(medicalRecordId)164 const bytePatientCitizenId = convertString(patientCitizenId)165 return contract.haveHistoryOfPatient(bytePatientCitizenId, medicalRecordId);166}167const lengthPatientHistory = (patientCitizenId) => {168 const bytePatientCitizenId = convertString(patientCitizenId)169 return +contract.countHistoryMedicalRecordForPatient(bytePatientCitizenId).toString();170}171const insertMedicalRecord = async (medicalRecord) => {172 let arrTx = []173 let key = convertString(medicalRecord.patientCitizenId + "" + medicalRecord.date + "" + medicalRecord.time)174 if (unlockAccount()) {175 // nurse176 arrTx.push(await contract.setMedicalRecordForNursePart1(177 convertString(medicalRecord.patientCitizenId),178 key,179 convertString(medicalRecord.clinic),180 convertString(medicalRecord.height),181 convertString(medicalRecord.bodyWeight),182 convertString(medicalRecord.bmi),183 convertString(medicalRecord.temperature),184 convertString(medicalRecord.date),185 convertString(medicalRecord.time),186 medicalRecord.treatmentYear,187 defaultAccount188 ))189 let medicalRecordId = await contract.getMedicalRecordId(key).toString()190 arrTx.push(await contract.setMedicalRecordForNursePart2(191 medicalRecordId,192 convertString(medicalRecord.pulseRate),193 convertString(medicalRecord.respiratoryRate),194 convertString(notRequiredField(medicalRecord.BP1)),195 convertString(notRequiredField(medicalRecord.BP2)),196 convertString(notRequiredField(medicalRecord.BP3)),197 convertString(notRequiredField(medicalRecord.chiefComplaint)),198 convertString(notRequiredField(medicalRecord.nurseName)),199 defaultAccount200 ))201 //doctor202 arrTx.push(await contract.setMedicalRecordForDoctor(203 medicalRecordId,204 convertString(medicalRecord.presentIllness),205 convertString(medicalRecord.physicalExem),206 convertString(medicalRecord.diagnosis),207 convertString(medicalRecord.treatment),208 convertString(medicalRecord.recommendation),209 convertString(notRequiredField(medicalRecord.appointment)),210 convertString(medicalRecord.doctorName),211 defaultAccount212 ))213 //save History214 arrTx.push(await contract.addHistoryMedicalRecord(215 convertString(medicalRecord.patientCitizenId),216 medicalRecordId,217 defaultAccount218 ))219 lockAccount()220 if (arrTx.length == 4) {221 //send email222 let patientNameAndEmail = contract.getPatientNameAndEmail(convertString(medicalRecord.patientCitizenId))223 const combindedData = bindData(patientScheme, [patientNameAndEmail], 'patientAndEmail')224 await sendEmail(combindedData)225 226 return { status: true, message: "SUCCESS", data: { medicalRecordId: medicalRecordId, transaction: arrTx } };227 }else{228 return { status: false, message: "ERROR" };229 }230 } else {231 return { status: false, message: "ERROR" };232 }233}234module.exports = {235 setMedicalRecordForNurse,236 setMedicalRecordForDoctor,...
test.js
Source:test.js
...59});60describe('convertString', function() {61 const { convertString } = converter;62 it('should convert nothing to undefined', function() {63 const result = convertString();64 expect(result).to.equal(undefined);65 });66 it('should convert undefined to undefined', function() {67 const result = convertString(undefined);68 expect(result).to.equal(undefined);69 });70 it('should not convert \'\'', function() {71 const result = convertString('');72 expect(result).to.equal('');73 });74 it('should not convert ð', function() {75 const result = convertString('ð');76 expect(result).to.equal('ð');77 });78 it('should not convert ð¦ðð¿', function() {79 const result = convertString('ð¦ðð¿');80 expect(result).to.equal('ð¦ðð¿');81 });82 it('should convert î³ to å¿', function() {83 const result = convertString('î³');84 expect(result).to.equal('å¿');85 });86 it('should convert î£ to ç', function() {87 const result = convertString('î£');88 expect(result).to.equal('ç');89 });90 it('should convert î° to 港', function() {91 const result = convertString('î°');92 expect(result).to.equal('港');93 });94 95 it('should convert U+F325 to \'ÃÌ\' (<00CA,0304>)', function() {96 const result = convertString(String.fromCodePoint(0xf325));97 expect(result).to.equal('ÃÌ');98 });99 it('should convert U+2A3ED to ã´', function() {100 const result = convertString(String.fromCodePoint(0x2A3ED));101 expect(result).to.equal('ã´');102 });103 it('should convert ï,î³ to ð¥«,ð¨¢', function() {104 const result = convertString('ï,î³')105 expect(result).to.equal('ð¥«,ð¨¢');106 });107 it('should not convert ABC', function() {108 const result = convertString('ABC')109 expect(result).to.equal('ABC');110 });111 it('should not convert æ', function() {112 const result = convertString('æ');113 expect(result).to.equal('æ');114 });115 it('should not convert æå', function() {116 const result = convertString('æå');117 expect(result).to.equal('æå');118 });119 it('should convert å£î³ to å£ð¨¢', function() {120 const result = convertString('å£î³');121 expect(result).to.equal('å£ð¨¢');122 });...
app.js
Source:app.js
1// string conversion function2function convertString(text) {3 const mainText = document.getElementById(text).innerText;4 const convertedText = parseFloat(mainText);5 return convertedText;6};7// total price calculation8function totalPrice(bestprice, memory, storage, delivery) {9 const finalPrice = bestprice + memory + storage + delivery;10 document.getElementById('total-price').innerText = finalPrice;11 document.getElementById('final-total').innerText = finalPrice;12}13// coupon calculatin14function couponCode() {15 const coupon = document.getElementById('coupon-field');16 if (coupon.value === 'stevekaku') {17 const discount = document.getElementById('total-price').innerText;18 const discountConvert = parseFloat(discount);19 document.getElementById('final-total').innerText = discountConvert - (discountConvert * 0.2);20 }21 coupon.value = '';22};23// click handle by event bubble 24document.getElementById('buttons').addEventListener('click', function (events) {25 // memory button events26 if (events.target.innerText == '8GB unified memory') {27 const memoryField = document.getElementById('memory-field');28 memoryField.innerText = 0;29 const bestPrice = convertString('best-price');30 const memoryPrice = convertString('memory-field');31 const storagePrice = convertString('storage-field');32 const deliveryPrice = convertString('delivery-field');33 totalPrice(bestPrice, memoryPrice, storagePrice, deliveryPrice);34 }35 else if (events.target.innerText == '16GB unified memory') {36 const memoryField = document.getElementById('memory-field');37 memoryField.innerText = 180;38 const bestPrice = convertString('best-price');39 const memoryPrice = convertString('memory-field');40 const storagePrice = convertString('storage-field');41 const deliveryPrice = convertString('delivery-field');42 totalPrice(bestPrice, memoryPrice, storagePrice, deliveryPrice);43 }44 // storage button events45 else if (events.target.innerText == '256GB SSD storage') {46 const storageField = document.getElementById('storage-field');47 storageField.innerText = 0;48 const bestPrice = convertString('best-price');49 const memoryPrice = convertString('memory-field');50 const storagePrice = convertString('storage-field');51 const deliveryPrice = convertString('delivery-field');52 totalPrice(bestPrice, memoryPrice, storagePrice, deliveryPrice);53 }54 else if (events.target.innerText == '512GB SSD storage') {55 const storageField = document.getElementById('storage-field');56 storageField.innerText = 100;57 const bestPrice = convertString('best-price');58 const memoryPrice = convertString('memory-field');59 const storagePrice = convertString('storage-field');60 const deliveryPrice = convertString('delivery-field');61 totalPrice(bestPrice, memoryPrice, storagePrice, deliveryPrice);62 }63 else if (events.target.innerText == '1TB SSD storage') {64 const storageField = document.getElementById('storage-field');65 storageField.innerText = 180;66 const bestPrice = convertString('best-price');67 const memoryPrice = convertString('memory-field');68 const storagePrice = convertString('storage-field');69 const deliveryPrice = convertString('delivery-field');70 totalPrice(bestPrice, memoryPrice, storagePrice, deliveryPrice);71 }72 // delivery button events73 else if (events.target.innerText == 'Friday, Aug 25 FREE Prime delivery') {74 const storageField = document.getElementById('delivery-field');75 storageField.innerText = 0;76 const bestPrice = convertString('best-price');77 const memoryPrice = convertString('memory-field');78 const storagePrice = convertString('storage-field');79 const deliveryPrice = convertString('delivery-field');80 totalPrice(bestPrice, memoryPrice, storagePrice, deliveryPrice);81 }82 else if (events.target.innerText == 'Friday, Aug 21 delivery charge $20') {83 const storageField = document.getElementById('delivery-field');84 storageField.innerText = 20;85 const bestPrice = convertString('best-price');86 const memoryPrice = convertString('memory-field');87 const storagePrice = convertString('storage-field');88 const deliveryPrice = convertString('delivery-field');89 totalPrice(bestPrice, memoryPrice, storagePrice, deliveryPrice);90 }...
AppContext.js
Source:AppContext.js
1import React, { useState, useEffect } from "react";2export const AppContext = React.createContext();3const AppProvider = ({ children }) => {4 const [taskList, setTaskList] = useState([]);5 // const [isChecked, setIsChecked] = useState(false);6 const [completedTask, setCompletedTask] = useState([]);7 const addTaskToList = (addedTask, status) => {8 const newTask = {9 id: Math.floor(Math.random() * 100),10 taskName: addedTask,11 status: status12 };13 const updated = [...taskList, newTask];14 setTaskList(updated);15 const convertString = JSON.stringify(updated);16 localStorage.setItem("taskList", convertString);17 };18 const completionStatus = (id, checkedStatus) => {19 const found = taskList.find((task) => task.id === id);20 const newTaskList = taskList.filter((task) => task.id !== id);21 found.status = checkedStatus;22 setTaskList(newTaskList);23 const updateTaskList = JSON.stringify(newTaskList);24 localStorage.setItem("taskList", updateTaskList);25 const completedObj = {26 id: found.id,27 taskName: found.taskName,28 status: found.status29 };30 const completedTasks = [...completedTask, completedObj];31 setCompletedTask(completedTasks);32 const convertString = JSON.stringify(completedTasks);33 localStorage.setItem("completedList", convertString);34 };35 const resetStatus = (id, status) => {36 const unCheck = completedTask.find((task) => task.id === id);37 const newTaskList = completedTask.filter((task) => task.id !== id);38 unCheck.status = status;39 setCompletedTask(newTaskList);40 const completedReset = JSON.stringify(newTaskList);41 localStorage.setItem("completedList", completedReset);42 const resetObj = {43 id: unCheck.id,44 taskName: unCheck.taskName,45 status: unCheck.status46 };47 const resetTask = [...taskList, resetObj];48 setTaskList(resetTask);49 const convertString = JSON.stringify(resetTask);50 localStorage.setItem("taskList", convertString);51 };52 const deleteTask = (id) => {53 const deletedTask = taskList.filter((task) => task.id !== id);54 setTaskList(deletedTask);55 const convertString = JSON.stringify(deletedTask);56 localStorage.setItem("taskList", convertString);57 };58 const deleteCompletedTask = (id) => {59 const deletedCompletedTask = completedTask.filter((task) => task.id !== id);60 setCompletedTask(deletedCompletedTask);61 const convertString = JSON.stringify(deletedCompletedTask);62 localStorage.setItem("completedList", convertString);63 };64 const editTask = (task) => {65 const temp = taskList;66 setTaskList(temp.map((item) => (item.id === task.id ? task : item)));67 const convertString = JSON.stringify(temp);68 localStorage.setItem("taskList", convertString);69 };70 const editCompletedTask = (taskCompleted) => {71 const temp = completedTask;72 setCompletedTask(73 temp.map((item) => (item.id === temp.id ? taskCompleted : item))74 );75 const convertString = JSON.stringify(temp);76 localStorage.setItem("completedList", convertString);77 };78 useEffect(() => {79 const taskListFromStorage = localStorage.getItem("taskList");80 if (JSON.parse(taskListFromStorage)) {81 setTaskList(JSON.parse(taskListFromStorage));82 } else {83 setTaskList([]);84 }85 }, []);86 useEffect(() => {87 const completedTaskFromStorage = localStorage.getItem("completedList");88 if (JSON.parse(completedTaskFromStorage)) {89 setCompletedTask(JSON.parse(completedTaskFromStorage));90 } else {91 setCompletedTask([]);92 }93 }, [completedTask.length]);94 return (95 <AppContext.Provider96 value={{97 taskList,98 addTaskToList,99 completionStatus,100 completedTask,101 resetStatus,102 deleteTask,103 deleteCompletedTask,104 editTask,105 editCompletedTask106 }}107 >108 {children}109 </AppContext.Provider>110 );111};...
pdfconverter.js
Source:pdfconverter.js
1const { platform } = require('process');2const { Converter } = require('./main/converter');3const Options = require('./options');4/**5 * Converter6 */7class PdfToPngConverter extends Converter {8 /**9 * Define all convert options.10 */11 constructor () {12 super();13 this.convertString = '';14 }15 /**16 * Get the converter.17 *18 * @return {string}19 */20 get converter () {21 const converters = {22 darwin: this.converterForMac,23 win32: this.converterForWindows,24 default: this.converterForLinux25 };26 if (this.customConverter) {27 return this.customConverter;28 }29 if (converters[platform]) {30 return converters[platform];31 }32 return converters.default;33 }34 /**35 * Get the converter for Linux.36 *37 * todo:38 * resize (convertOptions.push('-resize ' + options.width + (options.height ? 'X' + options.height : ''));)39 * background flatten40 * strip (profile)41 *42 * @return {string}43 */44 get converterForLinux () {45 return `convert ${this.convertString} -colorspace RGB`;46 }47 /**48 * Get the converter for Mac.49 *50 * @return {string}51 */52 get converterForMac () {53 return `convert ${this.convertString} -colorspace RGB`;54 }55 /**56 * Get the converter for Mac.57 *58 * @return {strring}59 */60 get converterForWindows () {61 return `magick.exe ${this.convertString} -colorspace RGB`;62 }63 /**64 * Get the path of the new file.65 *66 * @return {string}67 */68 get newFile () {69 return this.output + this.oldFile.name + '.jpg';70 }71 /**72 * Set the convert string.73 *74 * @param {string} convertString75 */76 setConvertString (convertString) {77 if (!convertString) {78 return;79 }80 if (convertString.constructor !== String) {81 throw new Error('The convert string should be a string');82 }83 this.convertString = convertString;84 }85 /**86 * Create the converter87 *88 * @param {string} file89 * @param {string} output90 * @param {string} customConverter91 * @param {number} density92 * @param {number} quality93 *94 * @return {object}95 */96 static create ({97 file,98 output,99 customConverter,100 density,101 quality102 }) {103 const converter = new PdfToPngConverter();104 converter.setFile(file);105 converter.setOutput(output);106 converter.setConverter(customConverter);107 converter.setConvertString(Options.create({108 density,109 quality110 }).convertString);111 return converter;112 }113}...
convert-string.js
Source:convert-string.js
1declare module "convert-string" {2 declare var convertString: typeof npm$namespace$convertString;3 declare var npm$namespace$convertString: {4 stringToBytes: typeof convertString$stringToBytes,5 bytesToString: typeof convertString$bytesToString,6 UTF8: typeof npm$namespace$convertString$UTF87 };8 declare function convertString$stringToBytes(str: string): number[];9 declare function convertString$bytesToString(bytes: number[]): string;10 declare var npm$namespace$convertString$UTF8: {11 stringToBytes: typeof convertString$UTF8$stringToBytes,12 bytesToString: typeof convertString$UTF8$bytesToString13 };14 declare function convertString$UTF8$stringToBytes(str: string): number[];15 declare function convertString$UTF8$bytesToString(bytes: number[]): string;...
Using AI Code Generation
1const { convertString } = require('playwright/lib/utils/convertString');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const title = await page.title();7 console.log(convertString(title));8 await browser.close();9})();
Using AI Code Generation
1const { convertString } = require('playwright-core/lib/utils/convertString');2const { convertString } = require('playwright-core/lib/utils/convertString');3const { convertString } = require('playwright-core/lib/utils/convertString');4const { convertString } = require('playwright-core/lib/utils/convertString');5const { convertString } = require('playwright-core/lib/utils/convertString');6const { convertString } = require('playwright-core/lib/utils/convertString');7const { convertString } = require('playwright-core/lib/utils/convertString');8const { convertString } = require('playwright-core/lib/utils/convertString');9const { convertString } = require('playwright-core/lib/utils/convertString');10const { convertString } = require('playwright-core/lib/utils/convertString');11const { convertString } = require
Using AI Code Generation
1const { convertString } = require('playwright/lib/utils/convertString');2const convertedString = convertString('Hello World');3console.log(convertedString);4const { convertString } = require('playwright');5const convertedString = convertString('Hello World');6console.log(convertedString);
Using AI Code Generation
1const { convertString } = require('playwright/lib/server/convertString');2const { convertString } = require('playwright/lib/server/convertString');3const { test, expect } = require('@playwright/test');4test('My test', async ({ page }) => {5 const title = await page.title();6 expect(title).toBe('Playwright');7});8test.describe('My test', () => {9 test('My test', async ({ page }) => {10 const title = await page.title();11 expect(title).toBe('Playwright');12 });13});14test('My test', async ({ page }) => {15 await page.setContent(`<div id="foo">bar</div>`);16 const foo = await page.$('#foo');17 const text = await foo.textContent();18 expect(text).toBe('bar');19});20test('My test', async ({ page }) => {21 await page.setContent(`<div id="foo">bar</div>`);22 const foo = await page.$('#foo');23 const text = await foo.textContent();24 expect(text).toBe('bar');25});26test('My test', async ({ page }) => {27 await page.setContent(`<div id="foo">bar</div>`);28 const foo = await page.$('#foo');29 const text = await foo.textContent();30 expect(text).toBe('bar');31});32test('My test', async ({ page }) => {33 await page.setContent(`<div id="foo">bar</div>`);34 const foo = await page.$('#foo');35 const text = await foo.textContent();36 expect(text).toBe('bar');37});38test('My test', async ({ page }) => {39 await page.setContent(`<div id="foo">bar</div>`);40 const foo = await page.$('#foo');41 const text = await foo.textContent();42 expect(text).toBe('bar');43});44test('My test', async ({ page }) => {45 await page.setContent(`<div id="foo">bar</div>`);46 const foo = await page.$('#foo');47 const text = await foo.textContent();48 expect(text).toBe('bar');49});50test('My test', async ({ page }) => {51 await page.setContent(`<div id="foo">bar</div>`);
Using AI Code Generation
1const { convertString } = require('playwright-core/lib/utils/convertString');2const { assert } = require('chai');3describe('convertString', () => {4 it('should convert string', () => {5 const result = convertString('Hello World');6 assert.equal(result, 'Hello World');7 });8});
Using AI Code Generation
1const { convertString } = require('playwright-core/lib/utils/convertString');2const text = 'a string';3console.log(convertString(text));4const { convertString } = require('playwright-core');5const text = 'a string';6console.log(convertString(text));
Using AI Code Generation
1const { convertString } = require('@playwright/test');2const lowerCaseString = convertString('HELLO WORLD', 'lowercase');3console.log(lowerCaseString);4const upperCaseString = convertString('hello world', 'uppercase');5console.log(upperCaseString);6const titleCaseString = convertString('hello world', 'titlecase');7console.log(titleCaseString);8const capitalizeCaseString = convertString('hello world', 'capitalizecase');9console.log(capitalizeCaseString);10const sentenceCaseString = convertString('hello world', 'sentencecase');11console.log(sentenceCaseString);12const camelCaseString = convertString('hello world', 'camelcase');13console.log(camelCaseString);14const pascalCaseString = convertString('hello world', 'pascalcase');15console.log(pascalCaseString);16const kebabCaseString = convertString('hello world', 'kebabcase');17console.log(kebabCaseString);18const snakeCaseString = convertString('hello world', 'snakecase');19console.log(snakeCaseString);20const dotCaseString = convertString('hello world', 'dotcase');21console.log(dotCaseString);22const pathCaseString = convertString('hello world', 'pathcase');23console.log(pathCaseString);24const lowerCaseDashesString = convertString('hello world', 'lowercasedashes');25console.log(lowerCaseDashesString);26const upperCaseDashesString = convertString('hello world', 'uppercasedashes');27console.log(upperCaseDashesString);28const lowerCaseUnderscoresString = convertString('hello world', 'lowercaseunderscores');29console.log(lowerCaseUnderscoresString);30const upperCaseUnderscoresString = convertString('hello world', 'uppercaseunderscores');31console.log(upperCaseUnderscoresString);
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!