Best JavaScript code snippet using qawolf
updatedb.js
Source:updatedb.js
...24var worldDeathsRef = firebaseRef.child('worldTotal').child('deaths');25var distRef = firebaseRef.child('kerala-dist');26var dbUpdateTimeRef = firebaseRef.child('dbUpdateTime');27var updateMoment;28function updateRef(ref, id){29 ref.on('value', function(snapshot){30 //console.log(snapshot.val());31 document.getElementById(id).innerHTML = snapshot.val();32 });33}34updateRef(keralaInfectedRef, 'keralaInfected');35updateRef(keralaDeathsRef, 'keralaDeaths');36updateRef(keralaRecoveredRef, 'keralaRecovered');37updateRef(keralaInfectedTodayRef, 'keralaInfectedToday');38function dbUpdateKerala(){39 var dbKeralaInfected = document.getElementById("dbKeralaInfected").value.trim();40 if(dbKeralaInfected.length != 0){41 keralaInfectedRef.set(dbKeralaInfected);42 document.getElementById("dbKeralaInfected").value = '';43 }44 var dbKeralaDeaths = document.getElementById("dbKeralaDeaths").value.trim();45 if(dbKeralaDeaths.length != 0){46 keralaDeathsRef.set(dbKeralaDeaths);47 document.getElementById("dbKeralaDeaths").value = '';48 }49 var dbKeralaRecovered = document.getElementById("dbKeralaRecovered").value.trim();50 if(dbKeralaRecovered.length != 0){51 keralaRecoveredRef.set(dbKeralaRecovered);52 document.getElementById("dbKeralaRecovered").value = '';53 }54 var dbKeralaInfectedToday = document.getElementById("dbKeralaInfectedToday").value.trim();55 if(dbKeralaInfectedToday.length != 0){56 keralaInfectedTodayRef.set(dbKeralaInfectedToday);57 document.getElementById("dbKeralaInfectedToday").value = '';58 }59 updateMoment = moment().format('DD.MM.YYYY, h:mm a');60 dbUpdateTimeRef.set(updateMoment);61}62// world update below63updateRef(worldInfectedRef, 'worldInfected');64updateRef(worldDeathsRef, 'worldDeaths');65function dbUpdateWorld(){66 var dbWorldInfected = document.getElementById("dbWorldInfected").value.trim();67 if(dbWorldInfected.length != 0){68 worldInfectedRef.set(dbWorldInfected);69 document.getElementById("dbWorldInfected").value = '';70 }71 var dbWorldDeaths = document.getElementById("dbWorldDeaths").value.trim();72 if(dbWorldDeaths.length != 0){73 worldDeathsRef.set(dbWorldDeaths);74 document.getElementById("dbWorldDeaths").value = '';75 }76 updateMoment = moment().format('DD.MM.YYYY, h:mm a');77 dbUpdateTimeRef.set(updateMoment);78}79// India update below80updateRef(indiaInfectedRef, 'indiaInfected');81updateRef(indiaDeathsRef, 'indiaDeaths');82function dbUpdateIndia(){83 var dbIndiaInfected = document.getElementById("dbIndiaInfected").value.trim();84 if(dbIndiaInfected.length != 0){85 indiaInfectedRef.set(dbIndiaInfected);86 document.getElementById("dbIndiaInfected").value = '';87 }88 var dbIndiaDeaths = document.getElementById("dbIndiaDeaths").value.trim();89 if(dbIndiaDeaths.length != 0){90 indiaDeathsRef.set(dbIndiaDeaths);91 document.getElementById("dbIndiaDeaths").value = '';92 }93 updateMoment = moment().format('DD.MM.YYYY, h:mm a');94 dbUpdateTimeRef.set(updateMoment);95}96//district update below97//district infected ref98var kasargodInfectedRef = firebaseRef.child('kerala-dist').child('kasargod').child('infected');99var kannurInfectedRef = firebaseRef.child('kerala-dist').child('kannur').child('infected');100var wayanadInfectedRef = firebaseRef.child('kerala-dist').child('wayanad').child('infected');101var kozhikodeInfectedRef = firebaseRef.child('kerala-dist').child('kozhikode').child('infected');102var malappuramInfectedRef = firebaseRef.child('kerala-dist').child('malappuram').child('infected');103var palakkadInfectedRef = firebaseRef.child('kerala-dist').child('palakkad').child('infected');104var thrissurInfectedRef = firebaseRef.child('kerala-dist').child('thrissur').child('infected');105var eranakulamInfectedRef = firebaseRef.child('kerala-dist').child('eranakulam').child('infected');106var kottayamInfectedRef = firebaseRef.child('kerala-dist').child('kottayam').child('infected');107var idukkiInfectedRef = firebaseRef.child('kerala-dist').child('idukki').child('infected');108var alappuzhaInfectedRef = firebaseRef.child('kerala-dist').child('alappuzha').child('infected');109var pathanamthittaInfectedRef = firebaseRef.child('kerala-dist').child('pathanamthitta').child('infected');110var kollamInfectedRef = firebaseRef.child('kerala-dist').child('kollam').child('infected');111var thiruvananthapuramInfectedRef = firebaseRef.child('kerala-dist').child('thiruvananthapuram').child('infected');112//district recovered ref113var kasargodRecoveredRef = firebaseRef.child('kerala-dist').child('kasargod').child('recovered');114var kannurRecoveredRef = firebaseRef.child('kerala-dist').child('kannur').child('recovered');115var wayanadRecoveredRef = firebaseRef.child('kerala-dist').child('wayanad').child('recovered');116var kozhikodeRecoveredRef = firebaseRef.child('kerala-dist').child('kozhikode').child('recovered');117var malappuramRecoveredRef = firebaseRef.child('kerala-dist').child('malappuram').child('recovered');118var palakkadRecoveredRef = firebaseRef.child('kerala-dist').child('palakkad').child('recovered');119var thrissurRecoveredRef = firebaseRef.child('kerala-dist').child('thrissur').child('recovered');120var eranakulamRecoveredRef = firebaseRef.child('kerala-dist').child('eranakulam').child('recovered');121var kottayamRecoveredRef = firebaseRef.child('kerala-dist').child('kottayam').child('recovered');122var idukkiRecoveredRef = firebaseRef.child('kerala-dist').child('idukki').child('recovered');123var alappuzhaRecoveredRef = firebaseRef.child('kerala-dist').child('alappuzha').child('recovered');124var pathanamthittaRecoveredRef = firebaseRef.child('kerala-dist').child('pathanamthitta').child('recovered');125var kollamRecoveredRef = firebaseRef.child('kerala-dist').child('kollam').child('recovered');126var thiruvananthapuramRecoveredRef = firebaseRef.child('kerala-dist').child('thiruvananthapuram').child('recovered');127// dist infected show128updateRef(kasargodInfectedRef, 'kasargodInfected');129updateRef(kannurInfectedRef, 'kannurInfected');130updateRef(wayanadInfectedRef, 'wayanadInfected');131updateRef(kozhikodeInfectedRef, 'kozhikodeInfected');132updateRef(malappuramInfectedRef, 'malappuramInfected');133updateRef(palakkadInfectedRef, 'palakkadInfected');134updateRef(thrissurInfectedRef, 'thrissurInfected');135updateRef(eranakulamInfectedRef, 'eranakulamInfected');136updateRef(kottayamInfectedRef, 'kottayamInfected');137updateRef(idukkiInfectedRef, 'idukkiInfected');138updateRef(alappuzhaInfectedRef, 'alappuzhaInfected');139updateRef(pathanamthittaInfectedRef, 'pathanamthittaInfected');140updateRef(kollamInfectedRef, 'kollamInfected');141updateRef(thiruvananthapuramInfectedRef, 'thiruvananthapuramInfected');142// dist recovered show143updateRef(kasargodRecoveredRef, 'kasargodRecovered');144updateRef(kannurRecoveredRef, 'kannurRecovered');145updateRef(wayanadRecoveredRef, 'wayanadRecovered');146updateRef(kozhikodeRecoveredRef, 'kozhikodeRecovered');147updateRef(malappuramRecoveredRef, 'malappuramRecovered');148updateRef(palakkadRecoveredRef, 'palakkadRecovered');149updateRef(thrissurRecoveredRef, 'thrissurRecovered');150updateRef(eranakulamRecoveredRef, 'eranakulamRecovered');151updateRef(kottayamRecoveredRef, 'kottayamRecovered');152updateRef(idukkiRecoveredRef, 'idukkiRecovered');153updateRef(alappuzhaRecoveredRef, 'alappuzhaRecovered');154updateRef(pathanamthittaRecoveredRef, 'pathanamthittaRecovered');155updateRef(kollamRecoveredRef, 'kollamRecovered');156updateRef(thiruvananthapuramRecoveredRef, 'thiruvananthapuramRecovered');157function dbUpdateDistrict(){158 //update each dist infected159 var dbKasargodInfected = document.getElementById("dbKasargodInfected").value.trim();160 if(dbKasargodInfected.length != 0){161 kasargodInfectedRef.set(dbKasargodInfected)162 document.getElementById("dbKasargodInfected").value = '';163 }164 //update each dist Recovered165 var dbKasargodRecovered = document.getElementById("dbKasargodRecovered").value.trim();166 if(dbKasargodRecovered.length != 0){167 kasargodRecoveredRef.set(dbKasargodRecovered)168 document.getElementById("dbKasargodRecovered").value = '';169 }170 //update each dist infected171 var dbKannurInfected = document.getElementById("dbKannurInfected").value.trim();172 if(dbKannurInfected.length != 0){173 kannurInfectedRef.set(dbKannurInfected);174 document.getElementById("dbKannurInfected").value = '';175 }176 //update each dist Recovered177 var dbKannurRecovered = document.getElementById("dbKannurRecovered").value.trim();178 if(dbKannurRecovered.length != 0){179 kannurRecoveredRef.set(dbKannurRecovered);180 document.getElementById("dbKannurRecovered").value = '';181 }182 //update each dist infected183 var dbWayanadInfected = document.getElementById("dbWayanadInfected").value.trim();184 if(dbWayanadInfected.length != 0){185 wayanadInfectedRef.set(dbWayanadInfected);186 document.getElementById("dbWayanadInfected").value = '';187 }188 //update each dist Recovered189 var dbWayanadRecovered = document.getElementById("dbWayanadRecovered").value.trim();190 if(dbWayanadRecovered.length != 0){191 wayanadRecoveredRef.set(dbWayanadRecovered);192 document.getElementById("dbWayanadRecovered").value = '';193 }194 //update each dist infected195 var dbKozhikodeInfected = document.getElementById("dbKozhikodeInfected").value.trim();196 if(dbKozhikodeInfected.length != 0){197 kozhikodeInfectedRef.set(dbKozhikodeInfected)198 document.getElementById("dbKozhikodeInfected").value = '';199 }200 //update each dist Recovered201 var dbKozhikodeRecovered = document.getElementById("dbKozhikodeRecovered").value.trim();202 if(dbKozhikodeRecovered.length != 0){203 kozhikodeRecoveredRef.set(dbKozhikodeRecovered)204 document.getElementById("dbKozhikodeRecovered").value = '';205 }206 //update each dist infected207 var dbMalappuramInfected = document.getElementById("dbMalappuramInfected").value.trim();208 if(dbMalappuramInfected.length != 0){209 malappuramInfectedRef.set(dbMalappuramInfected)210 document.getElementById("dbMalappuramInfected").value = '';211 }212 //update each dist Recovered213 var dbMalappuramRecovered = document.getElementById("dbMalappuramRecovered").value.trim();214 if(dbMalappuramRecovered.length != 0){215 malappuramRecoveredRef.set(dbMalappuramRecovered)216 document.getElementById("dbMalappuramRecovered").value = '';217 }218 //update each dist infected219 var dbPalakkadInfected = document.getElementById("dbPalakkadInfected").value.trim();220 if(dbPalakkadInfected.length != 0){221 palakkadInfectedRef.set(dbPalakkadInfected)222 document.getElementById("dbPalakkadInfected").value = '';223 }224 //update each dist Recovered225 var dbPalakkadRecovered = document.getElementById("dbPalakkadRecovered").value.trim();226 if(dbPalakkadRecovered.length != 0){227 palakkadRecoveredRef.set(dbPalakkadRecovered)228 document.getElementById("dbPalakkadRecovered").value = '';229 }230 //update each dist infected231 var dbThrissurInfected = document.getElementById("dbThrissurInfected").value.trim();232 if(dbThrissurInfected.length != 0){233 thrissurInfectedRef.set(dbThrissurInfected)234 document.getElementById("dbThrissurInfected").value = '';235 }236 //update each dist Recovered237 var dbThrissurRecovered = document.getElementById("dbThrissurRecovered").value.trim();238 if(dbThrissurRecovered.length != 0){239 thrissurRecoveredRef.set(dbThrissurRecovered)240 document.getElementById("dbThrissurRecovered").value = '';241 }242 //update each dist infected243 var dbEranakulamInfected = document.getElementById("dbEranakulamInfected").value.trim();244 if(dbEranakulamInfected.length != 0){245 eranakulamInfectedRef.set(dbEranakulamInfected)246 document.getElementById("dbEranakulamInfected").value = '';247 }248 //update each dist Recovered249 var dbEranakulamRecovered = document.getElementById("dbEranakulamRecovered").value.trim();250 if(dbEranakulamRecovered.length != 0){251 eranakulamRecoveredRef.set(dbEranakulamRecovered)252 document.getElementById("dbEranakulamRecovered").value = '';253 }254 //update each dist infected255 var dbKottayamInfected = document.getElementById("dbKottayamInfected").value.trim();256 if(dbKottayamInfected.length != 0){257 kottayamInfectedRef.set(dbKottayamInfected)258 document.getElementById("dbKottayamInfected").value = '';259 }260 //update each dist Recovered261 var dbKottayamRecovered = document.getElementById("dbKottayamRecovered").value.trim();262 if(dbKottayamRecovered.length != 0){263 kottayamRecoveredRef.set(dbKottayamRecovered)264 document.getElementById("dbKottayamRecovered").value = '';265 }266 //update each dist infected267 var dbIdukkiInfected = document.getElementById("dbIdukkiInfected").value.trim();268 if(dbIdukkiInfected.length != 0){269 idukkiInfectedRef.set(dbIdukkiInfected);270 document.getElementById("dbIdukkiInfected").value = '';271 }272 //update each dist Recovered273 var dbIdukkiRecovered = document.getElementById("dbIdukkiRecovered").value.trim();274 if(dbIdukkiRecovered.length != 0){275 idukkiRecoveredRef.set(dbIdukkiRecovered);276 document.getElementById("dbIdukkiRecovered").value = '';277 }278 //update each dist infected279 var dbAlappuzhaInfected = document.getElementById("dbAlappuzhaInfected").value.trim();280 if(dbAlappuzhaInfected.length != 0){281 alappuzhaInfectedRef.set(dbAlappuzhaInfected);282 document.getElementById("dbAlappuzhaInfected").value = '';283 }284 //update each dist Recovered285 var dbAlappuzhaRecovered = document.getElementById("dbAlappuzhaRecovered").value.trim();286 if(dbAlappuzhaRecovered.length != 0){287 alappuzhaRecoveredRef.set(dbAlappuzhaRecovered);288 document.getElementById("dbAlappuzhaRecovered").value = '';289 }290 //update each dist infected291 var dbPathanamthittaInfected = document.getElementById("dbPathanamthittaInfected").value.trim();292 if(dbPathanamthittaInfected.length != 0){293 pathanamthittaInfectedRef.set(dbPathanamthittaInfected);294 document.getElementById("dbPathanamthittaInfected").value = '';295 }296 //update each dist Recovered297 var dbPathanamthittaRecovered = document.getElementById("dbPathanamthittaRecovered").value.trim();298 if(dbPathanamthittaRecovered.length != 0){299 pathanamthittaRecoveredRef.set(dbPathanamthittaRecovered);300 document.getElementById("dbPathanamthittaRecovered").value = '';301 }302 //update each dist infected303 var dbKollamInfected = document.getElementById("dbKollamInfected").value.trim();304 if(dbKollamInfected.length != 0){305 kollamInfectedRef.set(dbKollamInfected);306 document.getElementById("dbKollamInfected").value = '';307 }308 //update each dist Recovered309 var dbKollamRecovered = document.getElementById("dbKollamRecovered").value.trim();310 if(dbKollamRecovered.length != 0){311 kollamRecoveredRef.set(dbKollamRecovered);312 document.getElementById("dbKollamRecovered").value = '';313 }314 //update each dist infected315 var dbThiruvananthapuramInfected = document.getElementById("dbThiruvananthapuramInfected").value.trim();316 if(dbThiruvananthapuramInfected.length != 0){317 thiruvananthapuramInfectedRef.set(dbThiruvananthapuramInfected);318 document.getElementById("dbThiruvananthapuramInfected").value = '';319 }320 var dbThiruvananthapuramRecovered = document.getElementById("dbThiruvananthapuramRecovered").value.trim();321 if(dbThiruvananthapuramRecovered.length != 0){322 thiruvananthapuramRecoveredRef.set(dbThiruvananthapuramRecovered);323 document.getElementById("dbThiruvananthapuramRecovered").value = '';324 }325 updateMoment = moment().format('DD.MM.YYYY, h:mm a');326 dbUpdateTimeRef.set(updateMoment);327}328function updateTime(ref, id){329 ref.on('value', function(snapshot){330 var v = snapshot.val();331 document.getElementById(id).innerHTML = moment(v, "DD.MM.YYYY h:mm a").locale('ml').fromNow() + ' à´
à´ªàµà´¡àµà´±àµà´±àµ à´àµà´¯àµà´¤àµ';332 });333}334updateTime(dbUpdateTimeRef, 'moment');335// const ml = moment('2020.01.01', 'YYYY.MM.DD').locale('ml')336// console.log(ml.fromNow());337//dist today inf338var kasargodTodayRef = firebaseRef.child('kerala-dist').child('kasargod').child('today');339var kannurTodayRef = firebaseRef.child('kerala-dist').child('kannur').child('today');340var wayanadTodayRef = firebaseRef.child('kerala-dist').child('wayanad').child('today');341var kozhikodeTodayRef = firebaseRef.child('kerala-dist').child('kozhikode').child('today');342var malappuramTodayRef = firebaseRef.child('kerala-dist').child('malappuram').child('today');343var palakkadTodayRef = firebaseRef.child('kerala-dist').child('palakkad').child('today');344var thrissurTodayRef = firebaseRef.child('kerala-dist').child('thrissur').child('today');345var eranakulamTodayRef = firebaseRef.child('kerala-dist').child('eranakulam').child('today');346var kottayamTodayRef = firebaseRef.child('kerala-dist').child('kottayam').child('today');347var idukkiTodayRef = firebaseRef.child('kerala-dist').child('idukki').child('today');348var alappuzhaTodayRef = firebaseRef.child('kerala-dist').child('alappuzha').child('today');349var pathanamthittaTodayRef = firebaseRef.child('kerala-dist').child('pathanamthitta').child('today');350var kollamTodayRef = firebaseRef.child('kerala-dist').child('kollam').child('today');351var thiruvananthapuramTodayRef = firebaseRef.child('kerala-dist').child('thiruvananthapuram').child('today');352var keralaTodayRef = firebaseRef.child('kerala-total').child('today');353updateRef(kasargodTodayRef, 'kasargodToday');354updateRef(kannurTodayRef, 'kannurToday');355updateRef(wayanadTodayRef, 'wayanadToday');356updateRef(kozhikodeTodayRef, 'kozhikodeToday');357updateRef(malappuramTodayRef, 'malappuramToday');358updateRef(palakkadTodayRef, 'palakkadToday');359updateRef(thrissurTodayRef, 'thrissurToday');360updateRef(eranakulamTodayRef, 'eranakulamToday');361updateRef(kottayamTodayRef, 'kottayamToday');362updateRef(idukkiTodayRef, 'idukkiToday');363updateRef(alappuzhaTodayRef, 'alappuzhaToday');364updateRef(pathanamthittaTodayRef, 'pathanamthittaToday');365updateRef(kollamTodayRef, 'kollamToday');366updateRef(thiruvananthapuramTodayRef, 'thiruvananthapuramToday');367updateRef(keralaTodayRef, 'keralaToday');368function dbUpdateToday(){369 var dbKeralaToday = document.getElementById("dbKeralaToday").value.trim();370 if(dbKeralaToday.length != 0){371 keralaTodayRef.set(dbKeralaToday);372 document.getElementById("dbKeralaToday").value = '';373 }374 var dbKasargodToday = document.getElementById("dbKasargodToday").value.trim();375 if(dbKasargodToday.length != 0){376 kasargodTodayRef.set(dbKasargodToday);377 document.getElementById("dbKasargodToday").value = '';378 }379 var dbKannurToday = document.getElementById("dbKannurToday").value.trim();380 if(dbKannurToday.length != 0){381 kannurTodayRef.set(dbKannurToday);382 document.getElementById("dbKannurToday").value = '';383 }384 var dbWayanadToday = document.getElementById("dbWayanadToday").value.trim();385 if(dbWayanadToday.length != 0){386 wayanadTodayRef.set(dbWayanadToday);387 document.getElementById("dbWayanadToday").value = '';388 }389 var dbKozhikodeToday = document.getElementById("dbKozhikodeToday").value.trim();390 if(dbKozhikodeToday.length != 0){391 kozhikodeTodayRef.set(dbKozhikodeToday);392 document.getElementById("dbKozhikodeToday").value = '';393 }394 var dbMalappuramToday = document.getElementById("dbMalappuramToday").value.trim();395 if(dbMalappuramToday.length != 0){396 malappuramTodayRef.set(dbMalappuramToday);397 document.getElementById("dbMalappuramToday").value = '';398 }399 var dbPalakkadToday = document.getElementById("dbPalakkadToday").value.trim();400 if(dbPalakkadToday.length != 0){401 palakkadTodayRef.set(dbPalakkadToday);402 document.getElementById("dbPalakkadToday").value = '';403 }404 var dbThrissurToday = document.getElementById("dbThrissurToday").value.trim();405 if(dbThrissurToday.length != 0){406 thrissurTodayRef.set(dbThrissurToday);407 document.getElementById("dbThrissurToday").value = '';408 }409 var dbEranakulamToday = document.getElementById("dbEranakulamToday").value.trim();410 if(dbEranakulamToday.length != 0){411 eranakulamTodayRef.set(dbEranakulamToday);412 document.getElementById("dbEranakulamToday").value = '';413 }414 var dbKottayamToday = document.getElementById("dbKottayamToday").value.trim();415 if(dbKottayamToday.length != 0){416 kottayamTodayRef.set(dbKottayamToday);417 document.getElementById("dbKottayamToday").value = '';418 }419 var dbIdukkiToday = document.getElementById("dbIdukkiToday").value.trim();420 if(dbIdukkiToday.length != 0){421 idukkiTodayRef.set(dbIdukkiToday);422 document.getElementById("dbIdukkiToday").value = '';423 }424 var dbAlappuzhaToday = document.getElementById("dbAlappuzhaToday").value.trim();425 if(dbAlappuzhaToday.length != 0){426 alappuzhaTodayRef.set(dbAlappuzhaToday);427 document.getElementById("dbAlappuzhaToday").value = '';428 }429 var dbPathanamthittaToday = document.getElementById("dbPathanamthittaToday").value.trim();430 if(dbPathanamthittaToday.length != 0){431 pathanamthittaTodayRef.set(dbPathanamthittaToday);432 document.getElementById("dbPathanamthittaToday").value = '';433 }434 var dbKollamToday = document.getElementById("dbKollamToday").value.trim();435 if(dbKollamToday.length != 0){436 kollamTodayRef.set(dbKollamToday);437 document.getElementById("dbKollamToday").value = '';438 }439 var dbThiruvananthapuramToday = document.getElementById("dbThiruvananthapuramToday").value.trim();440 if(dbThiruvananthapuramToday.length != 0){441 thiruvananthapuramTodayRef.set(dbThiruvananthapuramToday);442 document.getElementById("dbThiruvananthapuramToday").value = '';443 }444}445//-------------------------446var todaySwitch = firebaseRef.child('kerala-total').child('todaySwitch');447updateRef(todaySwitch, 'toggleText');448toggleButton.addEventListener('click', event => {449 var state;450 todaySwitch.on('value', function(snapshot){451 state = snapshot.val();452 });453 if(state == 'on'){454 todaySwitch.set('off');455 } else {456 todaySwitch.set('on');457 }...
postsHandler.js
Source:postsHandler.js
1const { db, admin, auth, functions } = require("../utils/firebase");2exports.getPosts = async (req, res) => {3 const postsRef = await db.collection("post").get();4 let posts = [];5 postsRef.forEach((doc) => posts.push(doc.data()));6 return res.json(posts);7};8exports.getInfo = async (req, res) => {9 const postsRef = await db.collection("info").get();10 let posts = [];11 postsRef.forEach((doc) => posts.push(doc.data()));12 return res.json(posts);13};14exports.updateUserInfo = async (req, res) => {15 const { userName } = req.body;16 const userId = req.user.uid;17 try {18 const updateUserRef = await db.collection("users").doc(userId);19 let data = {20 userName,21 };22 updateUserRef.update(data);23 res.status(200).send({24 status: "success",25 message: "data added successfully",26 data: data,27 });28 } catch (error) {29 res.status(500).json(error.message);30 }31};32exports.deleteUser = (req, res) => {33 admin.auth34 .deleteUser(uid)35 .then(() => {36 console.log("Successfully deleted user");37 })38 .catch((error) => {39 console.log("Error deleting user:", error);40 });41};42// exports.allUsers = async (req, res) =>{43// try {44// let listUsers = await auth.listUsers()45// // for (i = 0; i < listUsers.users.length; i++){46// // var obj = listUsers.users[i].email47// // console.log(obj)48// // }49// var obj = listUsers.users.map(emails => emails.email)50// console.log(listUsers)51// return res.status(200).send(obj)52// } catch (err) {53// return res.status(500).send({ message: `${err}`});54// }55// }56exports.postData = async (req, res) => {57 const { title, text } = req.body;58 try {59 const dataRef = await db.collection("post").doc();60 let entryData = {61 id: new Date(),62 title,63 text,64 };65 dataRef.set(entryData);66 res.status(200).send({67 status: "success",68 message: "entry added successfully",69 data: entryData,70 });71 } catch (error) {72 res.status(500).json(error.message);73 }74};75exports.postAtsiliepimus = async (req, res) => {76 const { atsiliepimas, name } = req.body;77 // const docId = req.params.id;78 const userId = req.user.uid;79 const userEmail = req.user.email;80 try {81 const dataRef = await db.collection("atsiliepimai").doc();82 let entryData = {83 time: new Date(),84 userId: userId,85 email: userEmail,86 documentId: dataRef.id,87 atsiliepimas,88 name,89 };90 dataRef.set(entryData);91 res.status(200).send({92 status: "success",93 message: "entry added successfully",94 data: entryData,95 });96 } catch (error) {97 res.status(500).json(error.message);98 }99};100exports.postVizitoInfo = async (req, res) => {101 const {102 Vardas,103 Pavarde,104 TelefonoNr,105 ElPastas,106 DatePicker,107 VaikoDuom,108 } = req.body;109 try {110 const vizitoRef = await db.collection("vizitas").doc();111 let vizitoData = {112 time: admin.firestore.Timestamp.fromDate(new Date(DatePicker)),113 createdTime: new Date(),114 perziureta: false,115 vardas: Vardas,116 pavarde: Pavarde,117 telNr: TelefonoNr,118 elPastas: ElPastas,119 vaikoDuomenys: VaikoDuom,120 documentId: vizitoRef.id,121 };122 vizitoRef.set(vizitoData);123 res.status(200).send({124 status: "success",125 message: "entry added successfully",126 data: vizitoData,127 });128 } catch (error) {129 res.status(500).json(error.message);130 }131};132exports.postKlausimas = async (req, res) => {133 const { klausimas, anonymousEmail, perziureta } = req.body;134 try {135 const klausimoRef = await db.collection("klausimai").doc(anonymousEmail);136 let Data = {137 createTime: new Date(),138 klausimas,139 anonymousEmail,140 perziureta: false,141 };142 klausimoRef.set(Data);143 res.status(200).send({144 status: "success",145 message: "data added successfully",146 data: Data,147 });148 } catch (error) {149 res.status(500).json(error.message);150 }151};152exports.postVaikoRez = async (req, res) => {153 const userId = req.user.uid;154 const {155 TevuVardas,156 TevuPavarde,157 TevuEmail,158 TevuTelNum,159 VaikoVardas,160 VaikoAmzius,161 AntrasVaikas,162 AntroVaikoVardas,163 AntroVaikoAmzius,164 } = req.body;165 // console.log(AntrasVaikas);166 if (AntrasVaikas === false) {167 try {168 const vaikoRezRef = await db.collection("vaikoRezervacija").doc(userId);169 let vaikoData = {170 createTime: new Date(),171 userId: userId,172 TevuVardas,173 TevuPavarde,174 TevuEmail,175 TevuTelNum,176 VaikoVardas,177 VaikoAmzius,178 AntrasVaikas,179 AdminConfirm: false,180 };181 if (!Number.isInteger(VaikoAmzius)) {182 res.status(500).json("Vaiko amzius turi buti sveikasis skaicius");183 } else if (VaikoAmzius > 3 || VaikoAmzius < 1) {184 res185 .status(500)186 .json(187 "Pirmos vaiko amzius negali buti didesnis nei 3 metai ir ne mazesnis nei 1 metai"188 );189 } else vaikoRezRef.set(vaikoData);190 const vaikoLankomumoRez = await db191 .collection("vaikoLankomumas")192 .doc(userId);193 let vaikoLankomumoData = {194 createTime: new Date(),195 userId: userId,196 Pirm_Pirmadienis: false,197 Pirm_Antradienis: false,198 Pirm_Treciadienis: false,199 Pirm_Ketvirtadienis: false,200 Pirm_Penktadienis: false,201 AntrasVaikas,202 TevuEmail,203 };204 vaikoLankomumoRez.set(vaikoLankomumoData);205 res.status(200).send({206 status: "success",207 message: "Duomenys ikelti vieno vaiko",208 data: vaikoData,209 });210 } catch (error) {211 res.status(500).json(error.message);212 }213 } else if (AntrasVaikas === true) {214 try {215 const vaikoRezRef = await db.collection("vaikoRezervacija").doc(userId);216 let vaikoData = {217 createTime: new Date(),218 userId: userId,219 TevuVardas,220 TevuPavarde,221 TevuEmail,222 TevuTelNum,223 VaikoVardas,224 VaikoAmzius,225 AntrasVaikas,226 AntroVaikoVardas,227 AntroVaikoAmzius,228 AdminConfirm: false,229 };230 if (!Number.isInteger(AntroVaikoAmzius)) {231 res.status(500).json("Vaiko amzius turi buti sveikasis skaicius");232 } else if (AntroVaikoAmzius > 3 || AntroVaikoAmzius < 1) {233 res234 .status(500)235 .json(236 "Antro vaiko amzius negali buti didesnis nei 3 metai ir ne mazesnis nei 1 metai"237 );238 } else if (!Number.isInteger(TevuTelNum)) {239 res.status(500).json("Telefono numeris turi susideti tik is skaiciu");240 } else vaikoRezRef.set(vaikoData);241 const vaikoLankomumoRez = await db242 .collection("vaikoLankomumas")243 .doc(userId);244 let vaikoLankomumoData = {245 createTime: new Date(),246 userId: userId,247 Pirm_Pirmadienis: false,248 Pirm_Antradienis: false,249 Pirm_Treciadienis: false,250 Pirm_Ketvirtadienis: false,251 Pirm_Penktadienis: false,252 Antr_Pirmadienis: false,253 Antr_Antradienis: false,254 Antr_Treciadienis: false,255 Antr_Ketvirtadienis: false,256 Antr_Penktadienis: false,257 AntrasVaikas,258 TevuEmail,259 };260 vaikoLankomumoRez.set(vaikoLankomumoData);261 res.status(200).send({262 status: "success",263 message: "Duomenys ikelti dvieju vaiku",264 data: vaikoData,265 });266 } catch (error) {267 res.status(500).json(error.message);268 }269 }270};271exports.updateVaikoLankomumaPirm = async (req, res) => {272 const userId = req.user.uid;273 const updateRef = await db274 .collection("vaikoLankomumas")275 .doc(req.params.id)276 .get();277 try {278 let entryData = {279 Pirm_Pirmadienis: !updateRef.data().Pirm_Pirmadienis,280 };281 updateRef.ref.update(entryData);282 res.status(200).send({283 status: "success",284 data: entryData,285 });286 } catch (error) {287 res.status(500).json(error.message);288 }289};290exports.updateVaikoLankomumaAntr = async (req, res) => {291 const userId = req.user.uid;292 const updateRef = await db293 .collection("vaikoLankomumas")294 .doc(req.params.id)295 .get();296 try {297 let entryData = {298 Pirm_Antradienis: !updateRef.data().Pirm_Antradienis,299 };300 updateRef.ref.update(entryData);301 res.status(200).send({302 status: "success",303 data: entryData,304 });305 } catch (error) {306 res.status(500).json(error.message);307 }308};309exports.updateVaikoLankomumaTrec = async (req, res) => {310 const userId = req.user.uid;311 const updateRef = await db312 .collection("vaikoLankomumas")313 .doc(req.params.id)314 .get();315 try {316 let entryData = {317 Pirm_Treciadienis: !updateRef.data().Pirm_Treciadienis,318 };319 updateRef.ref.update(entryData);320 res.status(200).send({321 status: "success",322 data: entryData,323 });324 } catch (error) {325 res.status(500).json(error.message);326 }327};328exports.updateVaikoLankomumaKetv = async (req, res) => {329 const userId = req.user.uid;330 const updateRef = await db331 .collection("vaikoLankomumas")332 .doc(req.params.id)333 .get();334 try {335 let entryData = {336 Pirm_Ketvirtadienis: !updateRef.data().Pirm_Ketvirtadienis,337 };338 updateRef.ref.update(entryData);339 res.status(200).send({340 status: "success",341 data: entryData,342 });343 } catch (error) {344 res.status(500).json(error.message);345 }346};347exports.updateVaikoLankomumaPenkt = async (req, res) => {348 const userId = req.user.uid;349 const updateRef = await db350 .collection("vaikoLankomumas")351 .doc(req.params.id)352 .get();353 try {354 let entryData = {355 Pirm_Penktadienis: !updateRef.data().Pirm_Penktadienis,356 };357 updateRef.ref.update(entryData);358 res.status(200).send({359 status: "success",360 data: entryData,361 });362 } catch (error) {363 res.status(500).json(error.message);364 }365};366exports.updateVaiko2LankomumaPirm = async (req, res) => {367 const userId = req.user.uid;368 const updateRef = await db369 .collection("vaikoLankomumas")370 .doc(req.params.id)371 .get();372 try {373 let entryData = {374 Antr_Pirmadienis: !updateRef.data().Antr_Pirmadienis,375 };376 updateRef.ref.update(entryData);377 res.status(200).send({378 status: "success",379 data: entryData,380 });381 } catch (error) {382 res.status(500).json(error.message);383 }384};385exports.updateVaiko2LankomumaAntr = async (req, res) => {386 const userId = req.user.uid;387 const updateRef = await db388 .collection("vaikoLankomumas")389 .doc(req.params.id)390 .get();391 try {392 let entryData = {393 Antr_Antradienis: !updateRef.data().Antr_Antradienis,394 };395 updateRef.ref.update(entryData);396 res.status(200).send({397 status: "success",398 data: entryData,399 });400 } catch (error) {401 res.status(500).json(error.message);402 }403};404exports.updateVaiko2LankomumaTrec = async (req, res) => {405 const userId = req.user.uid;406 const updateRef = await db407 .collection("vaikoLankomumas")408 .doc(req.params.id)409 .get();410 try {411 let entryData = {412 Antr_Treciadienis: !updateRef.data().Antr_Treciadienis,413 };414 updateRef.ref.update(entryData);415 res.status(200).send({416 status: "success",417 data: entryData,418 });419 } catch (error) {420 res.status(500).json(error.message);421 }422};423exports.updateVaiko2LankomumaKetv = async (req, res) => {424 const userId = req.user.uid;425 const updateRef = await db426 .collection("vaikoLankomumas")427 .doc(req.params.id)428 .get();429 try {430 let entryData = {431 Antr_Ketvirtadienis: !updateRef.data().Antr_Ketvirtadienis,432 };433 updateRef.ref.update(entryData);434 res.status(200).send({435 status: "success",436 data: entryData,437 });438 } catch (error) {439 res.status(500).json(error.message);440 }441};442exports.updateVaiko2LankomumaPenkt = async (req, res) => {443 const userId = req.user.uid;444 const updateRef = await db445 .collection("vaikoLankomumas")446 .doc(req.params.id)447 .get();448 try {449 let entryData = {450 Antr_Penktadienis: !updateRef.data().Antr_Penktadienis,451 };452 updateRef.ref.update(entryData);453 res.status(200).send({454 status: "success",455 data: entryData,456 });457 } catch (error) {458 res.status(500).json(error.message);459 }460};461exports.getVaikoLankomumoDuom = async (req, res) => {462 const userId = req.user.uid;463 const vaikoDuomRef = await db464 .collection("vaikoLankomumas")465 .where("userId", "==", userId)466 .get();467 let vaikoDuom = [];468 vaikoDuomRef.forEach((doc) => vaikoDuom.push(doc.data()));469 let vaikoData = {470 vaikoDuom,471 };472 return res.json(vaikoData);473};474exports.getVaikoDuom = async (req, res) => {475 const userId = req.user.uid;476 const vaikoDuomRef = await db477 .collection("vaikoRezervacija")478 .where("userId", "==", userId)479 .get();480 let vaikoDuom = [];481 vaikoDuomRef.forEach((doc) => vaikoDuom.push(doc.data()));482 let vaikoData = {483 vaikoDuom,484 };485 return res.json(vaikoData);486};487exports.postVaikoMaistas = async (req, res) => {488 const userId = req.user.uid;489 const { maistoKoregavimas } = req.body;490 try {491 const maistoRef = await db.collection("vaikoRezervacija").doc(userId);492 const getMaistoRef = await db493 .collection("vaikoRezervacija")494 .doc(userId)495 .get();496 let Data = {497 maistoSukurimoData: new Date(),498 maistoKoregavimas,499 };500 if (getMaistoRef._fieldsProto.AdminConfirm.booleanValue === true) {501 maistoRef.update(Data);502 res.status(200).send({503 status: "success",504 message: "data added successfully",505 data: Data,506 });507 } else {508 res.status(403).json("Vaikas dar nepriimtas i darzeli");509 }510 } catch (error) {511 res.status(500).json(error.message);512 }513};514// exports.postZinute = async (req, res) => {515// const userId = req.user.uid;516// const { zinute } = req.body;517// const adminId = "EkK9USOqRLUeLyQ52qUgom7xSrf2"518// try {519// const zinutesRef = await db520// .collection("Zinute")521// .doc(userId)522// .collection("Tekstas");523// let data = {524// createTime: new Date(),525// zinute,526// userId: userId,527// adminId: adminId,528// };529// zinutesRef.add(data);530// res.status(200).send({531// status: "success",532// message: "data added successfully",533// data: data,534// });535// } catch (error) {536// res.status(500).json(error.message);537// }538// };539// exports.getZinutesDuom = async (req, res) => {540// const userId = req.user.uid;541// const adminId = "EkK9USOqRLUeLyQ52qUgom7xSrf2"542// console.log(adminId)543// try {544// const zinutesDuomRef = await db545// .collection("Zinute")546// .doc(userId + adminId)547// .collection("Tekstas")548// .where("adminId", "==", adminId)549// .get();550// let zinutesDuom = [];551// zinutesDuomRef.forEach((doc) => zinutesDuom.push(doc.data()));552// let zinutesData = {553// zinutesDuom,554// };555// res.json(zinutesData);556// } catch (error) {557// res.status(500).json(error.message);558// }559// };560exports.getNaujausiAtsiliepimai = async (req, res) => {561 const atsiliepimuRef = await db562 .collection("atsiliepimai")563 .orderBy("time", "desc")564 .limit(4)565 .get();566 let atsiliepimai = [];567 atsiliepimuRef.forEach((doc) => atsiliepimai.push(doc.data()));568 let data = {569 atsiliepimai,570 };571 return res.json(data);572};573exports.deleteKomentara = async (req, res) => {574 // const userId = req.user.uid;575 await db576 .collection("atsiliepimai")577 .doc(req.params.id)578 .delete()579 .then(() => {580 console.log(req.params.id);581 if (!req.params.id) {582 res.status(500).json(error.meesage);583 } else {584 res.status(200).json("Success");585 // res.status(200).send({586 // status: "success",587 // });588 }589 })590 .catch((error) => {591 res.status(500).json(error.message);592 });593 // const deleteRef =await db594 // .collection("Atsiliepimai")595 // .doc(req.params.id)596 // .delete()597 // .then(598 // res.status(200).send({599 // status: "duomenys istrinti",600 // })601 // ).catch((error) => alert(error));602 // .then(603 // res.status(200).send({604 // status: "duomenys istrinti",605 // })606 // )607 // .catch((error) => alert(error.message));...
main.jsx
Source:main.jsx
...32 if (websocket.current && websocket.current.readyState === WebSocket.OPEN) disconnect();33 }34 }, []);35 const resetState = () => {36 updateRef(0, connectionStatusRef, setConnectionStatus);37 updateRef(null, tokenRef, setToken);38 updateRef(null, nameRef, setName);39 updateRef(null, myIdRef, setMyId);40 updateRef(null, myPlayerRef, setMyPlayer);41 updateRef({ board: [0, 0, 0, 0, 0, 0, 0, 0, 0] }, gameStateRef, setGameState);42 }43 const useInterval = (callback, delay) => {44 const savedCallback = useRef();45 useEffect(() => {46 savedCallback.current = callback;47 }, [callback]);48 useEffect(() => {49 function tick() {50 savedCallback.current();51 }52 if (delay !== null) {53 let id = setInterval(tick, delay);54 return () => clearInterval(id);55 }56 }, [delay]);57 }58 const updateRef = (newValue, ref, stateFunc) => {59 ref.current = newValue;60 stateFunc(newValue);61 }62 const findMyPlayer = (state) => {63 if (myId === state.idPlayer1 || myIdRef.current === state.idPlayer1) return 1;64 if (myId === state.idPlayer2 || myIdRef.current === state.idPlayer2) return 2;65 return null;66 }67 const findMyName = () => {68 if(myIdRef.current === gameStateRef.current.idPlayer1) return gameStateRef.current.namePlayer1;69 if(myIdRef.current === gameStateRef.current.idPlayer2) return gameStateRef.current.namePlayer2;70 return '';71 }72 const makeResult = (result) => {73 let message = '';74 let icon = null;75 if(result === 2) {76 message = 'Empate!';77 icon = (<MehOutlined />);78 }79 if(result === 3 && myPlayerRef.current === 1) {80 message = 'Parabéns ' + findMyName() + ', você venceu!';81 icon = (<SmileOutlined />);82 }83 if(result === 3 && myPlayerRef.current === 2) {84 message = findMyName() + ', infelizmente você perdeu!';85 icon = (<FrownOutlined />);86 }87 if(result === 4 && myPlayerRef.current === 1) {88 message = findMyName() + ', infelizmente você perdeu!';89 icon = (<FrownOutlined />);90 }91 if(result === 4 && myPlayerRef.current === 2) {92 message = 'Parabéns ' + findMyName() + ', você venceu!';93 icon = (<SmileOutlined />);94 }95 return {96 message: message,97 icon: icon98 };99 }100 const showResults = (status) => {101 updateRef(makeResult(status), resultsObjRef, setResultsObj);102 updateRef(true, resultsVisibleRef, setResultsVisible);103 setTimeout(104 function() {105 disconnect();106 }, 1000);107 }108 const handleAction = (response, ws) => {109 const action = response.action;110 switch (action) {111 case 2:112 if (response.token) {113 updateRef(jwt_decode(response.token).clientId, myIdRef, setMyId);114 updateRef(response.token, tokenRef, setToken);115 if (response.message) message.success(response.message);116 const request = {117 'action': 3,118 'token': response.token119 }120 ws.send(JSON.stringify(request));121 }122 else if (response.message) message.error(response.message);123 break;124 case 3:125 message.success('Você foi adicionado ao jogo');126 break;127 case 4:128 resetState();129 disconnect();130 if (response.message) message.info(response.message);131 break;132 case 5:133 if (response.message) message.info(response.message);134 break;135 case 6:136 if (response.gameState) {137 if (gameStateRef.current) {138 if (gameStateRef.current.status === 1 && response.gameState.status === 0) message.info('Seu oponente desconectou. O jogo foi encerrado');139 }140 if (!myPlayer) {141 updateRef(findMyPlayer(response.gameState), myPlayerRef, setMyPlayer);142 }143 if([2, 3, 4].includes(response.gameState.status)) showResults(response.gameState.status);144 updateRef(response.gameState, gameStateRef, setGameState);145 }146 if (response.message) message.info(response.message);147 break;148 default:149 break;150 }151 }152 const connect = () => {153 const protocol = 'ws:';154 const hostname = document.location.hostname;155 const port = socketPort;156 const ip = protocol + '//' + hostname + ':' + port;157 var ws = new WebSocket(ip);158 websocket.current = ws;159 updateRef(1, connectionStatusRef, setConnectionStatus);160 ws.onopen = () => {161 updateRef(2, connectionStatusRef, setConnectionStatus);162 const request = {163 'action': 2,164 'name': name165 }166 ws.send(JSON.stringify(request));167 }168 ws.onmessage = (response) => {169 response = JSON.parse(response.data);170 console.log(response);171 if (response && response.action) {172 handleAction(response, ws);173 }174 else if (response && response.message) message.error(response.message);175 }176 ws.onclose = () => {177 message.error('Desconectado do servidor');178 resetState();179 }180 }181 useInterval(() => {182 const syncRequest = {183 'action': 6,184 'token': token185 }186 websocket.current.send(JSON.stringify(syncRequest));187 }, (token && websocket.current.readyState === WebSocket.OPEN) ? syncDelay : null);188 const disconnect = () => {189 const request = {190 'action': 4,191 'name': name,192 'token': token193 }194 if (websocket.current && websocket.current.readyState === WebSocket.OPEN) {195 websocket.current.send(JSON.stringify(request));196 websocket.current.close();197 }198 resetState();199 }200 const setNameValue = (e) => {201 updateRef(e.target.value, nameRef, setName);202 }203 return (204 <div style={{ textAlign: 'center', height: '100vh' }}>205 <div style={{ height: '10%' }}>206 <Typography.Title level={1} style={{transform: 'translateY(50%)', WebkitTransform: 'translateY(50%)'}}>BFTicTacToe</Typography.Title>207 </div>208 {connectionStatus !== 2 ?209 <Row justify='center'>210 <Col span={24}>211 Nome: <Input style={{ width: '200px' }} onChange={setNameValue} value={name} disabled={connectionStatus !== 0}></Input>212 </Col>213 <Col span={24}>214 <Button type='primary' onClick={connect} style={{ margin: '1em' }} icon={<PlayCircleOutlined />} disabled={!name}>Conectar</Button>215 </Col>...
RefrigeratorCard.test.js
Source:RefrigeratorCard.test.js
1import React from "react";2import { render } from "@testing-library/react";3import RefrigeratorCard from "../components/RefrigeratorCard";4import userEvent from "@testing-library/user-event";5import backendAPI from "../Utils/backendAPI";6const REFRIGERATOR_INFO = {7 refrigerator_name: "something",8 id: 2,9};10it("renders successfully", () => {11 const refrigeratorCard = render(12 <RefrigeratorCard refrigerator={REFRIGERATOR_INFO} />13 );14 expect(refrigeratorCard.getByText("Created")).toBeTruthy();15});16it("doesn't show Rename and Delete if user is not owner", () => {17 const refrigerator = { ...REFRIGERATOR_INFO, isOwner: false };18 const refrigeratorCard = render(19 <RefrigeratorCard refrigerator={refrigerator} />20 );21 expect(refrigeratorCard.queryByText("Rename")).toBeNull();22 expect(refrigeratorCard.queryByText("Delete")).toBeNull();23});24it("shows Rename and Delete if user is owner", () => {25 const refrigerator = { ...REFRIGERATOR_INFO, isOwner: true };26 const refrigeratorCard = render(27 <RefrigeratorCard refrigerator={refrigerator} />28 );29 expect(refrigeratorCard.queryByText("Rename")).toBeTruthy();30 expect(refrigeratorCard.queryByText("Delete")).toBeTruthy();31});32it("clicking on Rename should open a rename modal", () => {33 const refrigerator = { ...REFRIGERATOR_INFO, isOwner: true };34 const refrigeratorCard = render(35 <RefrigeratorCard refrigerator={refrigerator} />36 );37 const editButton = refrigeratorCard.queryByText("Rename");38 userEvent.click(editButton);39 expect(refrigeratorCard.queryByText("Edit Refrigerator")).toBeTruthy();40 expect(refrigeratorCard.queryByText("Cancel")).toBeTruthy();41 expect(refrigeratorCard.queryByText("Update")).toBeTruthy();42});43it("clicking cancel on rename modal closes modal", () => {44 const refrigerator = { ...REFRIGERATOR_INFO, isOwner: true };45 const refrigeratorCard = render(46 <RefrigeratorCard refrigerator={refrigerator} />47 );48 const editButton = refrigeratorCard.queryByText("Rename");49 userEvent.click(editButton);50 const cancelButton = refrigeratorCard.queryByText("Cancel");51 userEvent.click(cancelButton);52 expect(refrigeratorCard.queryByText("Edit Refrigerator")).toBeNull();53 expect(refrigeratorCard.queryByText("Cancel")).toBeNull();54 expect(refrigeratorCard.queryByText("Update")).toBeNull();55});56it("clicking on Update on rename modal calls backendAPI", () => {57 const refrigerator = { ...REFRIGERATOR_INFO, isOwner: true };58 backendAPI.updateRefrigerator = jest.fn(() =>59 Promise.resolve([{ ...refrigerator, refrigerator_name: "something2" }])60 );61 const updateRef = jest.fn();62 const refrigeratorCard = render(63 <RefrigeratorCard updateRef={updateRef} refrigerator={refrigerator} />64 );65 const editButton = refrigeratorCard.queryByText("Rename");66 userEvent.click(editButton);67 const updateButton = refrigeratorCard.queryByText("Update");68 userEvent.click(updateButton);69 expect(backendAPI.updateRefrigerator).toHaveBeenCalled();70});71it("clicking on Delete should open delete modal", () => {72 const refrigerator = { ...REFRIGERATOR_INFO, isOwner: true };73 const refrigeratorCard = render(74 <RefrigeratorCard refrigerator={refrigerator} />75 );76 const deleteButton = refrigeratorCard.queryByText("Delete");77 userEvent.click(deleteButton);78 expect(refrigeratorCard.queryByText("Delete Refrigerator")).toBeTruthy();79 expect(80 refrigeratorCard.queryByText(81 `Are you sure you want to delete "${refrigerator.refrigerator_name}"?`82 )83 ).toBeTruthy();84 expect(refrigeratorCard.queryByText("No")).toBeTruthy();85 expect(refrigeratorCard.queryAllByText("DELETE")).toBeTruthy();86});87it("clicking on delete on delete modal calls backendAPI", () => {88 const refrigerator = { ...REFRIGERATOR_INFO, isOwner: true };89 backendAPI.deleteRefrigerator = jest.fn(() =>90 Promise.resolve([{ ...refrigerator, refrigerator_name: "something2" }])91 );92 const updateRef = jest.fn();93 const refrigeratorCard = render(94 <RefrigeratorCard updateRef={updateRef} refrigerator={refrigerator} />95 );96 const deleteButton = refrigeratorCard.queryByTestId("delete-refrigerator");97 userEvent.click(deleteButton);98 const confirmDelete = refrigeratorCard.queryByTestId(99 "confirm-delete-refrigerator"100 );101 userEvent.click(confirmDelete);102 expect(backendAPI.deleteRefrigerator).toHaveBeenCalled();103});104it("confirming delete calls updateRef if statuscode is 200", async () => {105 const refrigerator = { ...REFRIGERATOR_INFO, isOwner: true };106 backendAPI.deleteRefrigerator = jest.fn(() =>107 Promise.resolve({108 statusCode: 200,109 })110 );111 const updateRef = jest.fn();112 const refrigeratorCard = render(113 <RefrigeratorCard updateRef={updateRef} refrigerator={refrigerator} />114 );115 const deleteButton = refrigeratorCard.queryByTestId("delete-refrigerator");116 userEvent.click(deleteButton);117 const confirmDelete = refrigeratorCard.queryByTestId(118 "confirm-delete-refrigerator"119 );120 userEvent.click(confirmDelete);121 expect(backendAPI.deleteRefrigerator).toHaveBeenCalled();122 await new Promise((resolve) => setTimeout(resolve, 100));123 expect(updateRef).toHaveBeenCalled();124});125it("clicking on No on delete modal closes modal", () => {126 const refrigerator = { ...REFRIGERATOR_INFO, isOwner: true };127 const refrigeratorCard = render(128 <RefrigeratorCard refrigerator={refrigerator} />129 );130 const deleteButton = refrigeratorCard.queryByTestId("delete-refrigerator");131 userEvent.click(deleteButton);132 const noButton = refrigeratorCard.queryByText("No");133 userEvent.click(noButton);134 expect(refrigeratorCard.queryByText("Delete Refrigerator")).toBeNull();135 expect(136 refrigeratorCard.queryByText(137 `Are you sure you want to delete "${refrigerator.refrigerator_name}"?`138 )139 ).toBeNull();140 expect(refrigeratorCard.queryByText("No")).toBeNull();141});142it("clicking on refrigerator card calls handleClick prop", () => {143 const refrigerator = { ...REFRIGERATOR_INFO, isOwner: true };144 const handleClick = jest.fn();145 const refrigeratorCard = render(146 <RefrigeratorCard handleClick={handleClick} refrigerator={refrigerator} />147 );148 userEvent.click(refrigeratorCard.queryByText(refrigerator.refrigerator_name));149 expect(handleClick).toHaveBeenCalled();...
AuthContext.js
Source:AuthContext.js
1import React, { useContext, useState, useEffect } from 'react'2import { useHistory } from "react-router-dom";3import firebase from "firebase/app";4import "firebase/auth";5import "firebase/firestore";6import "firebase/storage"7const crypto = require('crypto');8const AuthContext = React.createContext()9export function useAuth() {10 return useContext(AuthContext);11}12export function AuthProvider({ children }) {13 useEffect(() => fetchData(), [])14 const [currentUser, setCurrentUser] = useState();15 const [loading, setLoading] = useState(true);16 const [isDelete, setIsDelete] = useState(false);17 const [isAdd, setIsAdd] = useState(false);18 const [urlLink, setUrlLink] = useState()19 const [detail, setDetail] = useState('')20 const storageRef = firebase.storage().ref()21 const [fileRef, setFileRef] = useState('')22 const jobsRef = firebase.firestore().collection('jobs');23 const [jobs, setJobs] = useState([])24 async function fetchData(path) {25 if (path === "/DashBoard") {26 const snapshot = await jobsRef.where('email', '==', currentUser.email).get();27 const data = []28 snapshot.forEach(doc => {29 var temp = doc.data()30 temp.docId = doc.id31 data.push(temp)32 });33 setJobs(data)34 } else {35 const snapshot = await jobsRef.get()36 const data = []37 snapshot.forEach(doc => {38 var temp = doc.data()39 temp.docId = doc.id40 data.push(temp)41 });42 setJobs(data)43 }44 }45 function AddJob() {46 setIsAdd(!isAdd)47 }48 function jobDetails(docId) {49 jobsRef.doc(docId).get().then((doc) => {50 if (doc.exists) {51 const details = doc.data();52 return details53 } else {54 // doc.data() will be undefined in this case55 console.log("No such document!");56 }57 })58 }59 function logIn(email, password) {60 return firebase.auth().signInWithEmailAndPassword(email, password)61 }62 function signUp(email, password) {63 return firebase.auth().createUserWithEmailAndPassword(email, password);64 }65 function Delete() {66 setIsDelete(!isDelete)67 }68 function logOut() {69 setIsAdd(false)70 return firebase.auth().signOut();71 }72 function resetPassword(email) {73 return firebase.auth().sendPasswordResetEmail(email);74 }75 async function deleteDoc(docId) {76 await jobsRef.doc(docId).delete();77 }78 async function update(value, docId, field) {79 const updateRef = jobsRef.doc(docId);80 console.log(value, docId, field)81 if (field === "overview") {82 await updateRef.update({ overview: value });83 } else if (field === "requirement") {84 await updateRef.update({ requirement: value });85 } else if (field === "experience") {86 await updateRef.update({ experience: value });87 } else if (field === "position") {88 await updateRef.update({ position: value });89 } else if (field === "type") {90 await updateRef.update({ type: value });91 } else if (field === "salary") {92 await updateRef.update({ salary: value });93 } else if (field === "company") {94 await updateRef.update({ company: value });95 } else if (field === "title") {96 await updateRef.update({ title: value });97 } else if (field === "location") {98 await updateRef.update({ location: value });99 } else if (field === "logo") {100 await updateRef.update({ logo: value });101 }102 fetchDoc(docId)103 }104 async function fetchDoc(docId) {105 await jobsRef.doc(docId).get().then((doc) => {106 doc.exists ? setDetail(doc.data()) :107 console.log("No such document!");108 })109 }110 async function addDoc(data) {111 await jobsRef.doc().set(data);112 fetchData()113 setIsAdd(!isAdd)114 }115 function uploadFile(e) {116 const fileHash = crypto.createHash('sha1').update(e.target.value).digest('hex');117 const file = e.target.files[0]118 const fileReference = storageRef.child(currentUser.email + "/" + fileHash)119 fileReference.put(file).then(() => (120 fileReference.getDownloadURL()121 .then((url) => {122 setUrlLink(url)123 setFileRef(fileHash)124 })125 .catch((error) => {126 console.log(error)127 })128 ))129 }130 async function deleteImage(prevURL) {131 console.log(prevURL)132 var desertRef = storageRef.child(currentUser.email + "/" + fileRef);133 // Delete the file134 desertRef.delete().then(() => {135 console.log("Image deleted")136 }).catch((error) => {137 // Uh-oh, an error occurred!138 });139 }140 useEffect(() => {141 const unsubscribe = firebase.auth().onAuthStateChanged(user => {142 setCurrentUser(user);143 setLoading(false);144 })145 return unsubscribe;146 }, [])147 const value = {148 currentUser,149 signUp,150 logIn,151 logOut,152 resetPassword,153 addDoc,154 jobDetails,155 deleteDoc,156 fetchData,157 jobs,158 isDelete,159 Delete,160 isAdd,161 AddJob,162 uploadFile,163 urlLink,164 update,165 detail,166 fetchDoc,167 deleteImage,168 fileRef169 }170 return ( <171 AuthContext.Provider value = { value } > {!loading && children } <172 /AuthContext.Provider>173 )...
UpdateUserDetails.js
Source:UpdateUserDetails.js
1import firebase from "../firebase";2import { SendEmail } from "./SendEmail";3//! Adding new user to firebase db4export async function AddNewUser(newUserData) {5 //register new user with auth6 const newUser = await firebase.register(7 newUserData.firstName,8 newUserData.email,9 newUserData.password10 );11 //add to users collection12 firebase.db.collection("users").doc(newUser).set({13 id: newUser,14 isAdmin: false,15 firstName: newUserData.firstName,16 lastName: newUserData.lastName,17 businessName: newUserData.businessName,18 phone: newUserData.phone,19 username: newUserData.email,20 email: newUserData.email,21 currentStep: 0,22 stepStatus: "started",23 projectStatus: "started",24 });25 //add to websites collection26 firebase.db27 .collection("websites")28 .doc(newUser)29 .set({30 pages: newUserData.pageArr,31 id: newUser,32 client: newUserData.email,33 logo_url: "",34 designQuestions: {35 businessName: newUserData.businessName,36 references: newUserData.references,37 fonts: newUserData.fonts,38 colors: newUserData.colors,39 comments: newUserData.comments,40 },41 });42}43//Add lead to db - if not checked out44export async function AddNewLead(leadDoc) {45 await firebase.db.collection("leads").doc(leadDoc.email).set({46 leadDoc,47 });48}49//update lead in db50export async function UpdateLead(updatedLeadDoc) {51 const docRef = firebase.db.collection("leads").doc(updatedLeadDoc.email);52 const doc = await docRef.get();53 if (!doc.exists) {54 AddNewLead(updatedLeadDoc);55 } else {56 docRef.update({57 updatedLeadDoc,58 });59 }60}61export async function handleAddMockupLink(user, mockupLink) {62 if (!user) return;63 const updateRef = firebase.db.collection("websites").doc(user.id);64 await updateRef.update(65 {66 mockupLink: mockupLink,67 mockupStatus: "pending",68 },69 { merge: true }70 );71 const content = "Your Mockup Link has been added.";72 await SendEmail(content, user.email);73}74export async function handleAddStagingLink(user, stagingLink) {75 if (!user) return;76 const updateRef = firebase.db.collection("websites").doc(user.id);77 await updateRef.update(78 {79 stagingLink: stagingLink,80 stagingStatus: "pending",81 },82 { merge: true }83 );84 const content = "Your Staging Link has been added.";85 console.log(user.email);86 await SendEmail(content, user.email);87}88export async function handleApproveDesignQuestions(user, callback) {89 if (!user) return;90 const updateRef = firebase.db.collection("users").doc(user.id);91 updateRef.update(92 {93 designQuestionStatus: "approved",94 stepStatus: "started",95 currentStep: user.currentStep + 1,96 projectStatus: "Selecting Hosting Package",97 },98 { merge: true }99 );100 await callback();101 const content = "Your Design questions have been approved.";102 await SendEmail(content, user.email);103}104//TODO function for updating design questions105export async function UpdateDesignQuestionsInDB(userId, updatedDoc) {106 const updateRef = firebase.db.collection("websites").doc(userId);107 updateRef.update(108 {109 designQuestions: updatedDoc,110 },111 { merge: true }112 );113}114//TODO function for updating hosting package selection115export async function UpdateHostingPackageInDB(userId, updatedDoc) {116 const updateRef = firebase.db.collection("websites").doc(userId);117 updateRef.update(118 {119 hostingPackage: updatedDoc,120 },121 { merge: true }122 );123}124//TODO function for updating stepstatus125export async function UpdateStepStatusInDB(userId, updatedDoc) {126 const { projectStatus, stepStatus } = updatedDoc;127 const updateRef = firebase.db.collection("users").doc(userId);128 updateRef.update(129 {130 projectStatus: projectStatus,131 stepStatus: stepStatus,132 },133 { merge: true }134 );135}136//TODO function for updating logo137export async function UpdateLogoUrlInDB(userId, updatedDoc) {138 const updateRef = firebase.db.collection("websites").doc(userId);139 updateRef.update(140 {141 logo_url: updatedDoc,142 },143 { merge: true }144 );145}146//TODO function for updating page content ?probably also need page title or something for this147export async function UpdatePageContentInDB(userId, updatedDoc, pageTitle) {148 const updateRef = firebase.db.collection("websites").doc(userId);149 const titleString = pageTitle + "Info";150 updateRef.update(151 {152 [titleString]: updatedDoc,153 },154 { merge: true }155 );...
UpdateUser.js
Source:UpdateUser.js
1import React, { createRef, useEffect } from 'react';2import { Modal, Form, Button, Col } from 'react-bootstrap';3const UpdateUser = props => {4 useEffect(() => {5 console.log('props', props.selectedUser)6 }, [props.selectedUser])7 const updateRef = createRef();8 const onSubmitUpdateUser = e => {9 e.preventDefault();10 e.target.className += " was-validated";11 updateRef.current.email.value = checkEmail(updateRef.current.email.value) ? updateRef.current.email.value : "";12 updateRef.current.pass.value = checkPassword(updateRef.current.pass.value) ? updateRef.current.pass.value : "";13 const updateUser = {14 username: updateRef.current.name.value,15 email: updateRef.current.email.value,16 full_name: updateRef.current.fullName.value,17 password: updateRef.current.pass.value,18 role: updateRef.current.role.value19 }20 updateRef.email && updateRef.password && props.update(props.selectedUser._id, updateUser);21 }22 const checkEmail = (email) => {23 return email && email.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);24 }25 const checkPassword = (pass) => {26 return pass && pass.length > 5;27 }28 return (29 < Modal show={props.show} onHide={props.onHide} >30 <Modal.Header closeButton>31 <Modal.Title>Edit User</Modal.Title>32 </Modal.Header>33 <Form className="needs-validation" noValidate ref={updateRef} onSubmit={onSubmitUpdateUser}>34 <Modal.Body>35 <Form.Row>36 <Col>37 <Form.Group controlId="name">38 <Form.Label>Name</Form.Label>39 <Form.Control name="newName" placeholder="New User Name" required defaultValue={props.selectedUser ? props.selectedUser.username : ""} />40 <div className="invalid-feedback">41 <div className="fieldError"> Invalid value.</div>42 </div>43 </Form.Group>44 <Form.Group controlId="email">45 <Form.Label>Email</Form.Label>46 <Form.Control name="newEmail" placeholder="Email" type="email" required defaultValue={props.selectedUser ? props.selectedUser.email : ""} />47 <div className="invalid-feedback">48 <div className="fieldError"> Invalid value.</div>49 </div>50 </Form.Group>51 <Form.Group controlId="fullName">52 <Form.Label>Full Name</Form.Label>53 <Form.Control name="newFullName" placeholder="Full Name" required defaultValue={props.selectedUser ? props.selectedUser.full_name : ""} />54 <div className="invalid-feedback">55 <div className="fieldError"> Invalid value.</div>56 </div>57 </Form.Group>58 <Form.Group controlId="pass">59 <Form.Label>Password</Form.Label>60 <Form.Control name="newPass" placeholder="Password should be over 6 letters" required defaultValue={props.selectedUser ? props.selectedUser.password : ""} />61 </Form.Group>62 <Form.Group controlId="role">63 <Form.Label>Role</Form.Label>64 <Form.Control as="select" name="newRole" required defaultValue={props.selectedUser ? props.selectedUser.role : "student"}>65 <option value="STUDENT">Student</option>66 <option value="TUTOR">Tutor</option>67 <option value="ADMIN">Admin</option>68 </Form.Control>69 <div className="invalid-feedback">70 <div className="fieldError"> Invalid value.</div>71 </div>72 </Form.Group>73 </Col>74 </Form.Row>75 </Modal.Body>76 <Modal.Footer>77 <Button variant="primary" type="submit">78 Update79 </Button>80 </Modal.Footer>81 </Form>82 </Modal >83 )84}...
useTake.js
Source:useTake.js
1import { useEffect, useRef, useState } from "react";2import { getStore } from "./createManager";3function useTake(name = "master") {4 const store = getStore(name);5 const updateRef = useRef({6 shouldUpdate: true,7 setInit: false,8 subKey: Symbol(),9 });10 const [, setUpdateTrigger] = useState({});11 useEffect(() => {12 updateRef.current.shouldUpdate = true;13 return () => {14 updateRef.current.shouldUpdate = false;15 store._removeListener(updateRef.current.subKey);16 };17 }, []);18 // init19 if (!updateRef.current.setInit) {20 store._addListener(updateRef.current.subKey, setUpdateTrigger);21 updateRef.current.setInitial = true;22 }23 return [store._state, store._dispatcher];24}...
Using AI Code Generation
1const qawolf = require('qawolf');2const browser = await qawolf.launch();3await qawolf.create();4const page = await browser.newPage();5await qawolf.create();6await page.type('[name="q"]', 'qawolf');7await page.click('[name="btnK"]');8await qawolf.create();9await page.click('h3');10await qawolf.create();11await page.click('[aria-label
Using AI Code Generation
1const { updateRef } = require("qawolf");2const { launch, page } = require("qawolf");3it("test", async () => {4 const browser = await launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await updateRef(page, "test");8 await browser.close();9});10const { updateRef } = require("qawolf");11const { launch, page } = require("qawolf");12it("test", async () => {13 const browser = await launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await updateRef(page, "test");17 await browser.close();18});19const { updateRef } = require("qawolf");20const { launch, page } = require("qawolf");21it("test", async () => {22 const browser = await launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await updateRef(page, "test");26 await browser.close();27});28import { updateRef } from "qawolf";29import { launch, page } from "qawolf";30it("test", async () => {31 const browser = await launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 await updateRef(page, "test");35 await browser.close();36});37import { updateRef } from "qawolf";38import { launch, page } from "qawolf";39it("test", async () => {40 const browser = await launch();41 const context = await browser.newContext();42 const page = await context.newPage();43 await updateRef(page, "test");44 await browser.close();45});
Using AI Code Generation
1const { updateRef } = require('qawolf');2updateRef('test.js', 'test2.js');3const { updateRef } = require('qawolf');4updateRef('test2.js', 'test.js');5const { updateRefDir } = require('qawolf');6updateRefDir('test.js', 'testDir');7const { updateRefDir } = require('qawolf');8updateRefDir('test.js', 'testDir', { recursive: true });
Using AI Code Generation
1const { updateRef } = require("qawolf");2updateRef("test", "test");3updateRef("test", "test", "test");4updateRef("test", "test", "test", "test");5import { updateRef } from "qawolf";6updateRef("test", "test");7updateRef("test", "test", "test");8updateRef("test", "test", "test", "test");
Using AI Code Generation
1const qawolf = require("qawolf");2const selector = require("qawolf/selectors");3const { chromium } = require("playwright");4const { updateRef } = require("qawolf");5(async () => {6 const browser = await chromium.launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 await page.click("input[name=\"q\"]");10 await page.fill("input[name=\"q\"]", "Hello World");
Using AI Code Generation
1const { updateRef } = require(“qawolf”);2updateRef(“test”, “test”);3const { updateRef } = require(“qawolf”);4updateRef(“test”, “test”);5const { updateRef } = require(“qawolf”);6updateRef(“test”, “test”);7const { updateRef } = require(“qawolf”);8updateRef(“test”, “test”);9const { updateRef } = require(“qawolf”);10updateRef(“test”, “test”);11const { updateRef } = require(“qawolf”);12updateRef(“test”, “test”);13const { updateRef } = require(“qawolf”);14updateRef(“test”, “test”);15const { updateRef } = require(“qawolf”);16updateRef(“test”, “test”);17const { updateRef } = require(“qawolf”);18updateRef(“test”, “test”);19const { updateRef } = require(“qawolf”);20updateRef(“test”, “test”);21const { updateRef } = require(“qawolf”);22updateRef(“test”, “test”);23const { updateRef } = require(“qawolf”);24updateRef(“test”, “test”);25const { updateRef } = require(“qawolf”);26updateRef(“test”, “test”);27const { updateRef } = require(“qawolf”);28updateRef(“test”, “test”);
Using AI Code Generation
1const { updateRef } = require("qawolf");2updateRef("test_id", "ref_id");3const { updateRef } = require("qawolf");4updateRef("test_id", "ref_id");5const { updateRef } = require("qawolf");6updateRef("test_id", "ref_id");7const { updateRef } = require("qawolf");8updateRef("test_id", "ref_id");9const { updateRef } = require("qawolf");10updateRef("test_id", "ref_id");11const { updateRef } = require("qawolf");12updateRef("test_id", "ref_id");13const { updateRef } = require("qawolf");14updateRef("test_id", "ref_id");15const { updateRef } = require("qawolf");16updateRef("test_id", "ref_id");17const { updateRef } = require("qawolf");18updateRef("test_id", "ref_id");19const { updateRef } = require("qawolf");20updateRef("test_id", "ref_id");21const { updateRef } = require("qawolf");22updateRef("test_id", "ref_id");23const { updateRef } = require("qawolf");24updateRef("test_id", "ref_id");25const { updateRef } = require("qawolf");26updateRef("test_id", "
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!!