Best JavaScript code snippet using ava
request.js
Source: request.js
1import axios from 'axios';2import moment from 'moment';3import { history } from 'react-router-dom';4import { stringify, parse } from 'qs';5import { notification } from 'antd';6import jsCookie from 'js-cookie';7import { startURL } from '../config/constant';8import store, { storeKeys } from './persistent-store';9let refreshTimeout;10let lastAccessTime;11export const baseURL = '/api';12export const contentType = {13 form: 'application/x-www-form-urlencoded',14 json: 'application/json',15};16export const headerKeys = {17 ContentType: 'Content-Type',18 Authorization: 'Authorization',19};20export const methods = {21 GET: 'GET',22 POST: 'POST',23 PUT: 'PUT',24 DELETE: 'DELETE',25 PATCH: 'PATCH',26 HEAD: 'HEAD',27 OPTIONS: 'OPTIONS',28};29// Get access token30export function getAccessToken() {31 const token = store.get(storeKeys.AccessToken);32 if (!token) {33 return '';34 }35 return token.access_token;36}37// Wrap the URL with the token38export function wrapURLWithToken(url) {39 const ss = url.split('?');40 const query = parse(ss[1]);41 query.accessToken = getAccessToken();42 return `${ss[0]}?${stringify(query)}`;43}44// ç»åº45export function logout() {46 console.log('Logout event');47 if (refreshTimeout) {48 clearTimeout(refreshTimeout);49 }50 //binhnt: Remove cookie51 jsCookie.remove('token');52 //Remove AccessToken53 store.remove(storeKeys.AccessToken);54 window.location = '#/login'55 // const { redirect } = parse(window.location.href.split('?')[1]);56 console.log("binhnt.request.logout: redirect = ", startURL)57 // if (window.location.pathname !== startURL + '/login' && !redirect) {58 // window.location = startURL + '/login';59 // window.history.replace({60 // pathname: '/user/login',61 // search: stringify({62 // redirect: window.location.href,63 // }),64 // });65 // }66}67// request æ¦æªå¨68function requestInterceptors(c) {69 const config = { ...c };70 const token = store.get(storeKeys.AccessToken);71 if (token) {72 // console.log(73 // 'binhnt.requestInterceptors: Token = ',74 // token.access_token,75 // headerKeys.Authorization76 // );77 config.headers[headerKeys.Authorization] = `${token.token_type} ${token.access_token}`;78 }79 return config;80}81// ajax请æ±82export default function request(url, options = {}) {83 // console.log('AccessToken: ', storeKeys.AccessToken);84 const oldToken = store.get(storeKeys.AccessToken);85 console.log("oldToken: ", oldToken);86 if (oldToken && oldToken.expires_at - lastAccessTime <= 0) {87 if (refreshTimeout) {88 clearTimeout(refreshTimeout);89 }90 console.log("binhnt.request: out of access time ")91 logout();92 // eslint-disable-next-line compat/compat93 return Promise.reject(new Error('The token has expired'));94 }95 lastAccessTime = moment().unix();96 const opts = { ...options };97 let showNotify = true;98 if (opts.hideNotify) {99 showNotify = false;100 delete opts.hideNotify;101 }102 const config = {103 method: methods.GET,104 baseURL,105 headers: {},106 transformRequest: (data, headers) => {107 switch (headers[headerKeys.ContentType]) {108 case contentType.json:109 return JSON.stringify(data);110 case contentType.form:111 return stringify(data);112 default:113 return data;114 }115 },116 paramsSerializer: params => {117 return stringify(params);118 },119 timeout: 60000,120 ...opts,121 };122 if (123 !(config.headers && config.headers[headerKeys.ContentType]) &&124 [methods.POST, methods.PUT, methods.PATCH].indexOf(config.method) > -1125 ) {126 config.headers[headerKeys.ContentType] = contentType.json;127 }128 const instance = axios.create(config);129 instance.interceptors.request.use(requestInterceptors);130 return instance131 .request({ url })132 .then(res => {133 const { data } = res;134 // console.log('request.request: Data: ', data, 'url', url);135 return data;136 })137 .catch(error => {138 const { response } = error;139 const { status, data } = response;140 if (status === 401 && data.error && data.error.code === 9999) {141 logout();142 return response;143 }144 if (showNotify) {145 let msg = 'Request error';146 if (status === 504) {147 msg = 'Not connected to server';148 } else if (data && data.error) {149 msg = data.error.message;150 }151 notification.error({152 message: `${config.baseURL}${url}`,153 description: msg,154 });155 }156 return response;157 });158}159// Put in the access token160export function setToken(token) {161 //binhnt: 1. Add cookies to access nextjs162 jsCookie.set('token', token.access_token);163 //binhnt: 2. Add Token to access Backend164 console.log("Set access token = ", token.expires_at)165 lastAccessTime = moment().unix();166 store.set(storeKeys.AccessToken, token);167 if (refreshTimeout) {168 clearTimeout(refreshTimeout);169 }170 // Renew the token 10 minutes in advance171 const timeout = token.expires_at - moment().unix() - 10;172 if (timeout > 0) {173 refreshTimeout = setTimeout(() => {174 const oldToken = store.get(storeKeys.AccessToken);175 if (oldToken && oldToken.expires_at - lastAccessTime <= 0) {176 if (refreshTimeout) {177 clearTimeout(refreshTimeout);178 }179 return;180 }181 request('/v1/pub/refresh-token', {182 method: methods.POST,183 }).then(res => {184 setToken(res);185 });186 }, timeout * 1000);187 }...
request_cms.js
Source: request_cms.js
1import axios from 'axios';2import moment from 'moment';3import { history } from 'react-router-dom';4import { stringify, parse } from 'qs';5import { notification } from 'antd';6import store, { storeKeys } from './persistent-store';7let refreshTimeout;8let lastAccessTime;9export const baseURL = '/cms';10export const contentType = {11 form: 'application/x-www-form-urlencoded',12 json: 'application/json',13};14export const headerKeys = {15 ContentType: 'Content-Type',16 Authorization: 'Authorization',17};18export const methods = {19 GET: 'GET',20 POST: 'POST',21 PUT: 'PUT',22 DELETE: 'DELETE',23 PATCH: 'PATCH',24 HEAD: 'HEAD',25 OPTIONS: 'OPTIONS',26};27// Get access token28export function getAccessToken() {29 const token = store.get(storeKeys.AccessToken);30 if (!token) {31 return '';32 }33 return token.access_token;34 return '';35}36// Wrap the URL with the token37export function wrapURLWithToken(url) {38 const ss = url.split('?');39 const query = parse(ss[1]);40 query.accessToken = getAccessToken();41 return `${ss[0]}?${stringify(query)}`;42}43// Sign out44export function logout() {45 if (refreshTimeout) {46 clearTimeout(refreshTimeout);47 }48 store.remove(storeKeys.AccessToken);49 const { redirect } = parse(window.location.href.split('?')[1]);50 if (window.location.pathname !== '/login' && !redirect) {51 window.location = '/login';52 // window.history.replace({53 // pathname: '/user/login',54 // search: stringify({55 // redirect: window.location.href,56 // }),57 // });58 }59}60// request Interceptor61function requestInterceptors(c) {62 const config = { ...c };63 const token = store.get(storeKeys.AccessToken);64 if (token) {65 config.headers[headerKeys.Authorization] = `${token.token_type} ${token.access_token}`;66 }67 return config;68}69// ajax request70export default function request(url, options = {}) {71 // console.log('request_cms.request: AccessToken: ', storeKeys.AccessToken);72 const oldToken = store.get(storeKeys.AccessToken);73 // console.log("oldToken: ", oldToken);74 if (oldToken && oldToken.expires_at - lastAccessTime <= 0) {75 if (refreshTimeout) {76 clearTimeout(refreshTimeout);77 }78 logout();79 // eslint-disable-next-line compat/compat80 return Promise.reject(new Error('The token has expired'));81 }82 lastAccessTime = moment().unix();83 const opts = { ...options };84 let showNotify = true;85 if (opts.hideNotify) {86 showNotify = false;87 delete opts.hideNotify;88 }89 const config = {90 method: methods.GET,91 baseURL,92 headers: {},93 transformRequest: (data, headers) => {94 switch (headers[headerKeys.ContentType]) {95 case contentType.json:96 return JSON.stringify(data);97 case contentType.form:98 return stringify(data);99 default:100 return data;101 }102 },103 paramsSerializer: params => {104 return stringify(params);105 },106 timeout: 60000,107 ...opts,108 };109 if (110 !(config.headers && config.headers[headerKeys.ContentType]) &&111 [methods.POST, methods.PUT, methods.PATCH].indexOf(config.method) > -1112 ) {113 config.headers[headerKeys.ContentType] = contentType.json;114 }115 const instance = axios.create(config);116 instance.interceptors.request.use(requestInterceptors);117 return instance118 .request({ url })119 .then(res => {120 const { data } = res;121 // console.log('request_cms.request: Data', data);122 return data;123 })124 .catch(error => {125 const { response } = error;126 const { status, data } = response;127 if (status === 401 && data.error && data.error.code === 9999) {128 logout();129 return response;130 }131 if (showNotify) {132 let msg = 'Request error';133 if (status === 504) {134 msg = 'Not connected to server';135 } else if (data && data.error) {136 msg = data.error.message;137 }138 notification.error({139 message: `${config.baseURL}${url}`,140 description: msg,141 });142 }143 return response;144 });145}146// Put in the access token147export function setToken(token) {148 lastAccessTime = token.expires_at;149 store.set(storeKeys.AccessToken, token);150 if (refreshTimeout) {151 clearTimeout(refreshTimeout);152 }153 // Renew the token 10 minutes in advance154 const timeout = token.expires_at - moment().unix() - 10;155 if (timeout > 0) {156 refreshTimeout = setTimeout(() => {157 const oldToken = store.get(storeKeys.AccessToken);158 if (oldToken && oldToken.expires_at - lastAccessTime <= 0) {159 if (refreshTimeout) {160 clearTimeout(refreshTimeout);161 }162 return;163 }164 request('/v1/pub/refresh-token', {165 method: methods.POST,166 }).then(res => {167 setToken(res);168 });169 }, timeout * 1000);170 }...
index.js
Source: index.js
1/* eslint-disable no-undef */2import EventEmitter from './EventEmitter';3export default class TokenManagement {4 event = null;5 isRefreshing = false;6 refreshTimeout = 3000;7 constructor({ isTokenValid, getAccessToken, onRefreshToken, refreshTimeout = 3000 }) {8 const event = new EventEmitter();9 this.refreshTimeout = refreshTimeout;10 event.on('refresh', () => {11 (async () => {12 try {13 const token = await getAccessToken();14 if (isTokenValid(token)) {15 event.emit('refreshDone', token);16 } else {17 event.emit('refreshing');18 }19 } catch (e) {}20 })();21 });22 event.on('refreshing', () => {23 if (this.isRefreshing) {24 return;25 }26 // fetch27 this.isRefreshing = true;28 const evtFire = false;29 onRefreshToken((newToken) => {30 this.event.emit('refreshDone', newToken);31 this.isRefreshing = false;32 });33 if (this.refreshTimeout) {34 setTimeout(() => {35 if (!evtFire) {36 this.event.emit('refreshDone', null);37 this.isRefreshing = false;38 }39 }, this.refreshTimeout);40 }41 });42 this.event = event;43 }44 getToken() {45 return new Promise((resolve) => {46 let isCalled = false;47 const refreshDoneHandler = (token) => {48 resolve(token);49 isCalled = true;50 };51 this.event.once('refreshDone', refreshDoneHandler);52 if (!isCalled) {53 this.event.emit('refresh');54 }55 });56 }57 inject(service) {58 return async (...args) => {59 const token = await this.getToken();60 const response = await service(token, ...args);61 return response;62 };63 }...
Using AI Code Generation
1import {Component} from '@angular/core';2import {Idle, DEFAULT_INTERRUPTSOURCES} from '@ng-idle/core';3import {Keepalive} from '@ng-idle/keepalive';4@Component({5})6export class AppComponent {7 idleState = 'Not started.';8 timedOut = false;9 lastPing?: Date = null;10 constructor(private idle: Idle, private keepalive: Keepalive) {11 idle.setIdle(5);12 idle.setTimeout(5);13 idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);14 idle.onIdleEnd.subscribe(() => this.idleState = 'No longer idle.');15 idle.onTimeout.subscribe(() => {16 this.idleState = 'Timed out!';17 this.timedOut = true;18 });19 idle.onIdleStart.subscribe(() => this.idleState = 'You\'ve gone idle!');20 idle.onTimeoutWarning.subscribe((countdown) => this.idleState = 'You will time out in ' + countdown + ' seconds!');21 keepalive.interval(15);22 keepalive.onPing.subscribe(() => this.lastPing = new Date());23 this.reset();24 }25 reset() {26 this.idle.watch();27 this.idleState = 'Started.';28 this.timedOut = false;29 }30 refreshTimeout() {31 this.idle.refreshTimeout();32 }33}
Using AI Code Generation
1test('test', t => {2 t.plan(2);3 t.refreshTimeout(10000);4 const promise = new Promise((resolve, reject) => {5 setTimeout(() => {6 resolve('done');7 }, 2000);8 });9 return promise.then(result => {10 t.is(result, 'done');11 });12});13### .log(message)14test('test', t => {15 t.log('hello');16 t.log('world');17 t.pass();18});19### .debug(message)20test('test', t => {21 t.debug('hello');22 t.debug('world');23 t.pass();24});25### .snapshot([message], snapshot)26import fs from 'fs';27test('test', t => {28 t.snapshot(fs.readFileSync('test.js'));29});30### .throws(function|promise, [error, [message]])31import fs from 'fs';32test('test', t => {33 t.throws(() => {34 fs.readFileSync('non-existent-file.js');35 });36});37### .notThrows(function|promise, [message])38import fs from 'fs';39test('test', t => {40 t.notThrows(() => {41 fs.readFileSync('test.js');42 });43});44### .ifError(error, [message])45import fs from 'fs';46test('test', t =>
Using AI Code Generation
1var refreshTimeout = require('refresh-timeout');2var timeout = refreshTimeout(function() {3 console.log('timeout expired');4}, 1000);5var interval = setInterval(function() {6 console.log('refreshing timeout');7 timeout.refresh();8}, 500);9setTimeout(function() {10 console.log('clearing interval');11 clearInterval(interval);12}, 10000);
Using AI Code Generation
1var available = require('available');2available.refreshTimeout();3module.exports.refreshTimeout = function(){4}5var available = require('./available');6var available = require('available');7available.refreshTimeout();8module.exports.refreshTimeout = function(){9}10var available = require('available');11available.refreshTimeout();12module.exports.refreshTimeout = function(){13}
Check out the latest blogs from LambdaTest on this topic:
Screenshots! These handy snippets have become indispensable to our daily business as well as personal life. Considering how mandatory they are for everyone in these modern times, every OS and a well-designed game, make sure to deliver a built in feature where screenshots are facilitated. However, capturing a screen is one thing, but the ability of highlighting the content is another. There are many third party editing tools available to annotate our snippets each having their own uses in a business workflow. But when we have to take screenshots, we get confused which tool to use. Some tools are dedicated to taking best possible screenshots of whole desktop screen yet some are browser based capable of taking screenshots of the webpages opened in the browsers. Some have ability to integrate with your development process, where as some are so useful that there integration ability can be easily overlooked.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Automation Testing Tutorial.
Working in IT, we have often heard the term Virtual Machines. Developers working on client machines have used VMs to do the necessary stuffs at the client machines. Virtual machines are an environment or an operating system which when installed on a workstation, simulates an actual hardware. The person using the virtual machine gets the same experience as they would have on that dedicated system. Before moving on to how to setup virtual machine in your system, let’s discuss why it is used.
There is no other automation framework in the market that is more used for automating web testing tasks than Selenium and one of the key functionalities is to take Screenshot in Selenium. However taking full page screenshots across different browsers using Selenium is a unique challenge that many selenium beginners struggle with. In this post we will help you out and dive a little deeper on how we can take full page screenshots of webpages across different browser especially to check for cross browser compatibility of layout.
Cross browser compatibility can simply be summed up as a war between testers and developers versus the world wide web. Sometimes I feel that to achieve browser compatibility, you may need to sell your soul to devil while performing a sacrificial ritual. Even then some API plugins won’t work.(XD)
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!!