Best JavaScript code snippet using cypress
userController.js
Source:userController.js
1'use strict';2const mongoose = require('mongoose'),3 bcrypt = require('bcryptjs'),4 Async = require('async'),5 saltRounds = 10,6 jwt = require('jsonwebtoken'),7 User = mongoose.model('User'),8 Code = mongoose.model('VerifyCode'),9 config = require("../config"),10 codecrt = require("../controllers/codeController"),11 {createWallets, DeleteOneWallet} = require("../controllers/walletsController"),12 {DeleteAllPawnForUser} = require("../controllers/pawnController"),13 passwordValidator = require('password-validator'),14 path = require('path'),15 multer = require('multer'),16 fs = require('fs'),17 fsextra = require('fs-extra'),18// Create a schema19 checkPass = new passwordValidator(),20 nodemailer = require('nodemailer'),21 rp = require('request-promise');22// Add properties to it23checkPass24 .is().min(8) // Minimum length 825 .is().max(100) // Maximum length 10026 .has().uppercase() // Must have uppercase letters27 .has().lowercase() // Must have lowercase letters28 .has().digits() // Must have digits29 .has().symbols() // Must have symbols30 .has().not().spaces(); // Should not have spaces31//.is().not().oneOf(['Passw0rd', 'Password123']); // Blacklist these values32// completely pointless, but whatever33const rn = require('random-number');34const options = {35 min: 1000,36 max: 999937 , integer: true38};39const Nexmo = require('nexmo');40const nexmo = new Nexmo({41 apiKey: config.API_KEY,42 apiSecret: config.API_SECRET,43}, {debug: true});44let Send_mail = async (mail, Verification) => {45 let transporter = await nodemailer.createTransport({46 service: 'gmail',47 auth: {48 user: 'mailfortest32018@gmail.com',49 pass: 'TrinhVM@1'50 }51 });52 await console.log("email " + mail);53 let mailOptions = await {54 from: 'mailfortest32018@gmail.com',55 to: mail,56 subject: 'Account Verification',57 text: 'Your confirmation code: ' + Verification,58 };59 transporter.sendMail(mailOptions, function (error, info) {60 if (error) {61 return false62 } else {63 return true64 }65 });66}67//delete on user68let DeleteOneUser = (obj) => {69 return new Promise((resolve, reject) => {70 User.findOneAndRemove(obj, function (err, userdl) {71 if (err) return reject(err);72 fsextra.removeSync(`public/uploads/${userdl.phone}`);73 resolve(userdl);74 });75 });76}77let UpdateUserSocketID = (obj) => {78 return new Promise((resolve, reject) => {79 User.findOneAndUpdate({socket_id: obj.socket_id}, obj, {new: true}, function (err, User) {80 if (err) return reject(err);81 resolve(User);82 });83 });84}85let UpdateUser = (condition, obj) => {86 return new Promise((resolve, reject) => {87 User.findOneAndUpdate(condition, obj, {new: true}, function (err, User) {88 if (err) return reject(err);89 resolve(User);90 });91 });92}93let comparePassword = function (password, user) {94 return bcrypt.compareSync(password, user.password);95}96let findManyUserObj = (obj) => {97 return new Promise((resolve, reject) => {98 User.find(obj, function (err, users) {99 if (err) reject(err);100 resolve(users);101 });102 });103}104let FindOneUserObj = (obj) => {105 return new Promise((resolve, reject) => {106 User.findOne(obj, function (err, users) {107 if (err) reject(err);108 resolve(users);109 });110 });111}112let FindUserSocketID = (obj) => {113 return new Promise((resolve, reject) => {114 User.findOne({socket_id: socket_id, _id: obj._id}, function (err, User) {115 if (err) return reject(err);116 resolve(User);117 });118 });119}120let findUserPhone = (phone) => {121 return new Promise((resolve, reject) => {122 User.findOne({phone: phone}, function (err, user) {123 if (err) reject(err);124 resolve(user);125 });126 });127};128let findUserId = (id) => {129 return new Promise((resolve, reject) => {130 User.findOne({_id: id}, function (err, user) {131 if (err) reject(err);132 resolve(user);133 });134 });135}136let findAllUser = () => {137 return new Promise((resolve, reject) => {138 User.find({}, function (err, user) {139 if (err) reject(err);140 resolve(user);141 });142 });143}144let findAllBusiness = () => {145 return new Promise((resolve, reject) => {146 User.find({roleType: 2}, function (err, user) {147 if (err) reject(err);148 resolve(user);149 });150 });151}152let UpdateUserID = (obj) => {153 return new Promise((resolve, reject) => {154 User.findOneAndUpdate({_id: obj._id}, obj, {new: true}, function (err, User) {155 if (err) return reject(err);156 User.password = undefined;157 resolve(User);158 });159 });160}161let UpdateUserObj = (condition, updateinfo) => {162 return new Promise((resolve, reject) => {163 User.findOneAndUpdate(condition, updateinfo, {new: true}, function (err, User) {164 if (err) return reject(err);165 resolve(User);166 });167 });168}169let SaveCoseVerify = (newCode) => {170 newCode.save(function (err, user) {171 if (err) console.log(err);172 });173};174let SingIN = (user, res) => {175 let Verification = rn(options);176 let newCode = new Code({177 accountId: user._id,178 phone: user.phone,179 code: Verification,180 });181 if (user.verifyType === 0) {182 // veify code mail183 if (Send_mail(user.email, Verification)) {184 SaveCoseVerify(newCode);185 return res.send({186 value: 6,187 message: Messages,188 code: Verification189 });190 } else {191 return res.send({192 value: 1,193 "message": Messages194 });195 }196 } else if (user.verifyType === 1) {197 //verify code sen message198 SaveCoseVerify(newCode);199 return res.send({200 value: 7,201 message: Messages,202 code: Verification203 });204 } else {205 return res.send({206 value: 8,207 message: Messages208 });209 }210}211let Messages = {212 1: "Send mail or message code vefrify fail",213 2: "Register user fail",214 3: "Register user error",215 4: "Find user fail",216 5: "User exits but not active",217 6: "Check mail code verify",218 7: "Check message code verify",219 8: "Type password to sign in",220 9: "Email exists",221 10: "phone undefined",222 11: "Error find code",223 12: "Check the phone number, send code more than 5 times will be blocked",224};225// gui lai code226exports.send_code_again = function (req, res) {227 //lÆ°u thông tin ngÆ°á»i dùng bảng chÃnh228 let {phone} = req.body;229 if (phone === undefined) {230 return res.send({231 message: Messages,232 value: 10,233 });234 }235 codecrt.findAllFollowPhone(Number(phone)).then(236 codes => {237 if (codes.length > 5) {238 return res.send({239 message: Messages,240 value: 12,241 });242 }243 findUserPhone(Number(phone))244 .then(245 user => {246 if (user) {247 return SingIN(user, res);248 } else {249 return res.send({250 message: Messages,251 value: 4252 });253 }254 },255 err => {256 return res.send({257 message: Messages,258 value: 4259 });260 });261 },262 err => {263 return res.send({264 message: Messages,265 value: 11,266 });267 }268 );269}270let mesVerify = {271 1: 'Authentication failed. User not found.',272 2: 'Authentication failed. code not right.',273 3: 'Authentication failed. paramas not enought.',274 4: 'Authentication failed. User not active.',275 5: 'Authentication failed. password not right.',276};277let findCode = (id) => {278 return new Promise((resolve, reject) => {279 Code.find({280 accountId: id281 }, function (err, code) {282 //console.log(code);283 if (err) reject(err);284 resolve(code[0]);285 })286 .sort({287 create_at: -1288 })289 .limit(1)290 });291}292exports.verify = function (req, res) {293 let {verifyType, code, phone, roleType} = req.body;294 if (295 verifyType === undefined || code === undefined ||296 phone === undefined || roleType === undefined297 ) {298 return res.json({299 value: 3,300 message: mesVerify301 })302 }303 FindOneUserObj({phone, roleType, verifyType})304 .then(userf => {305 if (!userf) {306 return res.json({307 value: 1,308 message: mesVerify309 })310 }311 findCode(userf._id)312 .then(313 codes => {314 if (codes) {315 if (codes.code === code) {316 //xóa code Äã active317 Code.deleteMany({318 phone: userf.phone319 }, function (err, re) {320 if (err) console.log(err);321 })322 if (userf.activeType === 0) {323 User.findOneAndUpdate(324 {_id: userf._id},325 {activeType: 1}, {new: true}, function (err, useOne) {326 console.log(err);327 })328 }329 userf.password = undefined;330 return res.send({331 message: jwt.sign({332 phone: userf.phone,333 create_at: userf.create_at,334 fullName: userf.fullName,335 _id: userf._id336 }, config.secret),337 value: 0,338 id: userf._id,339 roleType: userf.roleType,340 });341 } else {342 return res.send({343 value: 2,344 message: mesVerify345 })346 }347 }348 else {349 return res.send({350 value: 2,351 message: mesVerify352 })353 }354 },355 err => {356 return res.json({357 value: 2,358 message: mesVerify359 })360 }361 )362 },363 err => {364 return res.json({365 value: 1,366 message: mesVerify367 })368 });369}370//function dung Äá» ÄÄng ký bằng web371//dùng Äá» ÄÄng nháºp bằng máºt khẩu372//roleType: 2, // 1 user, 2 driver, 0 admin373//verifyType: 2, // 0: mail, 1 phone, 2 password374//kiá»m tra nếu email và phone tá»n tại sẽ không cho ÄÄng ký375exports.register_old = function (req, res) {376 if (req.body.phone === undefined ||377 req.body.password === undefined ||378 req.body.countryCode === undefined ||379 req.body.fullName === undefined) {380 return res.send({381 message: 'Truyá»n thiếu biến',382 value: 5383 });384 }385 if (!checkPass.validate(req.body.password)) {386 return res.send({387 value: 1,388 message: 'Minimum length 8, ' +389 'Maximum length 100, ' +390 'Must have uppercase letters, ' +391 'Must have lowercase letters, ' +392 'Must have digits, ' +393 'Must have symbols, ' +394 'Should not have spaces'395 });396 }397 findUserPhone(req.body.phone)398 .then(399 userphone => {400 if (!userphone) {401 let newUser = new User(req.body);402 newUser.verifyType = 1;403 newUser.roleType = 2;404 newUser.password = bcrypt.hashSync(req.body.password, saltRounds);405 newUser.save(function (err, users) {406 if (err) {407 console.log(err);408 return res.send({409 message: 'Lá»i ÄÄng ký',410 value: 4411 });412 } else {413 if (users) {414 let Verification = rn(options);415 let newCode = new Code({416 accountId: users._id,417 phone: users.phone,418 code: Verification,419 });420 SaveCoseVerify(newCode);421 //tạo giá» tiá»n khi ÄÄng ký thà nh công422 createWallets({423 accountID: users._id,424 phone: users.phone,425 }).then(426 res => {427 console.log("create wallet success");428 },429 err => {430 console.log("create wallet fail");431 }432 );433 return res.send({434 message: 'ÄÄng ký thà nh công',435 value: 0,436 code: Verification437 });438 }439 else {440 return res.send({441 message: 'Lá»i ÄÄng ký',442 value: 4,443 });444 }445 }446 });447 } else {448 return res.send({449 message: 'Sá» Äiá»n thoại Äã tá»n tại',450 value: 3451 });452 }453 },454 err => {455 return res.send({456 message: 'Sá» Äiá»n thoại Äã tá»n tại',457 value: 3458 });459 }460 );461}462exports.register_user_pass = function (req, res) {463 if (req.body.phone === undefined ||464 req.body.password === undefined ||465 req.body.countryCode === undefined ||466 req.body.fullName === undefined) {467 return res.send({468 message: 'Truyá»n thiếu biến',469 value: 5470 });471 }472 if (!checkPass.validate(req.body.password)) {473 return res.send({474 value: 1,475 message: 'Minimum length 8, ' +476 'Maximum length 100, ' +477 'Must have uppercase letters, ' +478 'Must have lowercase letters, ' +479 'Must have digits, ' +480 'Must have symbols, ' +481 'Should not have spaces'482 });483 }484 findUserPhone(req.body.phone)485 .then(486 userphone => {487 if (!userphone) {488 let newUser = new User(req.body);489 newUser.verifyType = 1;490 newUser.roleType = 1;491 newUser.password = bcrypt.hashSync(req.body.password, saltRounds);492 newUser.save(function (err, user) {493 if (err) {494 console.log(err);495 return res.send({496 message: 'Lá»i ÄÄng ký',497 value: 4498 });499 } else {500 if (user) {501 let Verification = rn(options);502 let newCode = new Code({503 accountId: user._id,504 phone: user.phone,505 code: Verification,506 });507 SaveCoseVerify(newCode);508 //tạo giá» tiá»n khi ÄÄng ký thà nh công509 createWallets({510 accountID: user._id,511 phone: user.phone,512 }).then(513 res => {514 console.log("create wallet success");515 },516 err => {517 console.log("create wallet fail");518 }519 );520 return res.send({521 message: 'ÄÄng ký thà nh công',522 value: 0,523 code: Verification524 });525 }526 else {527 return res.send({528 message: 'Lá»i ÄÄng ký',529 value: 4,530 });531 }532 }533 });534 } else {535 return res.send({536 message: 'Sá» Äiá»n thoại Äã tá»n tại',537 value: 3538 });539 }540 },541 err => {542 return res.send({543 message: 'Sá» Äiá»n thoại Äã tá»n tại',544 value: 3545 });546 }547 );548}549exports.update_active = function (req, res) {550 User.findOneAndUpdate({email: req.params.email}, req.body, {new: true}, function (err, User) {551 if (err)552 return res.status(400).send({553 response: 'Update fail',554 value: false555 });556 User.password = undefined;557 res.json({558 value: true,559 response: User560 });561 });562}563exports.profile = function (req, res) {564 User.findOne({_id: req.params.id}, function (err, User) {565 if (err) {566 return res.send({567 response: 'get profile fail',568 value: false569 });570 } else {571 if (User) {572 User.password = undefined;573 res.send({574 value: true,575 response: User576 });577 } else {578 return res.send({579 response: 'get profile fail',580 value: false581 });582 }583 }584 });585}586exports.update_profile = function (req, res) {587 User.findOneAndUpdate({_id: req.params.id}, req.body, {new: true}, function (err, User) {588 if (err)589 return res.send({590 response: 'Update fail',591 value: false592 });593 User.password = undefined;594 res.json({595 value: true,596 response: User597 });598 });599}600exports.update_password = function (req, res) {601 let {password, id} = req.body;602 if (password === undefined || id === undefined) {603 return res.send({604 value: 'not found params',605 response: false606 });607 }608 if (!checkPass.validate(password)) {609 return res.send({610 value: 'Minimum length 8, ' +611 'Maximum length 100, ' +612 'Must have uppercase letters, ' +613 'Must have lowercase letters, ' +614 'Must have digits, ' +615 'Must have symbols, ' +616 'Should not have spaces',617 response: false,618 });619 }620 let passwordh = bcrypt.hashSync(password, saltRounds);621 User.findOneAndUpdate({_id: id}, {622 password: passwordh623 }, {new: true}, function (err, User) {624 if (err)625 return res.send({626 value: 'Update fail',627 response: false628 });629 User.password = undefined;630 res.json({631 response: true,632 value: User633 });634 });635}636let uploadDir = config.folder_temp;637let Storage = multer.diskStorage({638 destination: uploadDir,639 filename: function (req, file, callback) {640 callback(null, file.fieldname + '-' + Date.now() + ".jpg");641 }642});643let upload = multer({644 storage: Storage,645 fileFilter: function (req, file, callback) {646 let ext = path.extname(file.originalname).toLowerCase();647 if (ext !== '.png'648 && ext !== '.jpg'649 && ext !== '.jpeg'650 ) {651 return callback(new Error('Only images are allowed'))652 }653 callback(null, true)654 },655 limits: {656 fileSize: 6000000657 }658}).single('avatar'); //Field name and max count659exports.update_avatar = function (req, res) {660 upload(req, res, function (err) {661 if (err) {662 return res.send({663 "response": false,664 "value": err,665 });666 }667 //console.log(req.file);668 if (!req.file) {669 return res.send({670 "response": false,671 "value": "not find image"672 });673 }674 let {id} = req.body;675 if (id === undefined) {676 return res.send({677 "response": false,678 "value": "not find params id user"679 });680 }681 findUserId(id)682 .then(683 userf => {684 if (userf) {685 // update and move avatar from folder tepms to folder user( phone number)686 UpdateUserID({_id: id, avatarLink: req.file.filename})687 .then(useru => {688 fsextra.moveSync(689 path.join(`${config.folder_temp}`, `${req.file.filename}`),690 path.join(`${config.folder_uploads}`, `${useru.phone}`, `${req.file.filename}`),691 {overwrite: true});692 FindAllInfoUser({_id: id})693 .then(userrp => {694 return res.send({695 value: userrp,696 response: true697 });698 },699 err => {700 return res.send({701 "response": false,702 "value": err703 });704 }705 );706 }, err => {707 return res.send({708 "response": false,709 "value": err710 });711 })712 } else {713 return res.send({714 "response": false,715 "value": "not find user"716 });717 }718 },719 err => {720 return res.send({721 "response": false,722 "value": err723 });724 }725 );726 });727};728let FindAllInfoUser = (obj) => {729 return new Promise((resolve, reject) => {730 User.findOne({_id: obj._id}, function (err, userf) {731 if (err) return reject(err);732 resolve(userf);733 });734 });735}736// dung Äá»737// update thông tin user738exports.update_userboth = (req, res) => {739 let {id} = req.body;740 let {phone} = req.user;741 console.log(req.body);742 if (id === undefined || phone === undefined) {743 return res.send({744 "response": false,745 "value": "not found id",746 });747 }748 UpdateUserObj({_id: id, phone}, req.body)749 .then(750 useru => {751 if (useru) {752 res.send({753 "response": true,754 "value": useru,755 });756 } else {757 res.send({758 "response": false,759 "value": "update fail",760 });761 }762 },763 err => {764 return res.send({765 "response": false,766 "value": err767 });768 }769 );770}771exports.update_identityCardFront = function (req, res) {772 upload(req, res, function (err) {773 if (err) {774 return res.send({775 "response": false,776 "value": err777 });778 }779 //console.log(req.file);780 if (!req.file) {781 return res.send({782 "response": false,783 "value": "not find image"784 });785 }786 if (req.body.id === undefined || req.body.expression === undefined || req.user.phone === undefined) {787 return res.send({788 "response": false,789 "value": "not find params id user"790 });791 }792 FindOneUserObj({_id: req.body.id, phone: req.user.phone})793 .then(794 userf => {795 if (!userf) {796 return res.json({797 "response": false,798 "value": "not find user"799 });800 }801 switch (req.body.expression) {802 case 'identityCardFront':803 // update and move avatar from folder tepms to folder user( phone number)804 UpdateUserObj({_id: req.body.id}, {identityCardFront: req.file.filename})805 .then(useru => {806 fsextra.moveSync(807 path.join(`${config.folder_temp}`, `${req.file.filename}`),808 path.join(`${config.folder_uploads}`, `${userf.phone}`, `${req.file.filename}`),809 {overwrite: true});810 return res.send({811 value: useru,812 response: true813 });814 }, err => {815 return res.json({816 "response": false,817 "value": err818 });819 });820 break;821 case 'identityCardBehind':822 // update and move avatar from folder tepms to folder user( phone number)823 UpdateUserObj({_id: req.body.id}, {identityCardBehind: req.file.filename})824 .then(useru => {825 fsextra.moveSync(826 path.join(`${config.folder_temp}`, `${req.file.filename}`),827 path.join(`${config.folder_uploads}`, `${userf.phone}`, `${req.file.filename}`),828 {overwrite: true});829 return res.send({830 value: useru,831 response: true832 });833 }, err => {834 return res.json({835 "response": false,836 "value": err837 });838 });839 break;840 case 'licenseeImageFront':841 // update and move avatar from folder tepms to folder user( phone number)842 UpdateUserObj({_id: req.body.id}, {licenseeImageFront: req.file.filename})843 .then(useru => {844 fsextra.moveSync(845 path.join(`${config.folder_temp}`, `${req.file.filename}`),846 path.join(`${config.folder_uploads}`, `${userf.phone}`, `${req.file.filename}`),847 {overwrite: true});848 return res.send({849 value: useru,850 response: true851 });852 }, err => {853 return res.json({854 "response": false,855 "value": err856 });857 });858 break;859 case 'licenseeImageBehind':860 // update and move avatar from folder tepms to folder user( phone number)861 UpdateUserObj({_id: req.body.id}, {licenseeImageBehind: req.file.filename})862 .then(useru => {863 fsextra.moveSync(864 path.join(`${config.folder_temp}`, `${req.file.filename}`),865 path.join(`${config.folder_uploads}`, `${userf.phone}`, `${req.file.filename}`),866 {overwrite: true});867 return res.send({868 value: useru,869 response: true870 });871 }, err => {872 return res.json({873 "response": false,874 "value": err875 });876 });877 break;878 default:879 return res.json({880 "response": false,881 "value": "không tim thấy"882 });883 }884 },885 err => {886 return res.json({887 "response": false,888 "value": err889 });890 }891 );892 });893}894exports.sign_in = function (req, res) {895 if (req.body.phone === undefined ||896 req.body.password === undefined) {897 return res.send({898 message: 'Truyá»n thiếu biến',899 value: 6900 });901 }902 User.findOne({903 phone: req.body.phone904 }, function (err, user) {905 if (err) {906 return res.send({907 message: 'Lá»i tìm user',908 value: 5,909 })910 }911 if (!user) {912 return res.send({913 message: 'Tà i khoản không tá»n tại',914 value: 2,915 })916 }917 if (!comparePassword(req.body.password, user)) {918 return res.json({919 message: 'Máºt khẩu không Äúng.',920 value: 3,921 })922 }923 if (user.activeType < 1) {924 return res.send({925 message: 'Tà i khoản chÆ°a Äược xác thá»±c',926 value: 1,927 })928 }929 res.send({930 message: jwt.sign({931 phone: user.phone,932 create_at: user.create_at,933 fullName: user.fullName,934 _id: user._id935 }, config.secret),936 value: 0,937 id: user._id,938 roleType: user.roleType,939 });940 })941}942exports.sign_in_admin = function (req, res) {943 if (req.body.phone === undefined ||944 req.body.password === undefined) {945 return res.send({946 value: 'not find params',947 response: false948 });949 }950 User.findOne({951 phone: req.body.phone952 }, function (err, user) {953 if (err) {954 return res.send({955 value: err,956 response: false957 });958 }959 if (!user) {960 return res.send({961 value: "user not found",962 response: false963 });964 }965 if (!comparePassword(req.body.password, user)) {966 return res.send({967 value: "wrong password",968 response: false969 })970 }971 if (user.activeType < 1) {972 return res.send({973 value: 'account not active',974 response: false,975 })976 }977 if (user.roleType !== 0) {978 return res.send({979 value: 'account not admin',980 response: false,981 })982 }983 res.send({984 value: jwt.sign({985 phone: user.phone,986 fullName: user.fullName,987 _id: user._id988 }, config.secret),989 response: true,990 roleType: user.roleType,991 });992 })993}994//kiem tra Äang nháºp qua session995exports.get_info = function (req, res) {996 let {phone} = req.user;997 if (!phone) {998 return res.send({999 value: "not find info user",1000 response: false1001 })1002 }1003 findUserPhone(phone)1004 .then(userf => {1005 if (userf) {1006 userf.activeType = undefined;1007 userf.password = undefined;1008 userf.verifyType = undefined;1009 return res.send({1010 value: userf,1011 response: true1012 })1013 } else {1014 return res.send({1015 value: "not find info user",1016 response: false1017 })1018 }1019 }, err => {1020 return res.send({1021 value: err,1022 response: false1023 })1024 })1025}1026exports.loginRequired = function (req, res, next) {1027 if (req.user) {1028 next();1029 } else {1030 return res.status(401).json({message: 'Unauthorized user!'});1031 }1032};1033exports.get_all_business = function (req, res) {1034 findAllBusiness()1035 .then(users => {1036 return res.json({1037 response: true,1038 value: users,1039 })1040 }, err => {1041 return res.json({1042 response: false,1043 value: err,1044 })1045 })1046};1047//get all user not follow1048exports.get_all_user_business_follow = function (req, res) {1049 findManyUserObj({roleType: 2, accept: false})1050 .then(users => {1051 return res.json({1052 response: true,1053 value: users,1054 })1055 }, err => {1056 return res.json({1057 response: false,1058 value: err,1059 })1060 })1061};1062exports.get_all_user_business_following = function (req, res) {1063 findManyUserObj({roleType: 2, accept: true})1064 .then(users => {1065 return res.json({1066 response: true,1067 value: users,1068 })1069 }, err => {1070 return res.json({1071 response: false,1072 value: err,1073 })1074 })1075};1076//delte user and delete all table have relationship1077let DeleteUser = (obj) => {1078 return new Promise((resolve, reject) => {1079 findUserId(obj._id)1080 .then(1081 userdl => {1082 //console.log(userdl);1083 if (userdl) {1084 if (userdl.length > 0) {1085 // không tá»n tại hoặc là admin không Äược xóa1086 reject("không xóa Äược, không tá»n tại hoặc là admin");1087 }1088 if (userdl.roleType === 1) {1089 // = 1 là ngÆ°á»i dùng1090 // tìm tất cả các pawn của ngÆ°á»i dùng Äá» xóa1091 DeleteAllPawnForUser(obj);1092 resolve(userdl);1093 }1094 if (userdl.roleType === 2) {1095 // = 2 là bussiness1096 resolve(userdl);1097 }1098 } else {1099 // không tá»n tại hoặc là admin không Äược xóa1100 reject("không xóa Äược, không tá»n tại hoặc là admin");1101 }1102 },1103 err => {1104 reject(err);1105 }1106 )1107 });1108};1109exports.delete_one_user_by_id = (req, res) => {1110 if (req.body._id === undefined) {1111 return res.json({1112 response: false,1113 value: "not find params id user"1114 })1115 }1116 DeleteUser(req.body)1117 .then(1118 userdl => {1119 if (userdl) {1120 return res.json({1121 response: true,1122 value: userdl1123 })1124 } else {1125 return res.json({1126 response: false,1127 value: "delete fail",1128 })1129 }1130 },1131 err => {1132 return res.json({1133 response: false,1134 value: err,1135 })1136 }1137 )1138}1139// inser new comments for user1140exports.insert_comment = (req, res) => {1141 let {_id, rating_star, body} = req.body;1142 let {phone} = req.user;1143 if (_id === undefined ||1144 rating_star === undefined ||1145 body === undefined ||1146 phone === undefined) {1147 return res.send({1148 "response": false,1149 "value": "not find params "1150 });1151 }1152 FindOneUserObj({phone})1153 .then(userf => {1154 if (userf) {1155 FindOneUserObj({_id})1156 .then(ownerf => {1157 if (ownerf) {1158 ownerf.comments.push({accountID: userf._id,phone:userf.phone,fullName:userf.fullName,sex:userf.sex,avatarLink:userf.avatarLink, rating_star, body});1159 ownerf.save(function (err, userud) {1160 if (err) return res.send({1161 "response": false,1162 "value": err1163 });1164 return res.send({1165 "response": true,1166 "value": userud1167 });1168 });1169 } else {1170 return res.send({1171 "response": false,1172 "value": "not find user"1173 });1174 }1175 },1176 err => {1177 return res.send({1178 "response": false,1179 "value": err1180 });1181 }1182 )1183 } else {1184 return res.send({1185 "response": false,1186 "value": "token is not master onwe"1187 });1188 }1189 },1190 err => {1191 return res.send({1192 "response": false,1193 "value": err1194 });1195 }1196 )1197}1198// get all comment1199exports.get_all_comment = (req, res) => {1200 let {phone} = req.user;1201 if (phone === undefined) {1202 return res.send({1203 "response": false,1204 "value": "not find params "1205 });1206 }1207 FindOneUserObj({phone})1208 .then(userf => {1209 if (userf) {1210 if (userf.roleType !== 0) {1211 return res.send({1212 "response": false,1213 "value": "user is not allowed to view this content"1214 });1215 }1216 findManyUserObj({"comments": {$ne: null}})1217 .then(userfcomment => {1218 let comments = [];1219 Async.forEachOf(userfcomment, function (usercm, key, callback) {1220 comments.push(...usercm.comments);1221 callback();1222 }, function (err) {1223 if (err) return res.send({1224 "response": false,1225 "value": err1226 });1227 res.send({1228 "response": true,1229 "value": comments,1230 });1231 });1232 }, err => {1233 console.log(err);1234 return res.send({1235 "response": false,1236 "value": "err find comments"1237 });1238 })1239 } else {1240 return res.send({1241 "response": false,1242 "value": "token is not master onwe"1243 });1244 }1245 },1246 err => {1247 return res.send({1248 "response": false,1249 "value": err1250 });1251 }1252 );1253}1254let FindCommentStatus = () => {1255 return new Promise((resolve, reject) => {1256 findManyUserObj({"comments": {$ne: null}})1257 .then(userfcomment => {1258 let comments = [];1259 Async.forEachOf(userfcomment, function (usercm, key, callback) {1260 comments.push(...usercm.comments);1261 callback();1262 }, function (err) {1263 if (err) return reject(err);1264 let comstatus = [];1265 Async.forEachOf(comments, function (comment, key, callback) {1266 if (comment.status === 1) {1267 comstatus.push(comment);1268 }1269 callback();1270 }, function (err) {1271 if (err) return reject(err);1272 resolve(comstatus);1273 });1274 });1275 }, err => {1276 reject(err);1277 })1278 });1279}1280// get all comment da duyet1281exports.get_all_comment_status = (req, res) => {1282 let { page, limit } = req.params;1283 if (page === undefined || limit === undefined) {1284 return res.send({1285 "response": false,1286 "value": "not find params "1287 });1288 }1289 FindCommentStatus()1290 .then(commets => {1291 if (commets.length > 0) {1292 return res.send({1293 "response": true,1294 "value": commets.slice((0 + page - 1) * limit, page * limit),1295 "pages": Math.round(commets.length/limit*1+0.5),1296 });1297 } else {1298 return res.send({1299 "response": false,1300 "value": "không tìm thấy comments"1301 });1302 }1303 }, err => {1304 console.log(err);1305 return res.send({1306 "response": false,1307 "value": "Lá»i tìm kiếm comments"1308 });1309 })1310}1311// update status comment1312exports.update_comment_status = (req, res) => {1313 let {_id} = req.body;1314 let {phone} = req.user;1315 if (phone === undefined || _id === undefined) {1316 return res.send({1317 "response": false,1318 "value": "not find params "1319 });1320 }1321 FindOneUserObj({phone})1322 .then(userf => {1323 if (userf) {1324 if (userf.roleType !== 0) {1325 return res.send({1326 "response": false,1327 "value": "user is not allowed to view this content"1328 });1329 }1330 User.findOne({"comments._id": _id}, function (err, usercomment) {1331 if (err || !usercomment) return res.send({1332 "response": false,1333 "value": "not find user comment"1334 });1335 let indexP = usercomment.comments.findIndex(comment => comment._id+"" === _id+"");1336 if (indexP < 0) {1337 return res.send({1338 "response": false,1339 "value": "not find index comment"1340 });1341 }1342 usercomment.comments[indexP].status = !usercomment.comments[indexP].status;1343 usercomment.save(function (err, usercommentupdate) {1344 if (err) return res.send({1345 "response": false,1346 "value": "errors update comment"1347 });1348 return res.send({1349 "response": true,1350 "value": usercommentupdate.comments[indexP]1351 });1352 });1353 })1354 } else {1355 return res.send({1356 "response": false,1357 "value": "token is not master onwe"1358 });1359 }1360 },1361 err => {1362 return res.send({1363 "response": false,1364 "value": "not find user"1365 });1366 }1367 );1368}1369// delete comment1370exports.delete_comments = (req, res) => {1371 let {_id} = req.body;1372 let {phone} = req.user;1373 if (phone === undefined || _id === undefined) {1374 return res.send({1375 "response": false,1376 "value": "not find params "1377 });1378 }1379 FindOneUserObj({phone})1380 .then(userf => {1381 if (userf) {1382 if (userf.roleType !== 0) {1383 return res.send({1384 "response": false,1385 "value": "user is not allowed to view this content"1386 });1387 }1388 User.findOne({"comments._id": _id}, function (err, usercomment) {1389 if (err || !usercomment) return res.send({1390 "response": false,1391 "value": "not find user comment"1392 });1393 let commentde = usercomment.comments.id(_id).remove();1394 // Equivalent to `parent.child = null`1395 usercomment.save(function (err) {1396 if (err)if (err) return res.send({1397 "response": false,1398 "value": "errors delete comment"1399 });1400 return res.send({1401 "response": true,1402 "value": commentde1403 });1404 });1405 })1406 } else {1407 return res.send({1408 "response": false,1409 "value": "token is not master onwe"1410 });1411 }1412 },1413 err => {1414 return res.send({1415 "response": false,1416 "value": "not find user"1417 });1418 }1419 );1420}1421exports.FindOneUserObj = FindOneUserObj;1422exports.findAllBusiness = findAllBusiness;1423exports.FindUserSocketID = FindUserSocketID;1424exports.findUserId = findUserId;1425// tìm kiếm ngÆ°á»i dùng qua sá» Äiá»n thoại1426exports.find_user_phone = findUserPhone;1427exports.findAllUser = findAllUser;...
TestimonialController.js
Source:TestimonialController.js
1'use strict';2const Testimonials = require('../models/testimonialModel');3const Users = require('../controllers/userController'),4 path = require('path'),5 multer = require('multer'),6 fsextra = require('fs-extra'),7 config = require('../config');8let CreateOneTestimonialObj = (obj) => {9 return new Promise((resolve, reject) => {10 let newTestimonials = new Testimonials(obj);11 newTestimonials.save(function (err, testimonal) {12 if (err) {13 return reject(err)14 }15 resolve(testimonal);16 })17 })18}19let FindAllTestimonialObj = (obj) => {20 return new Promise((resolve, reject) => {21 Testimonials.find(obj, function (err, testimonal) {22 if (err) {23 return reject(err)24 }25 resolve(testimonal);26 })27 })28}29let UpdateTestimonial = (conditon, obj) => {30 return new Promise((resolve, reject) => {31 Testimonials.findOneAndUpdate(conditon, obj, {new: true}, function (err, tm) {32 if (err) return reject(err);33 resolve(tm);34 });35 });36}37//delete one Testimonials38let DeleteOneTestimonial = (obj) => {39 return new Promise((resolve, reject) => {40 Testimonials.findOneAndRemove(obj, function (err, tm) {41 if (err) return reject(err);42 try {43 fsextra.remove(path.join(`${config.folder_uploads}`, `testimonials`, `${tm.avatarLink}`));44 resolve(tm);45 } catch (err) {46 return reject(err);47 }48 });49 });50};51let uploadDir = config.folder_temp;52let Storage = multer.diskStorage({53 destination: uploadDir,54 filename: function (req, file, callback) {55 callback(null, file.fieldname + '-' + Date.now() + ".jpg");56 }57});58/*59* function upload ảnh kiá»m tra ảnh Äá»nh dạng Äuôi có phải là png, jpg, hay jpeg60* dung lượng tá»i Äa cho phép là 6 mb61* */62let upload = multer({63 storage: Storage,64 fileFilter: function (req, file, callback) {65 let ext = path.extname(file.originalname).toLowerCase();66 if (ext !== '.png'67 && ext !== '.jpg'68 && ext !== '.jpeg'69 ) {70 return callback(new Error('Only images are allowed'))71 }72 callback(null, true)73 },74 limits: {75 fileSize: 600000076 }77}).single('file'); //Field name and max count78exports.insert_testimonial = (req, res) => {79 upload(req, res, function (err) {80 if (err) {81 return res.send({82 "response": false,83 "value": "upload file fail"84 });85 }86 if (!req.file) {87 return res.send({88 "response": false,89 "value": "upload file fail"90 });91 }92 let {content, full_name} = req.body;93 let {phone} = req.user;94 if (95 content === undefined ||96 phone === undefined ||97 full_name === undefined98 ) {99 return res.send({100 "response": false,101 "value": "not find params "102 });103 }104 Users.FindOneUserObj({phone})105 .then(userf => {106 if (userf) {107 if (userf.roleType !== 0) {108 return res.send({109 "response": false,110 "value": "account not admin"111 });112 }113 CreateOneTestimonialObj({content, full_name, avatarLink: req.file.filename})114 .then(testimonial => {115 if (!testimonial) {116 return res.send({117 "response": false,118 "value": "not find user"119 });120 }121 fsextra.moveSync(122 path.join(`${config.folder_temp}`, `${req.file.filename}`),123 path.join(`${config.folder_uploads}`, `testimonials`, `${req.file.filename}`),124 {overwrite: true});125 return res.send({126 "response": true,127 "value": testimonial128 });129 },130 err => {131 return res.send({132 "response": false,133 "value": "create testimonial"134 });135 }136 )137 } else {138 return res.send({139 "response": false,140 "value": "not find account admin"141 });142 }143 },144 err => {145 return res.send({146 "response": false,147 "value": "not find account admin"148 });149 }150 )151 })152}153// get all comment154exports.get_all_testimonials = (req, res) => {155 let {phone} = req.user;156 if (phone === undefined) {157 return res.send({158 "response": false,159 "value": "not find params "160 });161 }162 Users.FindOneUserObj({phone})163 .then(userf => {164 if (userf) {165 if (userf.roleType !== 0) {166 return res.send({167 "response": false,168 "value": "user is not allowed to view this content"169 });170 }171 FindAllTestimonialObj({})172 .then(testimonals => {173 if (testimonals.length === 0) {174 return res.send({175 "response": false,176 "value": []177 });178 }179 return res.send({180 "response": true,181 "value": testimonals182 });183 }, err => {184 return res.send({185 "response": false,186 "value": "err find testimonals"187 });188 })189 } else {190 return res.send({191 "response": false,192 "value": "token is not master onwe"193 });194 }195 },196 err => {197 return res.send({198 "response": false,199 "value": err200 });201 }202 );203}204// get all comment da duyet205exports.get_all_testimonials_active = (req, res) => {206 FindAllTestimonialObj({status: 1})207 .then(testimonals => {208 if (testimonals.length > 0) {209 return res.send({210 "response": true,211 "value": testimonals212 });213 } else {214 return res.send({215 "response": false,216 "value": "không tìm thấy comments"217 });218 }219 }, err => {220 return res.send({221 "response": false,222 "value": "Lá»i tìm kiếm comments"223 });224 })225}226// update status comment227exports.update_testimonial = (req, res) => {228 let {_id} = req.body;229 let {phone} = req.user;230 if (phone === undefined || _id === undefined) {231 return res.send({232 "response": false,233 "value": "not find params "234 });235 }236 let obj = {...req.body};237 // obj._id = undefined;238 Users.FindOneUserObj({phone})239 .then(userf => {240 if (userf) {241 if (userf.roleType !== 0) {242 return res.send({243 "response": false,244 "value": "user is not allowed to view this content"245 });246 }247 UpdateTestimonial({_id}, obj)248 .then(testimonal => {249 if (!testimonal) {250 return res.send({251 "response": false,252 "value": "update fail "253 });254 }255 res.send({256 "response": true,257 "value": testimonal258 });259 }, err => {260 return res.send({261 "response": false,262 "value": "update error"263 });264 });265 } else {266 return res.send({267 "response": false,268 "value": "token is not master onwe"269 });270 }271 },272 err => {273 return res.send({274 "response": false,275 "value": "not find user"276 });277 }278 );279}280// update testimonial iamge281exports.update_testimonial_image = (req, res) => {282 upload(req, res, function (err) {283 if (err) {284 return res.send({285 "response": false,286 "value": "upload file fail"287 });288 }289 if (!req.file) {290 return res.send({291 "response": false,292 "value": "upload file fail"293 });294 }295 let {_id} = req.body;296 let {phone} = req.user;297 if (phone === undefined || _id === undefined) {298 return res.send({299 "response": false,300 "value": "not find params "301 });302 }303 let obj = {...req.body};304 obj.avatarLink = req.file.filename;305 Users.FindOneUserObj({phone})306 .then(userf => {307 if (userf) {308 if (userf.roleType !== 0) {309 return res.send({310 "response": false,311 "value": "user is not allowed to view this content"312 });313 }314 UpdateTestimonial({_id}, obj)315 .then(testimonal => {316 if (!testimonal) {317 return res.send({318 "response": false,319 "value": "not find user comment"320 });321 }322 //remove icon old323 try {324 fsextra.remove(path.join(`${config.folder_uploads}`, `testimonials`, `${req.body.avatarLink}`));325 console.log('success!')326 } catch (err) {327 console.error(err)328 }329 fsextra.moveSync(330 path.join(`${config.folder_temp}`, `${req.file.filename}`),331 path.join(`${config.folder_uploads}`, `testimonials`, `${req.file.filename}`),332 {overwrite: true});333 res.send({334 "response": true,335 "value": testimonal336 });337 }, err => {338 return res.send({339 "response": false,340 "value": "update error"341 });342 });343 } else {344 return res.send({345 "response": false,346 "value": "token is not master onwe"347 });348 }349 },350 err => {351 return res.send({352 "response": false,353 "value": "not find user"354 });355 }356 );357 })358}359// delete comment360exports.delete_testimonial = (req, res) => {361 let {_id} = req.body;362 let {phone} = req.user;363 if (phone === undefined || _id === undefined) {364 return res.send({365 "response": false,366 "value": "not find params "367 });368 }369 Users.FindOneUserObj({phone})370 .then(userf => {371 if (userf) {372 if (userf.roleType !== 0) {373 return res.send({374 "response": false,375 "value": "user is not allowed to view this content"376 });377 }378 DeleteOneTestimonial({_id})379 .then(testimonal => {380 if (!testimonal) return res.send({381 "response": false,382 "value": "not find user comment"383 });384 res.send({385 "response": true,386 "value": testimonal387 });388 }, err => {389 return res.send({390 "response": false,391 "value": "not find user comment"392 });393 });394 } else {395 return res.send({396 "response": false,397 "value": "token is not master onwe"398 });399 }400 },401 err => {402 return res.send({403 "response": false,404 "value": "not find user"405 });406 }407 );...
advertiseController.js
Source:advertiseController.js
1'use strict';2const advertise = require('../models/advertiseModel'),3 user = require('../controllers/userController'),4 path = require('path'),5 multer = require('multer'),6 fsextra = require('fs-extra'),7 config = require('../config');8let FindOneAdvertise = (obj) => {9 return new Promise((resolve, reject) => {10 advertise.findOne(obj, function (err, adv) {11 if (err) return reject(err);12 resolve(adv);13 });14 });15};16let FindAllAdvertise = (obj) => {17 return new Promise((resolve, reject) => {18 advertise.find(obj, function (err, adv) {19 if (err) return reject(err);20 resolve(adv);21 }).sort({status: 1, create_at: -1});22 });23};24let UpdateAdvertise = (condition, Obj) => {25 return new Promise((resolve, reject) => {26 advertise.findOneAndUpdate(condition, Obj, {new: true}, function (err, adv) {27 if (err) reject(err);28 resolve(adv);29 });30 });31};32//delete on Advertise33let DeleteOneAdvertise = (obj) => {34 return new Promise((resolve, reject) => {35 advertise.findOneAndRemove(obj, function (err, adv) {36 if (err) return reject(err);37 //remove icon old38 try {39 fsextra.remove(path.join(`${config.folder_uploads}`, `advertises`, `${adv.url_image}`));40 resolve(adv);41 } catch (err) {42 return reject(err);43 }44 });45 });46}47let uploadDir = config.folder_temp;48let Storage = multer.diskStorage({49 destination: uploadDir,50 filename: function (req, file, callback) {51 callback(null, file.fieldname + '-' + Date.now() + ".jpg");52 }53});54/*55* function upload ảnh kiá»m tra ảnh Äá»nh dạng Äuôi có phải là png, jpg, hay jpeg56* dung lượng tá»i Äa cho phép là 6 mb57* */58let upload = multer({59 storage: Storage,60 fileFilter: function (req, file, callback) {61 let ext = path.extname(file.originalname).toLowerCase();62 if (ext !== '.png'63 && ext !== '.jpg'64 && ext !== '.jpeg'65 ) {66 return callback(new Error('Only images are allowed'))67 }68 callback(null, true)69 },70 limits: {71 fileSize: 600000072 }73}).single('image'); //Field name and max count74exports.insert_one = function (req, res) {75 upload(req, res, function (err) {76 if (err) {77 return res.send({78 "response": false,79 "value": "upload file fail"80 });81 }82 if (req.file) {83 if (req.user.phone === undefined) {84 return res.send({85 "response": false,86 "value": "user not found"87 });88 }89 user.find_user_phone(req.user.phone)90 .then(user => {91 if (user.roleType === 0) {92 let newAdv = new advertise(req.body);93 newAdv.url_image = req.file.filename;94 newAdv.save(function (err, adves) {95 if (err) return res.send({96 response: false,97 value: err,98 });99 fsextra.moveSync(100 path.join(`${config.folder_temp}`, `${req.file.filename}`),101 path.join(`${config.folder_uploads}`, `advertises`, `${req.file.filename}`),102 {overwrite: true});103 res.send({104 response: true,105 value: adves,106 })107 })108 } else {109 return res.send({110 "response": false,111 "value": "user isn't admin, only admin insert, update, delete Advertise"112 });113 }114 },115 err => {116 return res.send({117 "response": false,118 "value": "find user fail"119 });120 }121 )122 } else {123 return res.send({124 "response": false,125 "value": "save image fail"126 });127 }128 });129};130exports.update_advertises = function (req, res) {131 let {_id} = req.body;132 if (req.user.phone === undefined || _id === undefined) {133 return res.send({134 "response": false,135 "value": "user not found"136 });137 }138 user.find_user_phone(req.user.phone)139 .then(user => {140 if (user.roleType === 0) {141 UpdateAdvertise({_id}, req.body).then(142 catu => {143 if (catu) {144 res.send({145 response: true,146 value: catu,147 })148 } else {149 return res.send({150 "response": false,151 "value": "update false"152 });153 }154 }, err => {155 return res.send({156 "response": false,157 "value": "update advertise fail"158 });159 }160 )161 } else {162 return res.send({163 "response": false,164 "value": "user isn't admin, only admin insert, update, delete Advertise"165 });166 }167 },168 err => {169 return res.send({170 "response": false,171 "value": "loi tim user "172 });173 }174 )175};176exports.update_advertise_image = function (req, res) {177 upload(req, res, function (err) {178 if (err) {179 return res.send({180 "response": false,181 "value": "error save image"182 });183 }184 if (req.file) {185 let {_id} = req.body;186 if (req.user.phone === undefined || _id === undefined) {187 return res.send({188 "response": false,189 "value": "user not found"190 });191 }192 user.find_user_phone(req.user.phone)193 .then(user => {194 if (user.roleType === 0) {195 let obj = req.body;196 obj.url_image = req.file.filename;197 FindOneAdvertise({_id})198 .then(advf => {199 UpdateAdvertise({_id}, obj).then(200 advup => {201 if (advup) {202 //remove icon old203 try {204 fsextra.remove(path.join(`${config.folder_uploads}`, `advertises`, `${advf.icon}`));205 console.log('success!')206 } catch (err) {207 console.error(err)208 }209 fsextra.moveSync(210 path.join(`${config.folder_temp}`, `${req.file.filename}`),211 path.join(`${config.folder_uploads}`, `advertises`, `${req.file.filename}`),212 {overwrite: true});213 res.send({214 response: true,215 value: advup,216 })217 } else {218 return res.send({219 "response": false,220 "value": "update false"221 });222 }223 }, err => {224 return res.send({225 "response": false,226 "value": "update info advertises"227 });228 }229 )230 }, err => {231 return res.send({232 "response": false,233 "value": " find advertise fail"234 });235 })236 } else {237 return res.send({238 "response": false,239 "value": "user isn't admin, only admin insert, update, delete Advertise"240 });241 }242 },243 err => {244 return res.send({245 "response": false,246 "value": "find user fail"247 });248 }249 )250 } else {251 return res.send({252 "response": false,253 "value": "save image fail"254 });255 }256 });257};258exports.delete_adver = function (req, res) {259 let {_id} = req.body;260 if (req.user.phone === undefined || _id === undefined) {261 return res.send({262 "response": false,263 "value": "user not found"264 });265 }266 user.find_user_phone(req.user.phone)267 .then(user => {268 if (user.roleType === 0) {269 DeleteOneAdvertise({_id})270 .then(advdel => {271 if (advdel) {272 res.send({273 response: true,274 value: advdel,275 })276 } else {277 return res.send({278 "response": false,279 "value": "delete false"280 });281 }282 }, err => {283 return res.send({284 "response": false,285 "value": "err delete advertises"286 });287 }288 )289 } else {290 return res.send({291 "response": false,292 "value": "user isn't admin, only admin insert, update, delete Advertise"293 });294 }295 },296 err => {297 return res.send({298 "response": false,299 "value": "find user fail",300 });301 }302 )303};304exports.list_all_advertise = function (req, res) {305 FindAllAdvertise({})306 .then(advs => {307 res.send({308 response: true,309 value: advs,310 })311 }, (err) => {312 return res.send({313 response: false,314 value: err,315 })316 });317};318exports.list_advertise_active = function (req, res) {319 FindAllAdvertise({status: 1})320 .then(advs => {321 res.send({322 response: true,323 value: advs,324 })325 }, (err) => {326 return res.send({327 response: false,328 value: err,329 })330 });...
categoryController.js
Source:categoryController.js
1'use strict';2const category = require('../models/categoryModel'),3 user = require('../controllers/userController'),4 path = require('path'),5 multer = require('multer'),6 fsextra = require('fs-extra'),7 config = require('../config');8let FindOneCategories = (obj) => {9 return new Promise((resolve, reject) => {10 category.findOne(obj, function (err, cate) {11 if (err) return reject(err);12 resolve(cate);13 });14 });15};16let UpdateCategory = (condition, Obj) => {17 return new Promise((resolve, reject) => {18 category.findOneAndUpdate(condition, Obj, {new: true}, function (err, cate) {19 if (err) reject(err);20 resolve(cate);21 });22 });23};24//delete on Cat25let DeleteOneCat = (obj) => {26 return new Promise((resolve, reject) => {27 category.findOneAndRemove(obj, function (err, cat) {28 if (err) return reject(err);29 //remove icon old30 try {31 fsextra.remove(path.join(`${config.folder_uploads}`, `categories`, `${cat.icon}`));32 resolve(cat);33 } catch (err) {34 return reject(err);35 }36 });37 });38}39let uploadDir = config.folder_temp;40let Storage = multer.diskStorage({41 destination: uploadDir,42 filename: function (req, file, callback) {43 callback(null, file.fieldname + '-' + Date.now() + ".jpg");44 }45});46/*47* function upload ảnh kiá»m tra ảnh Äá»nh dạng Äuôi có phải là png, jpg, hay jpeg48* dung lượng tá»i Äa cho phép là 6 mb49* */50let upload = multer({51 storage: Storage,52 fileFilter: function (req, file, callback) {53 let ext = path.extname(file.originalname).toLowerCase();54 if (ext !== '.png'55 && ext !== '.jpg'56 && ext !== '.jpeg'57 ) {58 return callback(new Error('Only images are allowed'))59 }60 callback(null, true)61 },62 limits: {63 fileSize: 600000064 }65}).single('icon'); //Field name and max count66exports.insert_one = function (req, res) {67 upload(req, res, function (err) {68 if (err) {69 return res.send({70 "response": false,71 "value": err72 });73 }74 if (req.file) {75 if (req.user.phone === undefined) {76 return res.send({77 "response": false,78 "value": "user not found"79 });80 }81 user.find_user_phone(req.user.phone)82 .then(user => {83 if (user.roleType === 0) {84 let newCat = new category(req.body);85 newCat.icon = req.file.filename;86 newCat.save(function (err, categories) {87 if (err) return res.send({88 response: false,89 value: err,90 });91 fsextra.moveSync(92 path.join(`${config.folder_temp}`, `${req.file.filename}`),93 path.join(`${config.folder_uploads}`, `categories`, `${req.file.filename}`),94 {overwrite: true});95 res.send({96 response: true,97 value: categories,98 })99 })100 } else {101 return res.send({102 "response": false,103 "value": "user isn't admin, only admin insert, update, delete category"104 });105 }106 },107 err => {108 return res.send({109 "response": false,110 "value": err111 });112 }113 )114 } else {115 return res.send({116 "response": false,117 "value": "save image fail"118 });119 }120 });121};122exports.update_cat = function (req, res) {123 let {_id} = req.body;124 if (req.user.phone === undefined || _id === undefined) {125 return res.send({126 "response": false,127 "value": "user not found"128 });129 }130 user.find_user_phone(req.user.phone)131 .then(user => {132 if (user.roleType === 0) {133 UpdateCategory({_id}, req.body).then(134 catu => {135 if (catu) {136 res.send({137 response: true,138 value: catu,139 })140 } else {141 return res.send({142 "response": false,143 "value": "update false"144 });145 }146 }, err => {147 return res.send({148 "response": false,149 "value": err150 });151 }152 )153 } else {154 return res.send({155 "response": false,156 "value": "user isn't admin, only admin insert, update, delete category"157 });158 }159 },160 err => {161 return res.send({162 "response": false,163 "value": "loi tim user "164 });165 }166 )167};168exports.update_cat_image = function (req, res) {169 upload(req, res, function (err) {170 if (err) {171 return res.send({172 "response": false,173 "value": err174 });175 }176 if (req.file) {177 let {_id} = req.body;178 if (req.user.phone === undefined || _id === undefined) {179 return res.send({180 "response": false,181 "value": "user not found"182 });183 }184 user.find_user_phone(req.user.phone)185 .then(user => {186 if (user.roleType === 0) {187 let obj = req.body;188 obj.icon = req.file.filename;189 FindOneCategories({_id})190 .then(catf => {191 UpdateCategory({_id}, obj).then(192 catu => {193 if (catu) {194 //remove icon old195 try {196 fsextra.remove(path.join(`${config.folder_uploads}`, `categories`, `${catf.icon}`));197 console.log('success!')198 } catch (err) {199 console.error(err)200 }201 fsextra.moveSync(202 path.join(`${config.folder_temp}`, `${req.file.filename}`),203 path.join(`${config.folder_uploads}`, `categories`, `${req.file.filename}`),204 {overwrite: true});205 res.send({206 response: true,207 value: catu,208 })209 } else {210 return res.send({211 "response": false,212 "value": "update false"213 });214 }215 }, err => {216 return res.send({217 "response": false,218 "value": err219 });220 }221 )222 }, err => {223 return res.send({224 "response": false,225 "value": err226 });227 })228 } else {229 return res.send({230 "response": false,231 "value": "user isn't admin, only admin insert, update, delete category"232 });233 }234 },235 err => {236 return res.send({237 "response": false,238 "value": err239 });240 }241 )242 } else {243 return res.send({244 "response": false,245 "value": "save image fail"246 });247 }248 });249};250exports.delete_cat = function (req, res) {251 let {_id} = req.body;252 if (req.user.phone === undefined || _id === undefined) {253 return res.send({254 "response": false,255 "value": "user not found"256 });257 }258 user.find_user_phone(req.user.phone)259 .then(user => {260 if (user.roleType === 0) {261 DeleteOneCat({_id})262 .then(catdel => {263 if (catdel) {264 res.send({265 response: true,266 value: catdel,267 })268 } else {269 return res.send({270 "response": false,271 "value": "delete false"272 });273 }274 }, err => {275 return res.send({276 "response": false,277 "value": err278 });279 }280 )281 } else {282 return res.send({283 "response": false,284 "value": "user isn't admin, only admin insert, update, delete category"285 });286 }287 },288 err => {289 return res.send({290 "response": false,291 "value": err,292 });293 }294 )295};296exports.list_categories = function (req, res) {297 category.find({}, function (err, categories) {298 if (err) return res.send({299 response: false,300 value: err,301 });302 res.send({303 response: true,304 value: categories,305 })306 }).sort({label:1})...
index.js
Source:index.js
1const Generator = require('yeoman-generator');2const chalk = require('chalk');3const yosay = require('yosay');4const initJson = require('init-package-json');5const DownloadGit = require('download-git-repo');6const path = require('path');7const fsextra = require('fs-extra');8const replaceInFile = require('replace-in-file');9const formatJson = require('format-json');10const archiveDir = 'temp';11const defaultComponentName = 'react-component-template';12const defaultGlobalComponentName = 'ReactComponentTemplate';// eslint-disable-line13let defaultPackageJson = {};14let newComponentName = '';15let newGlobalComponentName = '';// eslint-disable-line16module.exports = class extends Generator {17 initializing() {18 this.log(19 yosay(`20 Welcome to the ${chalk.red('generator-react-component-magic')} generator!21 `)22 );23 }24 async executeMethod() {25 this.log('execute start');26 // 1. ä¸è½½å
27 await this._downloadTemplate();// eslint-disable-line28 // 2. å¤å¶æå®çæ件å°å·¥ä½ç®å½ä¸29 await this._copyTemplate();// eslint-disable-line30 // 4. merge package.json31 await this._mergePackageJson();// eslint-disable-line32 // 5. 读åpackage.jsonä¿¡æ¯ï¼ä¿®æ¹æ¨¡æ¿ä¸çå ä½ç¬¦33 await this._handlePlaceHolder();// eslint-disable-line34 // å®æ¯35 }36 // 1. ä¸è½½å
37 // TODO æ¾ç¤ºä¸è½½è¿åº¦38 _downloadTemplate() {39 this.log(40 'download template from https://github.com/58-magic/react-component-template'41 );42 this.log(`${chalk.red('......')}`);43 return new Promise(resolve =>44 DownloadGit(45 'https://github.com:58-magic/react-component-template',46 archiveDir,47 err => {48 // TODO é误æè·49 err ? this.log(`${chalk.red(err)}`) : this.log('downloaded');// eslint-disable-line50 resolve();// eslint-disable-line51 }52 )53 );54 }55 // 2. å¤å¶æå®çæ件å°å·¥ä½ç®å½ä¸56 _copyTemplate() {57 this.log('copy template');58 // è®°å½é»è®¤çpackage.jsonæ°æ®59 defaultPackageJson = fsextra.readJsonSync(60 this._getFilePath(archiveDir, 'package.json')// eslint-disable-line61 );62 // å é¤æ ç¨æ件63 const deleteFileArr = ['LICENSE', 'package-lock.json', 'README.md', 'package.json'];64 deleteFileArr.forEach(name => fsextra.removeSync(this._getFilePath(archiveDir, name)));// eslint-disable-line65 // å¤å¶ï¼èªå¨å é¤äºarchiveDirç®å½66 fsextra.moveSync(this._getFilePath(archiveDir, '.'), process.cwd());// eslint-disable-line67 this.log('copy template done!');68 return Promise.resolve();69 }70 // 3. merge package.json71 _mergePackageJson() {72 this.log('init package.json');73 const initFile = path.resolve(process.env.HOME, '.npm-init');74 // the dir where we're doin stuff.75 const dir = process.cwd();76 const configData = {};77 return new Promise(resolve =>78 initJson(dir, initFile, configData, (err, data) => {79 // TODO é误æè·80 err ? this.log(`${chalk.red(err)}`) : this.log('package.json done!');// eslint-disable-line81 const config = Object.assign({}, defaultPackageJson, {82 name: data.name,83 version: data.version,84 description: data.description,85 author: data.author,86 repository: data.repository,87 bugs: data.bugs,88 homepage: data.homepage89 });90 newComponentName = config.name;91 //92 newGlobalComponentName = newComponentName93 .split('-')94 .map(letter => letter[0].toUpperCase() + letter.slice(1))95 .join('');96 fsextra.writeFileSync(97 this._getFilePath('.', 'package.json'), // eslint-disable-line98 formatJson.plain(config)99 );100 resolve();101 })102 );103 }104 // 4. ä¿®æ¹æ¨¡æ¿ä¸çå ä½ç¬¦105 _handlePlaceHolder() {106 this.log('handle placeholder');107 // TODO å¦æ¤æ§è¡æçæé«ï¼ä½é
ç½®æ¯åæ»äº108 // å¦æè¦æå±å¯ä»¥åææç´¢å
¨ç®å½ä¸çplaceholder109 const opt1 = {110 files: [111 path.join(process.cwd(), 'webpack.config.js'),112 path.join(process.cwd(), 'rollup.config.js'),113 path.join(process.cwd(), 'examples/src/app.js')114 ],115 from: new RegExp(defaultComponentName, 'g'),116 to: newComponentName117 };118 // replaceInFile(options);119 replaceInFile.sync(opt1);120 const opt2 = {121 files: path.join(process.cwd(), 'rollup.config.js'),122 from: new RegExp(defaultGlobalComponentName, 'g'),123 to: newGlobalComponentName124 };125 replaceInFile.sync(opt2);126 this.log('finish !');127 }128 // è·åæ件路å¾129 /* eslint-disable */130 _getFilePath(pathname, filename) {131 return path.join(process.cwd(), pathname, filename);132 }...
app.js
Source:app.js
1'use strict';23// Libraries4const path = require('path');5const fs = require('fs');6const fsextra = require('fs-extra')78// IBM STT init and config9const { IamAuthenticator } = require('ibm-watson/auth');10const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');11const speechToText = new SpeechToTextV1({12 authenticator: new IamAuthenticator({13 apikey: '<your-apikey>',14 }),15 serviceUrl: '<your-serviceUrl>',16});171819// MAIN function20console.log('IBM Speech to Text using NodeJS\n');21var comProtocol = 'websockets';22var audioSources = 'audios/';23console.log(`Communication protocol: ${comProtocol}`)24console.log(`Audio sources: ${audioSources}\n`)2526var audioFiles = fs.readdirSync(audioSources);27if (audioFiles.length > 0) {28 console.log('Processing files...');29 for (const i in audioFiles) {30 let audioFile = audioFiles[i];31 let audioPathfile = path.join(audioSources, audioFile);32 if (fs.lstatSync(audioPathfile).isFile()) {33 console.log(`${audioFile} was read`); 34 let params = getParams(comProtocol, audioPathfile);35 if (comProtocol == 'recognize') { 36 sttRecognize(params, audioPathfile);37 } else {38 sttWebSockets(params, audioPathfile);39 }40 }41 }42} else {43 console.log('Error: There are not files in audios/ folder')44}454647// Get STT params according with a communication protocol48function getParams(comProtocol, audioPathfile) {49 let params = {50 contentType: 'audio/mp3',51 model: 'es-CO_NarrowbandModel',52 keywords: ['grabada y monitoreada', 'términos y condiciones'],53 keywordsThreshold: 0.5,54 inactivityTimeout: -1,55 speakerLabels: true 56 };57 if (comProtocol == 'recognize') {58 params["audio"] = fs.createReadStream(audioPathfile);59 } else if (comProtocol == 'websockets') {60 params["objectMode"] = true;61 }62 return params;63}646566// Using STT Recognize67function sttRecognize(params, audioPathfile) {68 let audioFile = path.parse(audioPathfile).base;69 speechToText.recognize(params)70 .then(response => {71 let dataJSON = JSON.stringify(response.result, null, 2);72 saveJSONFile(audioFile, dataJSON);73 moveFile('audios', 'audios/read', audioFile);74 })75 .catch(err => {76 console.log(err);77 });78}798081// Using STT WebSockets82function sttWebSockets(params, audioPathfile) {83 let audioFile = path.parse(audioPathfile).base;84 const recognizeStream = speechToText.recognizeUsingWebSocket(params);85 fs.createReadStream(audioPathfile).pipe(recognizeStream);86 recognizeStream.on('data', function(event) { onEvent('Data', event, audioFile); });87 recognizeStream.on('error', function(event) { onEvent('Error', event, audioFile); });88 recognizeStream.on('close', function(event) { onEvent('Close', event, audioFile); });89}909192// Auxiliar function for STT WebSockets93function onEvent(name, event, audioFile) {94 if (name == 'Data') {95 let dataJSON = JSON.stringify(event, null, 2);96 saveJSONFile(audioFile, dataJSON);97 moveFile('audios', 'audios/read', audioFile);98 } else {99 console.log(`${name}: ${event}, recognizing ${audioFile}`);100 }101}102103104// Save JSON file with filename of audiofile105function saveJSONFile(audioFile, dataJSON) {106 let filename = audioFile.split('.').slice(0, -1).join('.');107 let jsonFile = `${filename}.json`;108 fs.writeFileSync('json/' + jsonFile, dataJSON);109 console.log(`${jsonFile} file was saved`);110}111112113// Move file114function moveFile(source, destination, file) {115 fsextra.move(`${source}/${file}`, `${destination}/${file}`, function (err) {116 if (err) {117 return console.error(err);118 }119 console.log(`${file} was moved to ${destination}/`);120 })
...
uploader.js
Source:uploader.js
1"use strict";2const SocketIOFileUploadServer = require("socketio-file-upload/server");3const Helper = require("../helper");4const path = require("path");5const fsextra = require("fs-extra");6const fs = require("fs");7const fileType = require("file-type");8const readChunk = require("read-chunk");9const crypto = require("crypto");10const isUtf8 = require("is-utf8");11const log = require("../log");12const whitelist = [13 "application/ogg",14 "audio/midi",15 "audio/mpeg",16 "audio/ogg",17 "audio/vnd.wave",18 "image/bmp",19 "image/gif",20 "image/jpeg",21 "image/png",22 "image/webp",23 "text/plain",24 "video/mp4",25 "video/ogg",26 "video/webm",27];28class Uploader {29 constructor(socket) {30 const uploader = new SocketIOFileUploadServer();31 const folder = path.join(Helper.getFileUploadPath(), ".tmp");32 fsextra.ensureDir(folder, (err) => {33 if (err) {34 log.err(`Error ensuring ${folder} exists for uploads.`);35 } else {36 uploader.dir = folder;37 }38 });39 uploader.on("complete", (data) => {40 let randomName;41 let destPath;42 // Generate a random file name for storage on disk43 do {44 randomName = crypto.randomBytes(8).toString("hex");45 destPath = path.join(Helper.getFileUploadPath(), randomName.substring(0, 2), randomName);46 } while (fs.existsSync(destPath));47 fsextra.move(data.file.pathName, destPath).then(() => {48 const slug = encodeURIComponent(path.basename(data.file.pathName));49 const url = `uploads/${randomName}/${slug}`;50 socket.emit("upload:success", url);51 }).catch(() => {52 log.warn(`Unable to move uploaded file "${data.file.pathName}"`);53 // Emit failed upload to the client if file move fails54 socket.emit("siofu_error", {55 id: data.file.id,56 message: "Unable to move uploaded file",57 });58 });59 });60 uploader.on("error", (data) => {61 log.error(`File upload failed: ${data.error}`);62 });63 // maxFileSize is in bytes, but config option is passed in as KB64 uploader.maxFileSize = Uploader.getMaxFileSize();65 uploader.listen(socket);66 }67 static isValidType(mimeType) {68 return whitelist.includes(mimeType);69 }70 static router(express) {71 express.get("/uploads/:name/:slug*?", (req, res) => {72 const name = req.params.name;73 const nameRegex = /^[0-9a-f]{16}$/;74 if (!nameRegex.test(name)) {75 return res.status(404).send("Not found");76 }77 const folder = name.substring(0, 2);78 const uploadPath = Helper.getFileUploadPath();79 const filePath = path.join(uploadPath, folder, name);80 const type = Uploader.getFileType(filePath);81 const mimeType = type || "application/octet-stream";82 const contentDisposition = Uploader.isValidType(type) ? "inline" : "attachment";83 // doesn't exist84 if (type === undefined) {85 return res.status(404).send("Not found");86 }87 res.setHeader("Content-Disposition", contentDisposition);88 res.setHeader("Cache-Control", "max-age=86400");89 res.contentType(mimeType);90 return res.sendFile(filePath);91 });92 }93 static getMaxFileSize() {94 const configOption = Helper.config.fileUpload.maxFileSize;95 if (configOption === -1) { // no file size limit96 return null;97 }98 return configOption * 1024;99 }100 static getFileType(filePath) {101 let buffer;102 let type;103 try {104 buffer = readChunk.sync(filePath, 0, fileType.minimumBytes);105 } catch (e) {106 if (e.code === "ENOENT") { // doesn't exist107 return;108 }109 log.warn(`Failed to read ${filePath}`);110 return;111 }112 // returns {ext, mime} if found, null if not.113 const file = fileType(buffer);114 if (file) {115 type = file.mime;116 } else if (isUtf8(buffer)) {117 type = "text/plain";118 }119 return type;120 }121}...
fs-extra.js
Source:fs-extra.js
1var fsextra = require('fs-extra');2//åªé¤æå
§å®¹çç®é3fsextra.remove('./test',function(err){4 if(err){5 console.error(err);6 return;7 }8 console.log('Renamed');9});10//æ¬ç§»æªæ¡11fsextra.move('./test/test.js','./test1/demo.js',function(err){12 if(err){13 console.error(err);14 }15 console.log('Moved');16});17//æ¬ç§»ä¸è¦èç®æ¨è·¯å¾18fsextra.move('./test/test.js','./test1/demo.js',{clobber : true},function(err){19 if(err){20 console.error(err);21 return;22 }23 console.log('Moved');24});25//è¤è£½æªæ¡26fsextra.copy('./test/test.js','./test1/demo.js',function(err){27 if(err){28 console.error(err);29 return;30 }31 console.log('Copied');...
Using AI Code Generation
1const fsExtra = require('fs-extra');2const path = require('path');3const src = path.join(__dirname, 'test.txt');4const dest = path.join(__dirname, 'test', 'test.txt');5fsExtra.move(src, dest, { overwrite: true }, (err) => {6 if (err) return console.error(err);7 console.log('success!');8});9describe('test file move', () => {10 it('should move the file', () => {11 cy.exec('node test.js');12 });13});
Using AI Code Generation
1const fsExtra = require('fs-extra')2fsExtra.move('cypress/integration/MyTest.spec.js', 'cypress/integration/MyTest2.spec.js', {overwrite: true}, err => {3 if (err) return console.error(err)4 console.log('success!')5})6{7}8{9 "scripts": {10 }11}12describe('My Test', () => {13 it('does something', () => {14 expect(true).to.equal(true)15 })16})17const fsExtra = require('fs-extra')18fsExtra.move('cypress/integration/MyTest.spec.js', 'cypress/integration/MyTest2.spec.js', {overwrite: true}, err => {19 if (err) return console.error(err)20 console.log('success!')21})22{23}24{25 "scripts": {26 }27}28describe('My Test', () => {29 it('does something', () => {30 expect(true).to.equal(true)31 })32})
Using AI Code Generation
1const fs = require('fs-extra')2fs.move('test.txt', 'cypress/fixtures/test.txt', { overwrite: true })3 .then(() => console.log('success!'))4 .catch(err => console.error(err))5describe('My First Test', () => {6 it('Does not do much!', () => {7 cy.contains('type').click()8 cy.url().should('include', '/commands/actions')9 cy.get('.action-email')10 .type('
Using AI Code Generation
1describe('Test', function() {2 it('Test', function() {3 cy.task('moveFile', { src: 'cypress/fixtures/test.txt', dest: 'cypress/fixtures/test/test.txt' })4 })5})6const fsExtra = require('fs-extra')7module.exports = (on, config) => {8 on('task', {9 moveFile({ src, dest }) {10 return fsExtra.move(src, dest)11 }12 })13}14const fsExtra = require('fs-extra')15describe('Test', function() {16 it('Test', function() {17 fsExtra.move('cypress/fixtures/test.txt', 'cypress/fixtures/test/test.txt')18 })19})
Using AI Code Generation
1describe('Test', () => {2 it('Test', () => {3 cy.task('moveFile', {from: 'cypress/fixtures/test.txt', to: 'cypress/fixtures/test.txt'});4 });5});6const fsExtra = require('fs-extra');7module.exports = (on, config) => {8 on('task', {9 moveFile({from, to}) {10 fsExtra.move(from, to)11 .then(() => {12 return null;13 })14 .catch(err => {15 return err;16 });17 }18 });19};
Using AI Code Generation
1const fsExtra = require('fs-extra');2fsExtra.move('cypress/screenshots/test.js/test.js -- should -- test -- 1.png', 'cypress/screenshots/test.js/test.js -- should -- test -- 1.png', { overwrite: true })3.then(() => {4console.log('success!')5}).catch(err => {6console.error(err)7})
Using AI Code Generation
1describe('Cypress fsExtra.move', () => {2 it('should move a file', () => {3 cy.task('moveFile', {from: 'cypress/fixtures/someFile.txt', to: 'cypress/fixtures/someFile2.txt'})4 })5})6const fsExtra = require('fs-extra')7module.exports = (on, config) => {8 on('task', {9 moveFile({from, to}) {10 return fsExtra.move(from, to)11 }12 })13}14require('cypress-plugin-snapshots/commands')15Cypress.Commands.add('getBySel', (selector, ...args) => {16 return cy.get(`[data-test=${selector}]`, ...args)17})18Cypress.Commands.add('getBySelLike', (selector, ...args) => {19 return cy.get(`[data-test*=${selector}]`, ...args)20})21Cypress.Commands.add('getBySelLike', (selector, ...args) => {22 return cy.get(`[data-test*=${selector}]`, ...args)23})24Cypress.Commands.add('getBySelLike', (selector, ...args) => {25 return cy.get(`[data-test*=${selector}]`, ...args)26})27Cypress.Commands.add('getBySelLike', (selector, ...args) => {28 return cy.get(`[data-test*=${selector}]`, ...args)29})30Cypress.Commands.add('getBySelLike', (selector, ...args) => {31 return cy.get(`[data-test*=${selector}]`, ...args)32})33Cypress.Commands.add('getBySelLike', (selector, ...args) => {34 return cy.get(`[data-test*=${selector}]`, ...args)35})36Cypress.Commands.add('getBySelLike', (selector, ...args) => {37 return cy.get(`[data-test*=${selector}]`, ...args)38})
Using AI Code Generation
1import { move } from "fs-extra";2describe("test", () => {3 it("test", () => {4 cy.task("moveFile", "testFile.txt").then(() => {5 cy.readFile("cypress/fixtures/testFile.txt").then((file) => {6 expect(file).to.equal("test");7 });8 });9 });10});11const fs = require("fs-extra");12const path = require("path");13module.exports = (on, config) => {14 on("task", {15 moveFile(fileName) {16 const filePath = path.join(__dirname, `../${fileName}`);17 const destination = path.join(__dirname, `../fixtures/${fileName}`);18 return fs.move(filePath, destination);19 },20 });21};22{23}24{25 "scripts": {26 },27 "devDependencies": {28 }29}
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!