Best JavaScript code snippet using testcafe
medicine.js
Source:medicine.js
1const express = require("express");2const router = express.Router();3const Lodash = require("lodash");4const { Medicine, validateMeds } = require("../schemas/medicine");5const { Tag } = require("../schemas/tag");6const { requestLogger } = require("../logger");7const {8 validateMedCheckOut,9 validateMedCheckOutSearchQueries10} = require("../validateRequest.js");11const findTag = async name => {12 try {13 const tag = await Tag.findOne({14 'name' : { $regex: name, $options: "i"}15 });16 return tag;17 }18 catch (error) {19 console.log("Error Finding Tag by name", error);20 }21}22const findTagById = async id => {23 try {24 const tag = await Tag.findById(id);25 return tag;26 }27 catch (error) {28 console.error ("Error Finding Tag by Id", error);29 }30}31router.get('/', async (req, res) => {32 try {33 let page = 0;34 let limit = 10;35 let sort = "name"36 let order = 1;37 let sortObj = {};38 if (req.query.page)39 page = parseInt(req.query.page) - 1;40 if (req.query.limit)41 limit = parseInt(req.query.limit);42 if (req.query.order)43 order = parseInt(req.query.order);44 if (req.query.sort)45 sort = req.query.sort;46 sortObj[sort] = order;47 if(req.query.tag) {48 const tag = await findTag(req.query.tag);49 if (!tag) {50 requestLogger(`[GET] ${req.baseUrl} - 404`);51 return res.status(404).send(JSON.stringify({"message" : "Category not found"}));52 }53 const meds = await Medicine.find(54 {'tag': tag.name},55 null,56 {57 skip: page * limit,58 limit59 }60 ).sort(sortObj);61 requestLogger(`[GET] ${req.baseUrl} - 200`);62 return res.send(meds);63 }64 const meds = await Medicine.find(65 {},66 null,67 {68 skip: page * limit,69 limit70 }71 ).sort(sortObj);72 requestLogger(`[GET] ${req.baseUrl} - 200`);73 res.send(meds);74 }75 catch (error) {76 res.status(500).send(JSON.stringify({"message" : `Error Getting Medicine: ${error}`}));77 }78});79/** add new meds, or update if existed */80router.post('/', async (req, res) => {81 try {82 const { error } = validateMeds(req.body);83 if (error) {84 requestLogger(`[POST] ${req.baseUrl} - 400`);85 return res.status(400).send(JSON.stringify({"message" : `${error.details[0].message}`}));86 }87 const tag = await findTag(req.body.tag);88 if (!tag) {89 requestLogger(`[POST] ${req.baseUrl} - 404`);90 return res.status(404).send(JSON.stringify({"message" : "Category not found"}));91 }92 const med = await Medicine.findOne({93 "productNumber" : (req.body.productNumber).toLowerCase()94 });95 if (med) {96 requestLogger(`[POST] ${req.baseUrl} - 400`);97 return res.status(400).send(JSON.stringify(98 {"message" : `Medicine already exists with product number: ${req.body.productNumber}`}99 ));100 }101 let newMed = new Medicine({102 qty: req.body.qty,103 tag: tag._id,104 name: req.body.name,105 productNumber: (req.body.productNumber).toLowerCase(),106 description: req.body.description,107 price: req.body.price,108 approve: req.body.approve,109 expiry: new Date(req.body.expiry)110 });111 newMed = await newMed.save();112 requestLogger(`[POST] ${req.baseUrl} - 201`);113 res.status(201).send(newMed);114 }115 catch (error) {116 requestLogger(`[POST] ${req.baseUrl} - 500`);117 res.status(500).send(JSON.stringify({"message" : `Error Adding Medicine: ${error}`}));118 }119});120/**121# Search Medicine by Product Number122**/123router.get("/exact-search", async (req, res) => {124 try {125 if (!(req.query.productNumber)) {126 requestLogger(`[GET] ${req.baseUrl}/exact-search - 400`);127 return res.status(400).send(JSON.stringify({"message" : "Bad Request"}));128 }129 const med = await Medicine.findOne({"productNumber": req.query.productNumber});130 if (!med) {131 requestLogger(`[GET] ${req.baseUrl}/exact-search - 400`);132 return res.status(400).send(JSON.stringify({"message" : "Medicine Not Found"}));133 }134 requestLogger(`[GET] ${req.baseUrl}/exact-search - 200`);135 res.status(200).send(med);136 }137 catch (error) {138 requestLogger(`[GET] ${req.baseUrl}/exact-search - 500`);139 res.status(500).send(JSON.stringify({"message" : "Internal Server Error!"}));140 }141});142/**143# get medicine by product number at checkout cashier144**/145router.get("/checkout", async (req, res) => {146 try {147 const { error, message } = validateMedCheckOutSearchQueries(req.query);148 if (error) {149 requestLogger(`[GET] ${req.baseUrl}/checkout - 400`);150 return res.status(400).send(JSON.stringify({"message" : message}));151 }152 Medicine.find({153 $or: [154 {"name" : {$regex: req.query.q, $options: "i"}},155 {"productNumber" : {$regex: req.query.q, $options: "i"}},156 {"description" : {$regex: req.query.q, $options: "i"}}157 ]158 }).lean()159 .then(function (meds) {160 if (!meds)161 throw new Error ("Error Searching Medicines");162 Promise.all(meds.map( async med => {163 const tag = await Tag.findById(med.tag);164 med.category = tag.name;165 med.location = tag.location;166 return med;167 }))168 .then(function (meds) {169 requestLogger(`[GET] ${req.baseUrl}/checkout - 200`);170 return res.status(200).send(meds);171 });172 });173 }174 catch (error) {175 requestLogger(`[GET] ${req.baseUrl}/checkout - 500`);176 res.status(500).send(JSON.stringify({"message" : "Internal Server Error!"}));177 }178});179/**180# Reduct quantity after checkout181**/182router.put("/checkout", async (req, res) => {183 try {184 const { error , message } = validateMedCheckOut(req.body);185 if (error) {186 requestLogger(`[PUT] ${req.baseUrl}/checkout - 400`);187 return res.status(400).send(JSON.stringify({"message" : message}));188 }189 const { tagId, medId, qty } = req.body;190 const med = await Medicine.findById(medId);191 if (!med) {192 requestLogger(`[PUT] ${req.baseUrl}/checkout - 400`);193 return res.status(400).send(JSON.stringify({"message" : "Medicine Not Found!"}));194 }195 if (parseInt(med.qty) < parseInt(qty)) {196 requestLogger(`[PUT] ${req.baseUrl}/checkout - 400`);197 return res.status(400).send(JSON.stringify({"message" : `${med.name} : not enough remainning item(s)!`}));198 }199 const tag = await Tag.findById(tagId);200 if (!tag) {201 requestLogger(`[PUT] ${req.baseUrl}/checkout - 200`);202 return res.status(400).send(JSON.stringify({"message" : "Category Not Found!"}));203 }204 const update = {"qty" : parseInt(med.qty) - parseInt(qty)};205 let updatedMedicine = await Medicine.findByIdAndUpdate(206 medId,207 update,208 { new : true }209 ); 210 requestLogger(`[PUT] ${req.baseUrl}/checkout - 201`);211 res.status(201).send(updatedMedicine);212 }213 catch (error) {214 console.error(error);215 requestLogger(`[PUT] ${req.baseUrl}/checkout - 500`);216 res.status(500).send(JSON.stringify({"message" : "Internal Server Error!"}));217 }218});219/**220# Export Med Data by date and name221**/222router.get("/export", async (req, res) => {223 try {224 let qTag = "";225 let qName = "";226 let meds;227 if (req.query.tag)228 qTag = req.query.tag;229 if (req.query.name)230 qName = req.query.name231 if (req.query.d1 && req.query.d2) {232 meds = Medicine.find({233 "created" : {234 $gte: new Date(req.query.d1),235 $lt: new Date(req.query.d2)236 },237 $and : [238 {"name" : {239 $regex: qName,240 $options: "i"241 }},242 {"tag" : {243 $regex: qTag,244 $options: "i"245 }},246 {"description" : {247 $regex: qName,248 $options: "i"249 }}250 ]251 });252 }253 else {254 meds = Medicine.find({255 $and : [256 {"name" : { $regex : qName, $options: "i" }},257 {"tag" : { $regex : qTag, $options: "i" }},258 {"description" : { $regex : qName, $options: "i" }}259 ]260 });261 }262 meds.lean()263 .then(function (meds) {264 if(!meds)265 throw new Error("Error Searching Meds");266 Promise.all(meds.map( async med => {267 const tag = await Tag.findById(med.tag);268 med.category = tag.name;269 med.location = tag.location;270 return med;271 }))272 .then(function (meds) {273 requestLogger(`[GET] ${req.baseUrl}/export - 200`);274 return res.status(200).send(meds);275 })276 });277 }278 catch (error) {279 console.log(error);280 requestLogger(`[GET] ${req.baseUrl}/export - 500`);281 res.status(500).send(JSON.stringify({"message" : error.toString()}));282 }283});284/** total num of medicines **/285router.get('/count', async (req, res) => {286 try {287 const medCounts = await Medicine.count();288 requestLogger(`[GET] ${req.baseUrl}/count - 200`);289 res.status(200).send(JSON.stringify({"count" : medCounts}));290 }291 catch (error) {292 requestLogger(`[GET] ${req.baseUrl}/count - 500`);293 res.status(500).send(JSON.stringify({"message" : `Error Getting Medicine Counts: ${error}`}));294 }295});296/** get meds by tag name**/297router.get('/by-tag', async (req, res) => {298 try {299 const tag = await findTagById(req.query.tag);300 let searchQuery = ""301 if (!tag) {302 requestLogger(`[GET] ${req.baseUrl} - 404`);303 return res.status(404).send(JSON.stringify({"message" : "Category not found"}));304 }305 if (req.query.q)306 searchQuery = req.query.q;307 Medicine.find({308 "tag" : {$regex: tag._id, $options: "i"},309 $or: searchQuery === "" ? [310 {"name" : {$regex: searchQuery, $options: "i"}}311 ] :312 [313 {"productNumber" : {$regex: searchQuery, $options: "i"}},314 {"name" : {$regex: searchQuery, $options: "i"}},315 {"description" : {$regex: searchQuery, $options: "i"}}316 ]317 }).lean() // to convert the mongoose object to plain js object, and allow mutation318 .then (function (meds) {319 if (!meds)320 throw new Error("Error Searching Meds by Category!");321 Promise.all(meds.map(async med => {322 const tag = await Tag.findById(med.tag);323 med.category = tag.name;324 med.location = tag.location;325 return med;326 }))327 .then (meds => {328 console.log(req.baseUrl, "200");329 requestLogger(`[GET] ${req.baseUrl}/by-tag - 200`);330 return res.status(200).send(meds);331 });332 });333 }334 catch (error) {335 console.error(error);336 requestLogger(`[GET] ${req.baseUrl}/by-tag - 500`);337 res.status(500).send(JSON.stringify({"message" : `Error Getting Medicine by tag: ${error}`}));338 }339});340/** search meds by keyword **/341router.get('/search', async (req, res) => {342 try {343 let meds;344 let searchArea = "name";345 let filter = []346 if (req.query.area)347 searchArea = req.query.area;348 if (searchArea === "name")349 filter.push({"name" : { $regex: req.query.q, $options: "i"}});350 else if (searchArea === "description")351 filter.push({"description" : { $regex: req.query.q, $options: "i"}});352 else if (searchArea === "productNumber")353 filter.push({"productNumber" : { $regex: req.query.q, $options: "i"}});354 else {355 requestLogger(`[GET] ${req.baseUrl} - 400`);356 return res.status(400).send(JSON.stringify({357 "message" : `Invalid Search Field ${req.query.area}`358 }));359 }360 Medicine.find({361 $and: [...filter]362 }).lean() // lean() is to convert mongoose objects to plain javascript objects, the motive is to allow mutation363 .then (function (meds) {364 if (!meds)365 throw new Error("Meds Not Found!");366 // here I used promise.all to resolve the async call for every elements inside meds array367 Promise.all(meds.map(async med => {368 const tag = await Tag.findById(med.tag);369 med.category = tag.name;370 med.location = tag.location;371 return med;372 }))373 .then(meds => {374 requestLogger(`[GET] ${req.baseUrl}/search - 200`);375 return res.status(200).send(meds);376 });377 });378 }379 catch (error) {380 console.log(`Error Searching Mes : ${error}`);381 requestLogger(`[GET] ${req.baseUrl}/search - 500`);382 res.status(500).send(JSON.stringify({"message" : `Error Searching Medicine: ${error}`}));383 }384});385/** get meds by id */386router.get('/:id', async (req, res) => {387 try {388 const med = await Medicine.findById (req.params.id).lean();389 // console.log('expiry', med)390 if (!med) {391 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 404`);392 return res.status(404).send(JSON.stringify({"message" : "Med(s) not found"}));393 }394 const tag = await findTagById(med.tag);395 if (!tag) {396 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 400`);397 return res.status(400).send(JSON.stringify({"message" : "Invalid Category!"}));398 }399 const data = Object.assign(med, {category: tag.name, location: tag.location});400 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 200`);401 res.send(data);402 }403 catch (error) {404 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 500`);405 res.status(500).send(JSON.stringify({"message" : `Error Getting Medicine by Id: ${error}`}));406 }407});408/** edit medicine */409router.put('/:id', async (req, res) => {410 try {411 const tag = await findTagById(req.body.tag);412 if (!tag) {413 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 404`);414 return res.status(404).send(JSON.stringify({"message" : "Category not found"}));415 }416 // const filter = { id: req.params.id };417 const update = Object.assign(req.body, { updated : new Date() });418 let updatedMedicine = await Medicine.findByIdAndUpdate(419 req.params.id,420 update,421 { new: true }422 ).lean();423 if (!updatedMedicine) {424 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 404`);425 return res.status(404).send(JSON.stringify({"message" : "Med not found"}));426 }427 updatedMedicine = Object.assign(updatedMedicine, {category: tag.name, location: tag.location})428 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 201`);429 res.status(201).send(updatedMedicine);430 }431 catch (error) {432 console.error(error);433 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 500`);434 res.status(500).send(JSON.stringify({"message" : `Error Editting Medicine: ${error}`}));435 }436});437/** delete medicine **/438router.delete('/:id', async (req, res) => {439 try {440 // console.log("Searching Meds")441 const deletedMed = await Medicine.findByIdAndRemove(req.params.id);442 if (!deletedMed) {443 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 404`);444 return rs.status(404).send(JSON.stringify({"message" : "Med not found"}));445 }446 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 200`);447 res.send(deletedMed);448 }449 catch (error) {450 // process.stderr.write('{"status" : "error", "message" : "error deleting medicine"}');451 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 500`);452 res.status(500).send(JSON.stringify({"message" : `Error Deletion Medicine: ${error}`}));453 }454});...
booking.js
Source:booking.js
1const express = require('express');2const router = express.Router();3const mongoose = require('mongoose');4const { Doctor } = require('../schemas/doctor');5const { Employee } = require('../schemas/employee');6const { Booking, validateBookingEntry } = require('../schemas/booking');7const { BookingTimeSlot } = require('../schemas/bookingTimeSlot');8const { requestLogger } = require('../logger');9const validateObjectId = require('../middlewares/validateObjectId');10const { generateId, asyncFilter } = require('../utils');11// get all bookings12router.get('/', async (req, res) => {13 try {14 let limit = 10;15 let page = 0;16 let order = 1;17 let sort = 'dateTime';18 let sortObj = {};19 if (req.query.limit && parseInt(req.query.limit) > 0)20 limit = parseInt(req.query.limit);21 if (req.query.page && parseInt(req.query.page) > 0)22 page = parseInt(req.query.page) - 1;23 if (req.query.order && (req.query.order === '-1' || req.query.order === '1'))24 order = parseInt(req.query.order);25 if (req.query.sort && req.query.sort !== '')26 sort = req.query.sort;27 sortObj[sort] = order;28 let filters = [ { 'doctorName' : { $regex : '', $options: 'i' }} ];29 if (req.query.q && req.query.q !== '') {30 filters = [31 { 'doctorName' : { $regex : req.query.q, $options: 'i' }},32 { 'patientName' : { $regex: req.query.q, $options: 'i' }},33 { 'patientContact' : { $regex: req.query.q, $options: 'i' }}34 ]35 }36 const bookings = await Booking.find(37 {38 $or: [39 ...filters40 ]41 },42 null,43 {44 skip: page * limit,45 limit46 }47 ).sort(sortObj);48 requestLogger(`[GET] ${req.baseUrl} - 200`);49 res.status(200).send(bookings);50 }51 catch (error) {52 console.error(error.message);53 requestLogger(`[GET] ${req.baseUrl} - 500`);54 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));55 }56});57// create new booking58router.post('/', async (req, res) => {59 try {60 if (!req.body.timeSlot)61 req.body = {62 ...req.body,63 timeSlot: req.body.dateTime64 }65 const { error } = validateBookingEntry(req.body);66 if (error) {67 requestLogger(`[POST] ${req.baseUrl} - 400`);68 return res.status(400).send(JSON.stringify({'message' : error.details[0].message}))69 }70 // validate receptionist71 if (!mongoose.Types.ObjectId.isValid(req.body.receptionistId)) {72 requestLogger(`[POST] ${req.baseUrl} - 400`);73 return res.status(400).send(JSON.stringify({'message' : 'Invalid Employee Id'}));74 }75 const employee = await Employee.findById(req.body.receptionistId);76 if (!employee) {77 requestLogger(`[POST] ${req.baseUrl} - 400`);78 return res.status(400).send(JSON.stringify({'message' : 'Employee Not Found!'}));79 }80 // validate doctor81 if (!mongoose.Types.ObjectId.isValid(req.body.doctorId)) {82 requestLogger(`[POST] ${req.baseUrl} - 400`);83 return res.status(400).send(JSON.stringify({'message' : 'Invalid Doctor Id'}));84 }85 const doctor = await Doctor.findById(req.body.doctorId);86 if (!doctor) {87 requestLogger(`[POST] ${req.baseUrl} - 400`);88 return res.status(400).send(JSON.stringify({'message' : 'Doctor Not Found!'}));89 }90 const existingBookings = await Booking.find(91 { 'timeSlot' : { $regex : req.body.timeSlot, $options: 'i' }}92 );93 const bookingId = existingBookings.length + 1;94 let booking = new Booking({95 bookingId,96 receptionistName: employee.fullName,97 receptionistId: employee._id,98 doctorName: doctor.name,99 doctorId: doctor._id,100 patientName: req.body.patientName,101 patientContact: req.body.patientContact,102 dateTime: new Date(req.body.dateTime),103 timeSlot: req.body.timeSlot,104 remark: req.body.remark ? req.body.remark : ''105 });106 booking = await booking.save();107 requestLogger(`[POST] ${req.baseUrl} - 201`);108 return res.status(201).send(booking);109 }110 catch (error) {111 console.error(error);112 requestLogger(`[GET] ${req.baseUrl} - 500`);113 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));114 }115});116// search booking by doctor117router.get('/search', async (req, res) => {118 try {119 let filters = [];120 let bookings = [];121 if (req.query.doctor && req.query.doctor !== '' && mongoose.Types.ObjectId.isValid(req.query.doctor))122 filters.push({'doctorId' : { $regex: req.query.doctor, $options: 'i'} });123 if (filters.length !== 0) {124 bookings = await Booking.find({125 $and : [ ...filters ]126 });127 }128 requestLogger(`[GET] ${req.baseUrl}/search - 200`);129 res.status(200).send(bookings);130 }131 catch (error) {132 requestLogger(`[GET] ${req.baseUrl}/search - 500`);133 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));134 }135});136// get total number of bookings137router.get('/count', async (req, res) => {138 try {139 const count = await Booking.count();140 requestLogger(`[GET] ${req.baseUrl}/count - 200`);141 res.status(200).send(JSON.stringify({'count' : count}));142 }143 catch (error) {144 console.error(error);145 requestLogger(`[GET] ${req.baseUrl}/count - 500`);146 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));147 }148});149// get bookings by dateTime slot150router.get('/datetime', async(req, res) => {151 try {152 if (!req.query.doctor || req.query.doctor === '') {153 requestLogger (`[GET] ${req.baseUrl}/datetime - 400`);154 return res.status(400).send(JSON.stringify({'message' : 'Doctor Id is Required*'}));155 }156 if (!req.query.dateTime || req.query.dateTime === '') {157 requestLogger (`[GET] ${req.baseUrl}/datetime - 400`);158 return res.status(400).send(JSON.stringify({'message' : 'Booking Date & Time is Required*'}));159 }160 if (!mongoose.Types.ObjectId.isValid(req.query.doctor)) {161 requestLogger (`[GET] ${req.baseUrl}/datetime - 400`);162 return res.status(400).send(JSON.stringify({'message' : 'Invalid Doctor Id!'}));163 }164 const bookings = await Booking.find({165 $and: [166 {'doctorId' : { $regex: req.query.doctor, $options : 'i' }},167 {'dateTime' : { $lte: req.query.dateTime, $gte: req.query.dateTime }}168 ]169 });170 requestLogger (`[GET] ${req.baseUrl}/datetime - 200`);171 return res.status(200).send(bookings);172 }173 catch (error) {174 console.error(error);175 requestLogger(`[GET] ${req.baseUrl}/datetime - 500`);176 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));177 }178});179// // get bookings by date180// router.get('/available-slots', async (req, res) => {181// try {182// if (!req.query.date || req.query.date === '') {183// requestLogger(`[GET] ${req.baseUrl}/available-slots - 400`);184// return res.status(400).send(JSON.stringify({'message' : 'Empty Date!'}));185// }186//187// let date1 = new Date(req.query.date);188//189// if (!(date1 instanceof Date)) {190// requestLogger(`[GET] ${req.baseUrl}/available-slots - 400`);191// return res.status(400).send(JSON.stringify({'message' : 'Invalid Date!'}));192// }193//194// let date2 = new Date(req.query.date);195// date1.setDate(date1.getDate() + 1);196//197//198//199// BookingTimeSlot.find().lean()200// .then( async function (slots) {201// if (!slots)202// throw new Error('Error Fetching Time Slots');203//204// const availableSlots = await asyncFilter(slots, async (slot) => {205//206// const booking = await Booking.findOne({207// 'bookingDate' : {208// $gte: date2,209// $lt: date1210// },211// 'timeSlot' : slot._id212// });213//214// return booking === null;215// });216//217// requestLogger(`[GET] ${req.baseUrl}/available-slots - 200`);218// return res.status(200).send(availableSlots);219// });220// }221// catch (error) {222// console.error(error);223// requestLogger(`[GET] ${req.baseUrl}/by-date - 500`);224// res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));225// }226// });227//228//229// // get all booking time slots230// router.get('/all-slots', async (req, res) => {231// try {232// const slots = await BookingTimeSlot.find();233//234// res.status(200).send(slots);235// }236// catch (error) {237// requestLogger(`[GET] ${req.baseUrl}/all-slots - 500`);238// res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));239// }240// });241//242//243// // get available timeslots for the given date244// router.get('/by-date', async (req, res) => {245// try {246// if (!req.query.date || req.query.date === '') {247// requestLogger(`[GET] ${req.baseUrl}/available-slots - 400`);248// return res.status(400).send(JSON.stringify({'message' : 'Empty Date!'}));249// }250//251// let date1 = new Date(req.query.date);252//253// if (!(date1 instanceof Date)) {254// requestLogger(`[GET] ${req.baseUrl}/available-slots - 400`);255// return res.status(400).send(JSON.stringify({'message' : 'Invalid Date!'}));256// }257//258// let date2 = new Date(req.query.date);259// date1.setDate(date1.getDate() + 1);260// // console.log(date1, date2);261// const bookings = await Booking.find({262// 'bookingDate' : {263// $gte: date2,264// $lt: date1265// }266// });267//268// requestLogger(`[GET] ${req.baseUrl}/by-date - 200`);269// res.status(200).send(bookings);270// }271// catch (error) {272// console.error(error);273// requestLogger(`[GET] ${req.baseUrl}/available-slots - 500`);274// res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));275// }276// });277// get booking by id278router.get('/:id', validateObjectId, async (req, res) => {279 try {280 const booking = await Booking.findById(req.params.id);281 if (!booking) {282 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 404`);283 return res.status(404).send(JSON.stringify({'message' : 'Booking Not Found!'}));284 }285 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 200`);286 return res.status(200).send(booking);287 }288 catch (error) {289 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 500`);290 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));291 }292});293// edit/update booking by id294router.put('/:id', validateObjectId, async (req, res) => {295 try {296 const booking = await Booking.findByIdAndUpdate(297 req.params.id,298 { ...req.body, updated: new Date()},299 { new: true}300 );301 if (!booking) {302 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 400`);303 return res.status(400).send(JSON.stringify({'message' : 'Booking Update Failed'}));304 }305 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 201`);306 return res.status(201).send(booking);307 }308 catch (error) {309 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 500`);310 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));311 }312});313// delete booking by id314router.delete('/:id', validateObjectId, async (req, res) => {315 try {316 const booking = await Booking.findByIdAndRemove(req.params.id);317 if (!booking) {318 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 400`);319 return res.status(400).send(JSON.stringify({'message' : 'Deletion Failed'}));320 }321 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 201`);322 return res.status(201).send('');323 }324 catch (error) {325 console.error(error);326 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 500`);327 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));328 }329});...
doctor.js
Source:doctor.js
1/**2 # API Endpoints for doctors3 **/4const express = require('express');5const router = express.Router();6const mongoose = require('mongoose');7const Lodash = require('lodash');8const {9 Doctor,10 validateDoctorEntry,11 validateWorkingSchedule,12 validateCheckScheduleRequest13} = require('../schemas/doctor.js');14const { requestLogger } = require('../logger');15const { validateScheduleTiming } = require('../validateRequest');16const { isValidTime, generateId, to24HourFormat } = require('../utils');17const validateObjectId = require('../middlewares/validateObjectId');18// get all dcotors19router.get ('/', async (req, res) => {20 try {21 let limit = 10;22 let page = 0;23 let sort = 'name';24 let order = -1;25 let sortObj = {};26 if (req.query.page && parseInt(req.query.page) > 0)27 page = parseInt(req.query.page) - 1;28 if (req.query.limit && parseInt(req.query.limit) > 0)29 limit = parseInt (req.query.limit);30 if (req.query.sort && req.query.sort !== '')31 sort = req.query.sort;32 if (req.query.order && (req.query.order === '-1' || req.query.order === '1'))33 order = parseInt(req.query.order);34 sortObj[sort] = order;35 const doctors = await Doctor.find(36 {},37 null,38 {39 skip: limit * page,40 limit41 }42 ).sort(sortObj);43 requestLogger(`[GET] ${req.baseUrl} - 200`);44 res.status(200).send(doctors);45 }46 catch (error) {47 requestLogger(`[GET] ${req.baseUrl} - 500`);48 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));49 }50});51// create new doctor52router.post ('/', async (req, res) => {53 try {54 const { error } = validateDoctorEntry (req.body);55 if (error) {56 requestLogger(`[POST] ${req.baseUrl} - 400`);57 return res.status(200).send(JSON.stringify({'message' : error.details[0].message }));58 }59 req.body.workingSchedule.forEach( ws => {60 if (!(isValidTime(ws.startTime))) {61 requestLogger(`[POST] ${req.baseUrl} - 400`);62 return res.status(200).send(JSON.stringify({'message' : 'Field, startTime, is not a valid date-time value' }));63 }64 if (!(isValidTime(ws.endTime))) {65 requestLogger(`[POST] ${req.baseUrl} - 400`);66 return res.status(200).send(JSON.stringify({'message' : 'Field, endTime, is not a valid date-time value' }));67 }68 });69 let doctor = new Doctor({70 doctorId: generateId('doc'),71 name: req.body.name,72 specialization: req.body.specialization,73 workingSchedule: req.body.workingSchedule74 });75 doctor = await doctor.save();76 requestLogger(`[POST] ${req.baseUrl} - 201`)77 return res.status(201).send(doctor);78 }79 catch (error) {80 console.error(error.message);81 requestLogger(`[GET] ${req.baseUrl} - 500`);82 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));83 }84});85// add working schedule86router.put ('/add-schedule', async (req, res) => {87 try {88 const { error } = validateWorkingSchedule (req.body);89 if (error) {90 requestLogger(`[POST] ${req.baseUrl}/add-schedule - 400`);91 return res.status(200).send(JSON.stringify({'message' : error.details[0].message }));92 }93 if (!mongoose.Types.ObjectId.isValid(req.body.doctorId)) {94 requestLogger (`[PUT] ${req.baseUrl}/add-schedule - 400`);95 return res.status(400).send(JSON.stringify({'message' : 'Invalid Doctor Id!'}));96 }97 let doctor = await Doctor.findById(req.body.doctorId);98 if (!doctor) {99 requestLogger (`[PUT] ${req.baseUrl}/add-schedule - 400`);100 return res.status(400).send(JSON.stringify({'message' : 'Doctor Not Found!'}));101 }102 if (!(isValidTime(req.body.startTime))) {103 requestLogger(`[PUT] ${req.baseUrl}/add-schedule - 400`);104 return res.status(400).send(JSON.stringify({'message' : 'Field, startTime, is not a valid date-time value' }));105 }106 if (!(isValidTime(req.body.endTime))) {107 requestLogger(`[PUT] ${req.baseUrl}/add-schedule - 400`);108 return res.status(400).send(JSON.stringify({'message' : 'Field, endTime, is not a valid date-time value' }));109 }110 const { error: timingError, message } = validateScheduleTiming(doctor.workingSchedule, req.body);111 if (timingError) {112 requestLogger(`[PUT] ${req.baseUrl}/add-schedule - 400`);113 return res.status(400).send(JSON.stringify({'message' : message }));114 }115 const workingSchedule = [116 ...doctor.workingSchedule,117 {118 startTime: req.body.startTime,119 endTime: req.body.endTime,120 day: req.body.day121 }122 ];123 doctor = await Doctor.findByIdAndUpdate(124 req.body.doctorId,125 { workingSchedule, updatedAt: Date.now() },126 { new : true }127 );128 requestLogger(`[PUT] ${req.baseUrl}/add-schedule - 201`);129 return res.status(201).send(doctor);130 }131 catch (error) {132 console.error(error.message);133 requestLogger(`[PUT] ${req.baseUrl}/add-schedule - 500`);134 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));135 }136});137// remove working schedule138router.put ('/remove-schedule', async (req, res) => {139 try {140 const { error } = validateWorkingSchedule (req.body);141 if (error) {142 requestLogger(`[POST] ${req.baseUrl}/add-schedule - 400`);143 return res.status(200).send(JSON.stringify({'message' : error.details[0].message }));144 }145 if (!mongoose.Types.ObjectId.isValid(req.body.doctorId)) {146 requestLogger (`[PUT] ${req.baseUrl}/add-schedule - 400`);147 return res.status(400).send(JSON.stringify({'message' : 'Invalid Doctor Id!'}));148 }149 let doctor = await Doctor.findById(req.body.doctorId);150 if (!doctor) {151 requestLogger (`[PUT] ${req.baseUrl}/add-schedule - 400`);152 return res.status(400).send(JSON.stringify({'message' : 'Doctor Not Found!'}));153 }154 const scheduleToRemove = {155 startTime: req.body.startTime,156 endTime: req.body.endTime,157 day: req.body.day158 }159 const workingSchedule = doctor.workingSchedule.filter(ws => !(Lodash.isEqual(ws, scheduleToRemove)));160 doctor = await Doctor.findByIdAndUpdate(161 req.body.doctorId,162 { workingSchedule, updatedAt : Date.now() },163 { new : true }164 );165 requestLogger(`[PUT] ${req.baseUrl}/remove-schedule - 201`);166 return res.status(201).send(doctor);167 }168 catch (error) {169 console.error(error.message);170 requestLogger(`[PUT] ${req.baseUrl}/remove-schedule - 500`);171 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));172 }173});174// check whether the given datetime is fall inside doctor schedule175router.get('/check-schedule', async (req, res) => {176 try {177 const requestQueries = {178 doctorId: req.query.doctor,179 time: req.query.time,180 day: req.query.day181 }182 const { error } = validateCheckScheduleRequest(requestQueries);183 if (error) {184 requestLogger(`[GET] ${req.baseUrl}/check-schedule - 400`);185 return res.status(400).send(JSON.stringify({'message' : error.details[0].message}));186 }187 if (!mongoose.Types.ObjectId.isValid(requestQueries.doctorId)) {188 requestLogger(`[GET] ${req.baseUrl}/check-schedule - 400`);189 return res.status(400).send(JSON.stringify({'message' : 'Invalid Doctor ID!'}));190 }191 const doctor = await Doctor.findById(requestQueries.doctorId);192 if (!doctor) {193 requestLogger(`[GET] ${req.baseUrl}/check-schedule - 400`);194 return res.status(400).send(JSON.stringify({'message' : 'Doctor Not Found!'}));195 }196 const workingSchedule = doctor.workingSchedule;197 const bookingTime = parseInt((requestQueries.time).split(':')[0]);198 let isRegular = false;199 workingSchedule.some( ws => {200 const startHour = to24HourFormat(ws.startTime);201 const endHour = to24HourFormat(ws.endTime);202 if (ws.day === parseInt(requestQueries.day) && bookingTime >= startHour && bookingTime <= endHour) {203 isRegular = true;204 return true;205 }206 });207 return res.status(200).send(JSON.stringify({'doctor' : doctor.name,'isRegular' : isRegular}));208 }209 catch (error) {210 console.error(error);211 requestLogger(`[GET] ${req.baseUrl}/check-schedule - 500`);212 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));213 }214});215// get doctor count216router.get ('/count', async (req, res) => {217 try {218 const count = await Doctor.count();219 requestLogger(`[GET] ${req.baseUrl}/count - 200`);220 res.status(200).send(JSON.stringify({'count' : count }));221 }222 catch (error) {223 console.error(error.message);224 requestLogger(`[GET] ${req.baseUrl}/count - 500`);225 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));226 }227});228// search doctor by name229router.get ('/search', async (req, res) => {230 try {231 let doctors = [];232 if (req.query.q && req.query.q !== '') {233 doctors = await Doctor.find(234 { 'name' : { $regex : req.query.q, $options: 'i' }}235 );236 }237 requestLogger(`[GET] ${req.baseUrl}/search - 200`);238 res.status(200).send(doctors);239 }240 catch (error) {241 console.error(error.message);242 requestLogger(`[GET] ${req.baseUrl}/search - 500`);243 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));244 }245});246// get doctor by id247router.get('/:id', validateObjectId, async (req, res) => {248 try {249 const doctor = await Doctor.findById(req.params.id);250 if (!doctor) {251 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 404`);252 return res.status(404).send(JSON.stringify({'message' : 'Doctor Not Found!'}));253 }254 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 200`);255 return res.status(200).send(doctor);256 }257 catch (error) {258 console.error(error.message);259 requestLogger(`[GET] ${req.baseUrl}/${req.parmas.id} - 500`);260 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));261 }262});263// update doctor by id264router.put ('/:id', validateObjectId, async (req, res) => {265 try {266 const update = Object.assign(req.body, { updated : new Date() });267 const doctor = await Doctor.findByIdAndUpdate(268 req.params.id,269 update,270 { new : true }271 );272 if (!doctor) {273 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 400`);274 return res.status(400).send(JSON.stringify({'message' : 'Doctor Upate Failed!'}));275 }276 requestLogger(`[PUT] ${req.baseUrl} - 201`)277 return res.status(201).send(doctor);278 }279 catch (error) {280 console.error(error.message);281 requestLogger(`[PUT] ${req.baseUrl}/${req.parmas.id} - 500`);282 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));283 }284});285// delete doctor by id286router.delete ('/:id', validateObjectId, async (req, res) => {287 try {288 const doctor = await Doctor.findByIdAndRemove(req.params.id);289 if (!doctor) {290 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 400`);291 return res.status(400).send(JSON.stringify({'message' : 'Doctor Deletion Failed!'}));292 }293 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 204`);294 return res.status(204).send('');295 }296 catch (error) {297 console.error(error.message);298 requestLogger(`[DELETE] ${req.baseUrl}/${req.parmas.id} - 500`);299 res.status(500).send(JSON.stringify({'message' : 'Internal Server Error!'}));300 }301});...
wrapper-request-callback.test.js
Source:wrapper-request-callback.test.js
1'use strict'2// const request = require('request')3const { expect } = require('chai')4const sinon = require('sinon')5const proxyquire = require('proxyquire')6const requestLogger = {}7const events = require('events')8const util = require('util')9const wrapper = proxyquire('../../../../app/services/clients/base-client/wrapper', {10 '../../../utils/request-logger': requestLogger11})12describe('wrapper: request scenarios', () => {13 describe('when the request returns successfully with statusCode 200', () => {14 let cb15 let resolved16 let returnee17 // Create a stubbed request object18 function RequestStub () {19 const self = this20 events.EventEmitter.call(self)21 return function (options, callback) {22 setTimeout(() => {23 // Emit a response that our test is checking for24 self.emit('response', { statusCode: 200 })25 // And execute the callback26 callback(null, { statusCode: 200, request: options, body: 'success' }, 'success')27 }, 100)28 return self29 }30 }31 // Wire the EventEmitter into it, so we can emit the event specified above to any watchers32 util.inherits(RequestStub, events.EventEmitter)33 before(done => {34 requestLogger.logRequestStart = sinon.spy()35 requestLogger.logRequestEnd = sinon.spy()36 requestLogger.logRequestFailure = sinon.spy()37 requestLogger.logRequestError = sinon.spy()38 cb = sinon.spy()39 returnee = wrapper(new RequestStub(), 'get')('http://example.com/', cb)40 returnee41 .then(result => {42 resolved = result43 done()44 })45 .catch(done)46 })47 it('should return a promise', () => {48 expect(returnee.constructor).to.equal(Promise)49 })50 it('should return a promise that is resolved with the body of the successful request', () => {51 expect(resolved).to.equal('success')52 })53 it('should call a supplied callback function', () => {54 expect(cb.lastCall.args[0]).to.equal(null)55 expect(cb.lastCall.args[1]).to.have.property('statusCode').to.equal(200)56 expect(cb.lastCall.args[1]).to.have.property('body').to.equal('success')57 expect(cb.lastCall.args[2]).to.equal('success')58 expect(cb.called).to.equal(true)59 })60 it('should log the request start and request end but not a request failure or error', () => {61 expect(requestLogger.logRequestStart.called).to.equal(true)62 expect(requestLogger.logRequestEnd.called).to.equal(true)63 expect(requestLogger.logRequestError.called).to.equal(false)64 expect(requestLogger.logRequestFailure.called).to.equal(false)65 })66 })67 describe('when the request fails', () => {68 let cb69 let rejected70 let returnee71 // Create a stubbed request object72 function RequestStub () {73 const self = this74 events.EventEmitter.call(self)75 return function (options, callback) {76 setTimeout(() => {77 // Emit a response that our test is checking for78 self.emit('response', { statusCode: 404 })79 // And execute the callback80 callback(null, { statusCode: 404, request: options, body: 'not found' }, 'not found')81 }, 100)82 return self83 }84 }85 // Wire the EventEmitter into it, so we can emit the event specified above to any watchers86 util.inherits(RequestStub, events.EventEmitter)87 before(done => {88 requestLogger.logRequestStart = sinon.spy()89 requestLogger.logRequestEnd = sinon.spy()90 requestLogger.logRequestFailure = sinon.spy()91 requestLogger.logRequestError = sinon.spy()92 cb = sinon.spy()93 returnee = wrapper(new RequestStub(), 'get')('http://example.com/', cb)94 returnee95 .then(done)96 .catch(err => {97 rejected = err98 done()99 })100 })101 it('should return a promise', () => {102 expect(returnee.constructor).to.equal(Promise)103 })104 it('should return a promise that is rejected with an error with a message equal to the response body and an \'errorCode\' property equal to the response code', () => {105 expect(rejected.constructor).to.equal(Error)106 expect(rejected.message).to.equal('not found')107 expect(rejected.errorCode).to.equal(404)108 })109 it('should call a supplied callback function with the results of the request', () => {110 expect(cb.lastCall.args[0]).to.equal(null)111 expect(cb.lastCall.args[1]).to.have.property('statusCode').to.equal(404)112 expect(cb.lastCall.args[1]).to.have.property('body').to.equal('not found')113 expect(cb.lastCall.args[2]).to.equal('not found')114 })115 it('should log the request start, end and failure but not a request error', () => {116 expect(requestLogger.logRequestStart.called).to.equal(true)117 expect(requestLogger.logRequestEnd.called).to.equal(true)118 expect(requestLogger.logRequestError.called).to.equal(false)119 expect(requestLogger.logRequestFailure.called).to.equal(true)120 })121 })122 describe('when the request errors', () => {123 let cb124 let rejected125 let returnee126 // Create a stubbed request object127 function RequestStub () {128 const self = this129 events.EventEmitter.call(self)130 return function (options, callback) {131 setTimeout(() => {132 // Emit a response that our test is checking for133 self.emit('error', new Error('something simply dreadful happened'))134 // And execute the callback135 callback(new Error('something simply dreadful happened'))136 }, 100)137 return self138 }139 }140 // Wire the EventEmitter into it, so we can emit the event specified above to any watchers141 util.inherits(RequestStub, events.EventEmitter)142 before(done => {143 requestLogger.logRequestStart = sinon.spy()144 requestLogger.logRequestEnd = sinon.spy()145 requestLogger.logRequestFailure = sinon.spy()146 requestLogger.logRequestError = sinon.spy()147 cb = sinon.spy()148 returnee = wrapper(new RequestStub(), 'get')('http://example.com/', cb)149 returnee150 .then(done)151 .catch(err => {152 rejected = err153 done()154 })155 })156 it('should return a promise', () => {157 expect(returnee.constructor).to.equal(Promise)158 })159 it('should return a promise that is rejected with the error that the request module returned', () => {160 expect(rejected.constructor).to.equal(Error)161 expect(rejected.message).to.equal('something simply dreadful happened')162 expect(rejected.errorCode).to.equal(undefined)163 })164 it('should call a supplied callback function with the results of the request', () => {165 expect(cb.lastCall.args[0]).to.equal(rejected)166 expect(cb.lastCall.args[1]).to.equal(undefined)167 expect(cb.lastCall.args[2]).to.equal(undefined)168 })169 it('should log the request start, end and error but not a request failure', () => {170 expect(requestLogger.logRequestStart.called).to.equal(true)171 expect(requestLogger.logRequestEnd.called).to.equal(true)172 expect(requestLogger.logRequestError.called).to.equal(true)173 expect(requestLogger.logRequestFailure.called).to.equal(false)174 })175 })...
employee.js
Source:employee.js
1const express = require("express");2const router = express.Router();3const mongoose = require("mongoose");4const Lodash = require("lodash");5const validateObjectId = require('../middlewares/validateObjectId');6const {7 Employee,8 validateEmployee,9 validateEmployeeEditRequest,10 validateLogin11} = require("../schemas/employee");12const { requestLogger } = require("../logger");13/** Get all employee **/14router.get("/", async (req, res) => {15 try {16 let page = 0;17 let limit = 10;18 if (req.query.page)19 page = parseInt(req.query.page) - 1;20 if (req.query.limit)21 limit = parseInt(req.query.limit);22 const employees = await Employee.find(23 null,24 null,25 { page: limit * page, limit }26 ).sort({username: 1});27 let emps = employees.map( e => e=Lodash.pick(e, ["_id", "username", "fullName", "mobile", "level"]));28 requestLogger(`[GET] ${req.baseUrl} - 200`);29 res.status(200).send(emps);30 }31 catch (error) {32 requestLogger(`[GET] ${req.baseUrl} - 500`);33 res.status(500).send(`Error getting employees: ${error}`);34 }35});36/** create new employee **/37router.post("/", async (req, res) => {38 try {39 const { error } = validateEmployee(req.body);40 if (error) {41 requestLogger(`[POST] ${req.baseUrl} - 400`);42 return res.status(400).send(JSON.stringify({"message": error.details[0].message}));43 }44 const existingEmp = await Employee.findOne({"username" : req.body.username});45 if (existingEmp) {46 requestLogger(`[POST] ${req.baseUrl} - 400`);47 return res.status(400).send(JSON.stringify({"message" : "User Already Exists!"}));48 }49 let emp = new Employee({50 username: req.body.username,51 level: req.body.level,52 fullName: req.body.fullName,53 mobile: req.body.mobile,54 password: req.body.password55 });56 emp = await emp.save();57 requestLogger(`[POST] ${req.baseUrl} - 201`);58 res.status(201).send(Lodash.pick(emp, ["username", "fullName", "level", "mobile", "_id"]));59 }60 catch (error) {61 requestLogger(`[POST] ${req.baseUrl} - 500`);62 res.status(500).send(JSON.stringify({"message" : `Error Creating New Employee: ${error}`}));63 }64});65router.post("/login", async (req, res) => {66 try {67 const { username, password } = req.body;68 const emp = await Employee.findOne({"username" : username});69 if (!emp) {70 requestLogger(`[POST] ${req.baseUrl}/login - 400`);71 return res.status(400).send(JSON.stringify({"message" : "invalid username/password"}));72 }73 validateLogin(username, password, function(result) {74 const { status, message, emp } = result;75 if (status === 404) {76 requestLogger(`[POST] ${req.baseUrl}/login - 404`);77 return res.status(404).send(JSON.stringify({"message" : message}));78 }79 if (status === 401) {80 requestLogger(`[POST] ${req.baseUrl}/login - 401`);81 return res.status(401).send(JSON.stringify({"message" : message}));82 }83 let empData = Lodash.pick(emp, ["_id", "username", "mobile", "level", "fullName"]);84 requestLogger(`[POST] ${req.baseUrl}/login - 200`);85 res.status(200).send(empData);86 });87 // const loginResult = await validateLogin(username, password);88 }89 catch (error) {90 requestLogger(`[POST] ${req.baseUrl}/login - 500`);91 res.status(500).send(JSON.stringify({"message" : `Error Login Employee: ${error}`}));92 }93});94/* filter employees by search keyword */95router.get("/search", async (req, res) => {96 try {97 // find by username98 let emps = await Employee.find(99 {"username" : {$regex: req.query.q, $options: "i"}}100 );101 emps = emps.map(emp => Lodash.pick(emp, ["_id", "username", "fullName", "mobile", "level"]));102 requestLogger(`[GET] ${req.baseUrl}/search - 200`);103 res.status(200).send(emps);104 }105 catch (error) {106 requestLogger(`[GET] ${req.baseUrl}/search - 500`);107 res.status(500).send(JSON.stringify({"message" : `Error Searching Employee. ${error}`}));108 }109});110/** get employee by id **/111router.get("/:id", validateObjectId, async(req, res) => {112 try {113 const emp = await Employee.findById(req.params.id);114 if (!emp) {115 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 404`);116 return res.status(404).send(JSON.stringify({"message" : "Employee Not Found!"}));117 }118 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 200`);119 res.status(200).send(Lodash.pick(emp, ["_id", "username", "mobile", "level", "fullName"]));120 }121 catch (error) {122 requestLogger(`[GET] ${req.baseUrl}/${req.params.id} - 500`);123 res.status(500).send(JSON.stringify({"message" : "Server Error on Getting Employee By Id."}))124 }125});126/** edit employee **/127router.put("/:id", validateObjectId, async (req, res) => {128 try {129 const { error, message } = validateEmployeeEditRequest(req.body);130 if (error) {131 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 400`);132 return res.status(400).send(JSON.stringify({"message" : message}));133 }134 const emp = await Employee.findByIdAndUpdate(135 req.params.id,136 req.body,137 { new : true }138 );139 if (!emp) {140 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 404`);141 return res.status(404).send(JSON.stringify({"message" : "Employee Not Found"}));142 }143 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 201`);144 res.status(201).send(Lodash.pick(emp, ["_id", "username", "fullName", "mobile", "level"]));145 }146 catch (error) {147 requestLogger(`[PUT] ${req.baseUrl}/${req.params.id} - 500`);148 res.status(500).send(JSON.stringify({"message" : "Server Error on Editing Employee"}));149 }150});151/** delete employee **/152router.delete("/:id", validateObjectId, async (req, res) => {153 try {154 const emp = await Employee.findByIdAndRemove(req.params.id);155 if (!emp) {156 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 400`);157 return res.status(400).send(JSON.stringify({"message" : "User Not Found!"}));158 }159 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 200`);160 res.status(200).send(emp);161 }162 catch(error) {163 requestLogger(`[DELETE] ${req.baseUrl}/${req.params.id} - 500`);164 res.status(500).send(JSON.stringify({"message" : "Internal Server Error"}));165 }166});...
RegistrationTests.js
Source:RegistrationTests.js
...3import RegistrationPage from "../pages/RegistrationPage";4import RestUtil from "../../js/react/util/RestUtil";5import { getURL } from "../util/ClientFunctions";6const registerPage = new RegistrationPage();7const requestLogger = RequestLogger();8const USERNAME_ERROR_MESSAGE = "This username has a problem";9const PASSWORD_ERROR_MESSAGE = "This password has a problem";10const serverUsernameErrorMock = RequestMock().onRequestTo(/\/users\//).respond({11 username: [USERNAME_ERROR_MESSAGE]12}, 400, config.corsHeaders);13const serverPasswordErrorMock = RequestMock().onRequestTo(/\/users\//).respond({14 password: [PASSWORD_ERROR_MESSAGE]15}, 400, config.corsHeaders);16const serverErrorMock = RequestMock().onRequestTo(/\/users\//).respond(null, 500, config.corsHeaders);17fixture `Tests the registration page`18 .page `${config.siteUrl}/register`;19 test.requestHooks(requestLogger)("registering with a username already being used", async (t) => {20 const name = Date.now().toString(10);21 await RestUtil.sendPOST("users/", {...
requestLogger.js
Source:requestLogger.js
1const winston = require('winston');2const { createLogger,transports, format} = require('winston');3require('winston-mongodb');4const variables = require("../config/variables");5const { combine, timestamp, printf } = format;6const myFormat = printf(({ level, message, label, timestamp }) => {7 return `${timestamp} [${label}] ${level}: ${message}`;8});9class RequestLogger {10 constructor() {11 this.requestLogger = createLogger({12 format: combine(13 timestamp(),14 myFormat,15 format.metadata({fillWith: ['label'] })16 ),17 transports: [18 new transports.MongoDB({19 db: variables.MONGODB_LOG_URI,20 collection: variables.MONGODB_LOG_REQUEST_COLLECTION,21 capped:true,22 options: { useUnifiedTopology: true }23 }),24 new winston.transports.Console(),25 ]26 });27 }28 logDeniedRequest(request){29 this.requestLogger.log({30 label: 'Denied',31 level: 'warn',32 message: 'Request id: ' + request.requestid + ' User id: ' + request.userid + ' Dentist id: ' + request.dentistid33 });34 }35 logAcceptedRequest(request){36 this.requestLogger.log({37 label: 'Accepted',38 level: 'info',39 message: 'Request id: ' + request.requestid + ' User id: ' + request.userid + ' Dentist id: ' + request.dentistid40 });41 }42 logDBConnectionSuccess(message){43 this.requestLogger.log({44 label: 'DB Connected',45 level: 'info',46 message: message47 });48 }49 logLimiterAtFullCapacity(message){50 this.requestLogger.log({51 label: 'Limiter Running',52 level: 'info',53 message: message54 });55 }56}...
policies.js
Source:policies.js
1// config/policies.js2/**3* Policy defines middleware that is run before each controller/controller.4* Any policy dropped into the /middleware directory is made globally available through sails.middleware5* Below, use the string name of the middleware6*/7module.exports.policies = {8 // default require authentication9 // see api/policies/authenticated.js10 '*': [ 'requestLogger', 'jsonRedirect', 'redirect', 'transform', 'authenticated', 'fileStorage', 'context', 'customControllerCallbacks' ],11 // whitelist the auth controller12 'APAuthenticatedSessionsController': {13 'login': [ 'requestLogger', 'transform', 'context' ],14 'logout' : [ 'requestLogger' ],15 16 },17 // messaging controllers policies18 // 'ChannelController': [ 'authenticated' ],19 'ChannelController': {20 '*': ['requestLogger', 'authenticated', 'defaultPushApp'],21 'create': ['requestLogger', 'defaultPushApp'],22 'subscribe': ['requestLogger', 'defaultPushApp'],23 'unsubscribe': ['requestLogger', 'defaultPushApp']24 },25 'MessageController': {26 '*': [ 'requestLogger', 'authenticated', 'defaultPushApp' ],27 'create': [ 'requestLogger', 'defaultPushApp', 'adminOnly' ]28 },29 'DeviceController': {30 '*': ['requestLogger', 'authenticated', 'defaultPushApp'],31 'create': ['requestLogger', 'defaultPushApp'],32 'findDeviceChannels': ['requestLogger', 'defaultPushApp']33 },34 'AppController': {35 'create': ['requestLogger', 'authenticated', 'transformCertFiles'],36 'update': ['requestLogger', 'authenticated', 'transformCertFiles']37 },38 // whitelist the admin controller39 'AdminController': {40 'index': [ 'redirect' ],41 'countAll': [ ]42 },43 // whitelist the health check controller44 'APHealthCheckController': {45 'healthcheck' : [ 'requestLogger' ]46 }...
Using AI Code Generation
1import { RequestLogger } from 'testcafe';2 .requestHooks(logger)('My test', async t => {3 .click('#send-request')4 .expect(logger.contains(r => r.response.statusCode === 200)).ok();5 });6import { RequestLogger } from 'testcafe';7 .requestHooks(logger)('My test', async t => {8 .click('#send-request')9 .expect(logger.contains(r => r.response.statusCode === 200)).ok();10 });
Using AI Code Generation
1import { Selector, RequestLogger } from 'testcafe';2 .requestHooks(logger)('My test', async t => {3 await t.expect(logger.contains(record => record.response.statusCode === 200)).ok();4 });5const { CucumberJsonReporter } = require('testcafe-reporter-cucumber-json');6const reporter = new CucumberJsonReporter();7reporter.reportTaskStart(new Date(), null, null);8reporter.reportFixtureStart('My fixture');9reporter.reportTestStart('My test');10reporter.reportTestDone('My test', {11 quarantine: {12 },13}, {14 video: {15 },16 callsite: {17 },18 quarantine: {19 },20});21reporter.reportFixtureDone('My fixture');22reporter.reportTaskDone(new Date(), 0, null, null);23const { CucumberJsonReporter } = require('testcafe-reporter-cucumber-json');24const reporter = new CucumberJsonReporter();25reporter.reportTaskStart(new Date(), null, null);26reporter.reportFixtureStart('My fixture');27reporter.reportTestStart('My test');28reporter.reportTestDone('My test', {29 quarantine: {30 },31}, {
Using AI Code Generation
1import { RequestLogger } from 'testcafe';2test('My test', async t => {3 .click('#send-request')4 .expect(logger.contains(record => record.response.statusCode === 200)).ok();5});6import { RequestLogger } from 'testcafe';7test('My test', async t => {8 .click('#send-request')9 .expect(logger.contains(record => record.response.statusCode === 200)).ok();10});11import { RequestLogger } from 'testcafe';12test('My test', async t => {13 .click('#send-request')14 .expect(logger.contains(record => record.response.statusCode === 200)).ok();15});16import { RequestLogger } from 'testcafe';17test('My test', async t => {18 .click('#send-request')19 .expect(logger.contains(record => record.response.statusCode === 200)).ok();20});
Using AI Code Generation
1import { RequestLogger } from 'testcafe';2const logger = RequestLogger({ url: /.*\/api\/v1\/users\/.*/, method: 'get' }, {3});4 .requestHooks(logger);5test('My test', async t => {6 .click('#myButton')7 .expect(logger.contains(record => record.response.statusCode === 200)).ok();8});9import { RequestLogger } from 'testcafe';10const logger = RequestLogger({ url: /.*\/api\/v1\/users\/.*/, method: 'get' }, {11});12 .requestHooks(logger);13test('My test', async t => {14 .click('#myButton')15 .expect(logger.contains(record => record.response.statusCode === 200)).ok();16});17 at RequestHook._onConfigureResponse (C:\Users\user\AppData\Roaming18 at RequestHook._onConfigureResponse (C:\Users\user\AppData\Roaming
Using AI Code Generation
1import { RequestLogger } from 'testcafe';2const logger = RequestLogger(/https:\/\/example.com\/api\/.*/, {3});4 .requestHooks(logger);5test('My test', async t => {6});7import { RequestLogger } from 'testcafe';8const logger = RequestLogger(/https:\/\/example.com\/api\/.*/, {9});10 .requestHooks(logger);11test('My test', async t => {12});13import { RequestLogger } from 'testcafe';14const logger = RequestLogger(/https:\/\/example.com\/api\/.*/, {15});16 .requestHooks(logger);17test('My test', async t => {18});19import { RequestLogger } from 'testcafe';20const logger = RequestLogger(/https:\/\/example.com\/api\/.*/, {21});22 .requestHooks(logger);23test('My test', async t => {24});25import { RequestLogger } from 'testcafe';26const logger = RequestLogger(/https:\/\/example.com\/api\/.*/, {27});28 .requestHooks(logger);29test('My test', async t => {30});31import { RequestLogger } from 'testcafe';32const logger = RequestLogger(/https
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!!