Best JavaScript code snippet using apickli
auth.js
Source:auth.js
1const express = require('express');2const jwt = require('jsonwebtoken');3const authHelpers = require('../auth/_helpers');4const passportLocal = require('../auth/local');5const passportJWT = require('../auth/jwt');6const router = express.Router();7router.post(8 '/register',9 authHelpers.loginRedirect,10 authHelpers.createUser,11 (req, res, next) => {12 passportLocal.authenticate('local', (_error, user) => {13 if (user) {14 const payload = {15 id: user.id,16 };17 const token = jwt.sign(payload, process.env.JWT_SECRET, {18 expiresIn: '30d',19 });20 const responseBody = {21 statusCode: 200,22 statusMessage: 'Successfully registered user',23 data: {24 token,25 user,26 },27 };28 return res.status(responseBody.statusCode).json(responseBody);29 }30 const responseBody = {31 statusCode: 500,32 statusMessage: 'Error while registering user',33 };34 return res.status(responseBody.statusCode).json(responseBody);35 })(req, res, next);36 }37);38router.post('/login', authHelpers.loginRedirect, (req, res, next) => {39 // eslint-disable-next-line consistent-return40 passportLocal.authenticate('local', (err, user) => {41 if (err) {42 const responseBody = {43 statusCode: 500,44 statusMessage: 'Error logging in user',45 data: err,46 };47 return res.status(responseBody.statusCode).json(responseBody);48 }49 if (!user) {50 const responseBody = {51 statusCode: 403,52 statusMessage: 'User not found',53 data: {},54 };55 return res.status(responseBody.statusCode).json(responseBody);56 }57 if (user) {58 req.logIn(user, error => {59 if (error) {60 const responseBody = {61 statusCode: 500,62 statusMessage: 'Error logging in user at request',63 data: {},64 };65 return res.status(responseBody.statusCode).json(responseBody);66 }67 const payload = {68 id: user.id,69 };70 const token = jwt.sign(payload, process.env.JWT_SECRET, {71 expiresIn: '24h',72 });73 const responseBody = {74 statusCode: 200,75 statusMessage: 'Successfully logged in user',76 data: {77 token,78 user,79 },80 };81 return res.status(responseBody.statusCode).json(responseBody);82 });83 }84 })(req, res, next);85});86router.post('/adminlogin', authHelpers.loginRedirect, (req, res, next) => {87 // eslint-disable-next-line consistent-return88 passportLocal.authenticate('local', (err, user) => {89 if (err) {90 const responseBody = {91 statusCode: 500,92 statusMessage: 'Error logging in user',93 data: err,94 };95 return res.status(responseBody.statusCode).json(responseBody);96 }97 if (!user) {98 const responseBody = {99 statusCode: 403,100 statusMessage: 'User not found',101 data: {},102 };103 return res.status(responseBody.statusCode).json(responseBody);104 }105 if (user) {106 req.logIn(user, error => {107 if (error) {108 const responseBody = {109 statusCode: 500,110 statusMessage: 'Error logging in user at request',111 data: {},112 };113 return res.status(responseBody.statusCode).json(responseBody);114 }115 if(user.role != 1)116 {117 const responseBody = {118 statusCode: 500,119 statusMessage: 'Not Admin User Error',120 data: {},121 };122 return res.status(responseBody.statusCode).json(responseBody);123 }124 const payload = {125 id: user.id,126 };127 const token = jwt.sign(payload, process.env.JWT_SECRET, {128 expiresIn: '24h',129 });130 const responseBody = {131 statusCode: 200,132 statusMessage: 'Successfully logged in user',133 data: {134 token,135 user,136 },137 };138 return res.status(responseBody.statusCode).json(responseBody);139 });140 }141 })(req, res, next);142});143router.get('/logout', passportJWT.authenticate('jwt'), (req, res) => {144 req.logout();145 const responseBody = {146 statusCode: 200,147 statusMessage: 'Logout success',148 data: {},149 };150 return res.status(responseBody.statusCode).json(responseBody);151});152router.post('/forgot', (req, res) => {153 authHelpers154 .forgotPassword(req, res)155 // eslint-disable-next-line consistent-return156 .then(response => {157 if (response) {158 const responseBody = {159 statusCode: 200,160 statusMessage: 'Successfully sent password reset for user',161 data: response,162 };163 return res.status(responseBody.statusCode).json(responseBody);164 }165 })166 .catch(error => {167 const responseBody = {168 statusCode: 500,169 statusMessage: error.message,170 data: error,171 };172 return res.status(responseBody.statusCode).json(responseBody);173 });174});175router.post('/reset', (req, res) => {176 authHelpers177 .resetPassword(req, res)178 // eslint-disable-next-line consistent-return179 .then(response => {180 if (response) {181 const responseBody = {182 statusCode: 200,183 statusMessage: 'Successfully changed password for user',184 data: response,185 };186 return res.status(responseBody.statusCode).json(responseBody);187 }188 })189 .catch(error => {190 const responseBody = {191 statusCode: 500,192 statusMessage: error.message,193 data: error,194 };195 return res.status(responseBody.statusCode).json(responseBody);196 });197});198router.post('/verify', (req, res) => {199 jwt.verify(req.body.token, process.env.JWT_SECRET, (err, decoded) => {200 if (decoded) {201 const responseBody = {202 statusCode: 200,203 statusMessage: 'Successfully verified jwt',204 data: decoded,205 };206 return res.status(responseBody.statusCode).json(responseBody);207 }208 const responseBody = {209 statusCode: 500,210 statusMessage: 'Error verifing jwt',211 data: err,212 };213 return res.status(responseBody.statusCode).json(responseBody);214 });215});...
User.service.js
Source:User.service.js
1const bcrypt = require('bcryptjs');23const User = require('../models/User.model');4const { request: requestUtility } = require('../libs/utilities');5const mongoose = require('mongoose');67class UserService {8 async createUser(request) {9 const responseBody = {};10 11 try {12 if (!mongoose.connection.readyState) {13 throw new Error();14 }15 16 if (!request.body) {17 responseBody.statusCode = 422;18 responseBody.data = {19 errors: { default: ['No data sent with request.'] },20 };21 22 return responseBody;23 }24 25 const full_name = `${request.body.first_name} ${request.body.last_name}`;26 const userData = {...request.body, full_name};2728 const isUserFound = await User.findOne({ 'email': request.body.email });2930 if (isUserFound) {31 responseBody.statusCode = 409;32 responseBody.data = {33 errors: { default: ['There was an error creating user. Please try again.'] },34 };35 36 return responseBody;37 }3839 const encryptedPassword = await this.encryptPassword(request.body.password);40 userData.password = encryptedPassword;4142 const user = await User.create(userData);43 const token = requestUtility.signToken(user._id, request.body.email);44 45 user.token = token;4647 responseBody.statusCode = 201;48 responseBody.data = {49 email: user.email,50 first_name: user.first_name,51 full_name: user.full_name,52 id: user._id,53 last_name: user.last_name,54 token: user.token,55 };56 } catch (error) {57 responseBody.statusCode = 500;58 responseBody.data = {59 errors: { default: ['There was an error creating user. Please try again.'] },60 };61 } finally {62 return responseBody;63 }64 }6566 async encryptPassword(password) {67 if (!password) {68 throw new Error('No password provided.');69 }7071 return await bcrypt.hash(password, 10);72 }7374 async deleteUser(id) {75 const responseBody = {};7677 try {78 const isUserFound = await User.findById(id);7980 if (!isUserFound) {81 responseBody.statusCode = 404;82 responseBody.data = {83 errors: { default: ['Could not find user to delete.'] },84 };8586 return responseBody;87 }8889 await User.deleteOne({ _id: id });9091 responseBody.statusCode = 200;92 responseBody.data = {93 message: 'Successfully deleted user.',94 };95 } catch (error) {96 responseBody.statusCode = 500;97 responseBody.data = {98 errors: { default: ['The server encountered an error.'] },99 };100 }101102 return responseBody;103 }104 105 async getAllUsers() {106 const responseBody = {};107108 try {109 const result = await User.find();110 111 responseBody.statusCode = 200;112 responseBody.data = result;113 } catch (error) {114 responseBody.statusCode = 500;115 responseBody.data = {116 errors: { default: ['There was an error getting users. Please try again.'] },117 };118 }119120 return responseBody;121 }122123 async getUser(id) {124 const responseBody = {};125126 try {127 const result = await User.findById(id);128 129 if (!result) {130 responseBody.statusCode = 404;131 responseBody.data = {132 errors: { default: ['Could not get user information. Please try again.'] },133 };134135 return responseBody;136 }137 138 responseBody.statusCode = 200;139 responseBody.data = result;140 } catch (error) {141 responseBody.statusCode = 500;142 responseBody.data = {143 errors: { default: ['Could not get user information. Please try again.'] },144 };145 }146147 return responseBody;148 }149 150 async updateUser(request) {151 const responseBody = {};152153 try {154 const isUserFound = await User.findById(request.params.id);155156 if (!isUserFound) {157 responseBody.statusCode = 404;158 responseBody.data = {159 errors: { default: ['Could not find a user with the provided id.'] },160 };161162 return responseBody;163 }164165 const result = await User.findByIdAndUpdate(request.params.id, request.body, { new: true });166167 if (!result) {168 responseBody.statusCode = 500;169 responseBody.data = {170 errors: { default: ['Could not update user information. Please try again.'] },171 };172173 return responseBody;174 }175 176 responseBody.statusCode = 200;177 responseBody.data = result;178 } catch (error) {179 responseBody.statusCode = 500;180 responseBody.data = {181 errors: { default: ['Could not update user information. Please try again.'] },182 };183 }184185 return responseBody;186 }187}188
...
Auth.service.js
Source:Auth.service.js
1const bcrypt = require('bcryptjs');2const jwt = require('jsonwebtoken');34const UserModel = require('../models/User.model');5const { JWT_SECRET } = require('../config');67class AuthService {8 constructor() {9 this.passwordExpiry = '2 minutes';10 }1112 async login(request, isTest = false) {13 const responseBody = {};1415 try {16 if (isTest) {17 throw new Error('Testing error handling.');18 }1920 if (!request.body.password) {21 responseBody.statusCode = 422;22 responseBody.errors = {23 default: ['Invalid credentials.'],24 };2526 return responseBody;27 }2829 const user = await UserModel.findOne({ email: request.body.email });3031 if (!user) {32 responseBody.statusCode = 422;33 responseBody.errors = {34 default: ['Invalid credentials.'],35 };3637 return responseBody;38 }3940 const isPasswordCorrect = await bcrypt.compare(request.body.password, user.password);4142 if (!isPasswordCorrect) {43 responseBody.statusCode = 422;44 responseBody.errors = {45 default: ['Invalid credentials.'],46 };4748 return responseBody;49 }5051 const token = this.signToken(user._id, request.body.email);52 53 user.token = token;5455 responseBody.statusCode = 200;56 responseBody.data = {57 email: user.email,58 first_name: user.first_name,59 full_name: user.full_name,60 last_name: user.last_name,61 token: user.token62 };63 } catch (error) {64 responseBody.statusCode = 500;65 responseBody.errors = {66 default: ['There was an issue connecting to the server. Please wait a moment and try again.'],67 };68 }6970 return responseBody;71 }7273 signToken(user_id, email) {74 return jwt.sign(75 { user_id, email },76 JWT_SECRET,77 { expiresIn: this.passwordExpiry }78 );79 }80 81 async validate(request, isTest = false) {82 const responseBody = {};8384 try {85 if (isTest) {86 throw new Error('Testing error handling.');87 }8889 responseBody.statusCode = 200;90 responseBody.data = {91 token: request.user.token,92 };93 } catch (error) {94 responseBody.statusCode = 500;95 responseBody.errors = {96 default: ['There was an issue connecting to the server. Please wait a moment and try again.'],97 };98 }99100 return responseBody;101 }102}103
...
Using AI Code Generation
1var apickli = require('apickli');2var myApickli = new apickli.Apickli('http', 'httpbin.org');3myApickli.get('/ip', function (error, response) {4 if (error) {5 console.log(error);6 } else {7 console.log(myApickli.responseBody);8 }9});10{ "origin": "xx.xx.xx.xx" }11var apickli = require('apickli');12var myApickli = new apickli.Apickli('http', 'httpbin.org');13myApickli.get('/ip', function (error, response) {14 if (error) {15 console.log(error);16 } else {17 console.log(myApickli.responseBodyAsJson);18 }19});20{ origin: 'xx.xx.xx.xx' }21var apickli = require('apickli');22var myApickli = new apickli.Apickli('http', 'httpbin.org');23myApickli.get('/ip', function (error, response) {24 if (error) {25 console.log(error);26 } else {27 console.log(myApickli.getResponseHeader('Content-Type'));28 }29});
Using AI Code Generation
1var apickli = require('apickli');2var myApickli = new apickli.Apickli('http', 'localhost:8080');3myApickli.addRequestHeader('Content-Type', 'application/json');4myApickli.addRequestHeader('Accept', 'application/json');5 myApickli.assertResponseCode(200);6 console.log(myApickli.getResponseBody());7});
Using AI Code Generation
1var apickli = require('apickli');2var {defineSupportCode} = require('cucumber');3var apickli = new apickli.Apickli('http', 'localhost:8000');4defineSupportCode(function({When, Then}) {5 When('I set the request body to:', function (string, callback) {6 this.apickli.setRequestBody(string);7 callback(null, 'pending');8 });9 Then('the response body should be:', function (string, callback) {10 this.apickli.assertResponseBody(string);11 callback(null, 'pending');12 });13});14var apickli = require('apickli');15var {defineSupportCode} = require('cucumber');16defineSupportCode(function({When, Then}) {17 When('I set the request body to:', function (string, callback) {18 this.apickli.setRequestBody(string);19 callback(null, 'pending');20 });21 Then('the response body should be:', function (string, callback) {22 this.apickli.assertResponseBody(string);23 callback(null, 'pending');24 });25});26var apickli = require('apickli');27var {defineSupportCode} = require('cucumber');28defineSupportCode(function({When, Then}) {29 When('I set the request body to:', function (string, callback) {30 this.apickli.setRequestBody(string);31 callback(null, 'pending');32 });33 Then('the response body should be:', function (string, callback) {34 this.apickli.assertResponseBody(string);35 callback(null, 'pending');36 });37});
Using AI Code Generation
1var apickli = require('apickli');2var {defineSupportCode} = require('cucumber');3defineSupportCode(function({Given, When, Then}) {4 Given('I have a variable set to {stringInDoubleQuotes}', function (variable, callback) {5 this.apickli.storeValueInScenarioScope(variable, 'foo');6 callback();7 });8 When('I set a request header {stringInDoubleQuotes} to the variable {stringInDoubleQuotes}', function (header, variable, callback) {9 this.apickli.addRequestHeader(header, this.apickli.getVariableValue(variable));10 callback();11 });12 Then('the response header {stringInDoubleQuotes} should be the variable {stringInDoubleQuotes}', function (header, variable, callback) {13 this.apickli.assertResponseContainsHeader(header, this.apickli.getVariableValue(variable));14 callback();15 });16 Then('the response body should contain the variable {stringInDoubleQuotes}', function (variable, callback) {17 this.apickli.assertResponseBodyContains(this.apickli.getVariableValue(variable));18 callback();19 });20});
Using AI Code Generation
1var apickli = require('apickli');2var {Given, Then, When} = require('cucumber');3var chai = require('chai');4var expect = chai.expect;5module.exports = function() {6 this.Before(function(callback) {7 this.apickli = new apickli.Apickli('http', 'httpbin.org');8 this.apickli.addRequestHeader('Content-Type', 'application/json');9 callback();10 });11 this.Given(/^I have a valid request body$/, function(callback) {12 this.apickli.storeValueInScenarioScope('requestBody', '{"name":"John"}');13 callback();14 });15 this.When(/^I send the request$/, function(callback) {16 this.apickli.post('/post', this.apickli.getVariableValue('requestBody'), callback);17 });18 this.Then(/^I get the response$/, function(callback) {19 expect(this.apickli.getResponseObject()).to.not.be.null;20 callback();21 });22 this.Then(/^I get the response body$/, function(callback) {23 expect(this.apickli.responseBody).to.not.be.null;24 callback();25 });26};271 scenario (1 passed)284 steps (4 passed)
Using AI Code Generation
1var apickli = require('apickli');2var assert = require('assert');3module.exports = function () {4 this.Given(/^I have a test api$/, function (callback) {5 callback(null, 'pending');6 });7 this.When(/^I call the test api$/, function (callback) {8 });9 this.Then(/^I should get a response$/, function (callback) {10 assert.equal(this.apickli.responseBody, 'Google');11 callback();12 });13};
Using AI Code Generation
1var apickli = require('apickli');2module.exports = function() {3 this.Given(/^I have a request body$/, function(next) {4 var requestBody = {5 };6 this.apickli.storeValueInScenarioScope('requestBody', requestBody);7 next();8 });9 this.When(/^I send a POST request to "([^"]*)"$/, function(path, next) {10 var requestBody = this.apickli.getScenarioVariable('requestBody');11 this.apickli.setRequestBody(JSON.stringify(requestBody));12 this.apickli.post(path, next);13 });14 this.Then(/^the response code should be (\d+)$/, function(statusCode, next) {15 this.apickli.assertResponseCode(statusCode);16 next();17 });18 this.Then(/^response body should contain "([^"]*)"$/, function(expectedBody, next) {19 var responseBody = this.apickli.getResponseBody();20 this.apickli.assertContains(responseBody, expectedBody);21 next();22 });23};
Using AI Code Generation
1var response = apickli.getResponseBody();2var value = apickli.getResponseBodyObject().property;3var response = apickli.getResponseBody();4var value = apickli.getResponseBodyObject().property;5var response = apickli.getResponseBody();6var value = apickli.getResponseBodyObject().property;7var response = apickli.getResponseBody();8var value = apickli.getResponseBodyObject().property;9var response = apickli.getResponseBody();10var value = apickli.getResponseBodyObject().property;11var response = apickli.getResponseBody();12var value = apickli.getResponseBodyObject().property;13var response = apickli.getResponseBody();14var value = apickli.getResponseBodyObject().property;15var response = apickli.getResponseBody();16var value = apickli.getResponseBodyObject().property;17var response = apickli.getResponseBody();18var value = apickli.getResponseBodyObject().property;19var response = apickli.getResponseBody();20var value = apickli.getResponseBodyObject().property;21var response = apickli.getResponseBody();22var value = apickli.getResponseBodyObject().property;23var response = apickli.getResponseBody();24var value = apickli.getResponseBodyObject().property;
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!!