How to use cacheResponse method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

ESClient.js

Source:ESClient.js Github

copy

Full Screen

1import _ from 'lodash';2import Promise from 'bluebird';3import md5 from 'md5';4import performanceNow from 'performance-now';5import buildRedisClient from 'humane-node-commons/lib/RedisClient';6import * as Request from 'humane-node-commons/lib/Request';7import InternalServiceError from 'humane-node-commons/lib/InternalServiceError';8export default class ESClient {9    constructor(config) {10        this.request = Request.builder(_.extend({}, config.esConfig, {logLevel: config.logLevel, baseUrl: (config.esConfig && config.esConfig.url) || 'http://localhost:9200'}));11        this.redisKeyPrefix = process.env.REDIS_KEY_PREFIX;12        if (this.redisKeyPrefix) {13            this.redisKeyPrefix = `${this.redisKeyPrefix}/`;14        } else {15            this.redisKeyPrefix = '';16        }17        this.redisClient = buildRedisClient(_.pick(config, ['redisConfig', 'redisSentinelConfig']));18    }19    // throw new InternalServiceError('Internal Service Error', {code: 'INTERNAL_SERVICE_ERROR', details: response.body && response.body.error || response.body});20    storeInCache(key, data) {21        // nice to have: pack data with MessagePack22        return this.redisClient.setAsync([this.redisKeyPrefix + key, JSON.stringify(data), 'EX', 300])23          .then(() => data)24          .catch(() => {25              console.error('REDIS_ERROR: Error in storing key: ', this.redisKeyPrefix + key);26              return null;27          }); // eat the error28    }29    retrieveFromCache(key) {30        // nice to have: pack data with MessagePack31        return this.redisClient.getAsync(this.redisKeyPrefix + key)32          .then((data) => {33              if (!_.isUndefined(data) && !_.isNull(data) && _.isString(data)) {34                  return JSON.parse(data);35              }36              return null;37          })38          .catch(() => {39              console.error('REDIS_ERROR: Error in retrieving key: ', this.redisKeyPrefix + key);40              return null;41          }); // eat the error42    }43    removeFromCache(key) {44        return this.redisClient.delAsync(this.redisKeyPrefix + key)45          .catch(() => {46              console.error('REDIS_ERROR: Error in removing key: ', this.redisKeyPrefix + key);47              return null;48          }); // eat the error49    }50    static processResponse(response) {51        let _response = response;52        if (_.isArray(_response)) {53            _response = response[0];54        }55        if (_response.statusCode < 400) {56            return _response.body;57        }58        // console.error('Error: ', _response.body);59        throw new InternalServiceError('Internal Service Error', {_statusCode: _response.statusCode, details: (_response.body && _response.body.error) || _response.body});60    }61    // queries will be in following format:62    //      index or indices63    //      type64    //      search65    static bulkFormat(queries) {66        let ret = '';67        _.forEach(queries, (query) => {68            ret += JSON.stringify({index: (query.indices || [query.index]).join(','), type: (query.types || [query.type]).join(',')});69            ret += '\n';70            ret += JSON.stringify(query.search);71            ret += '\n';72        });73        return ret;74    }75    allPages(index, type, query, size, cb) {76        const _this = this;77        let totalResults = 0;78        function recursiveFetch(page) {79            return _this.search({index, type, search: _.assign({from: page * size, size}, query)})80              .then((response) => {81                  if (response && response.hits) {82                      if (page === 0) {83                          totalResults = response.hits.total;84                      }85                      // process response...86                      cb(response);87                      const hits = response.hits.hits;88                      if (hits && totalResults > (page * size) + hits.length) {89                          // recursively fetch next page90                          return recursiveFetch(page + 1);91                      }92                  }93                  return true;94              });95        }96        return recursiveFetch(0)97          .catch((error) => {98              throw new InternalServiceError('Internal Service Error', {details: (error && error.cause) || error, stack: error && error.stack});99          });100    }101    search(queryOrPromise) {102        const startTime = performanceNow();103        return Promise.resolve(queryOrPromise)104          .then((query) => {105              const uri = !query.type ? `/${query.index}/_search` : `/${query.index}/${query.type}/_search`;106              console.log('search: ', uri, JSON.stringify(query.search));107              const queryKey = md5(JSON.stringify(query.search));108              const cacheKey = `${uri}:${queryKey}`;109              return this.retrieveFromCache(cacheKey)110                .then((cacheResponse) => {111                    if (cacheResponse) {112                        cacheResponse.took = _.round(performanceNow() - startTime, 3);113                        console.log('search: Retrieved from cache in (ms): ', cacheResponse.took);114                        return cacheResponse;115                    }116                    return this.request({method: 'POST', uri, body: query.search})117                      .then(response => Request.handleResponse(response))118                      .then((queryResponse) => {119                          console.log('search: in (ms): ', _.round(performanceNow() - startTime, 3));120                          if (queryResponse) {121                              return this.storeInCache(cacheKey, queryResponse);122                          }123                          return null;124                      });125                });126          })127          .catch((error) => {128              console.error('Error: ', error, error.stack);129              throw new InternalServiceError('Internal Service Error', {details: (error && error.cause) || error, stack: error && error.stack});130          });131    }132    explain(id, query) {133        const uri = `/${query.index}/${query.type}/${id}/_explain`;134        //console.log('Explain: ', uri, JSON.stringify(query.search));135        return this.request({method: 'POST', uri, body: query.search})136          .then(response => Request.handleResponse(response))137          .catch((error) => {138              throw new InternalServiceError('Internal Service Error', {details: (error && error.cause) || error, stack: error && error.stack});139          });140    }141    get(index, type, id) {142        const startTime = performanceNow();143        const uri = `/${index}/${type}/${id}`;144        const cacheKey = md5(uri);145        return this.retrieveFromCache(cacheKey)146          .then((cacheResponse) => {147              if (cacheResponse) {148                  cacheResponse.took = _.round(performanceNow() - startTime, 3);149                  console.log('get: Retrieved from cache in (ms): ', cacheResponse.took);150                  return cacheResponse;151              }152              return this.request({method: 'GET', uri})153                .then(response => Request.handleResponse(response))154                .then((getResponse) => {155                    console.log('get: in (ms): ', _.round(performanceNow() - startTime, 3));156                    if (getResponse) {157                        return this.storeInCache(cacheKey, getResponse);158                    }159                    return null;160                });161          })162          .catch((error) => {163              throw new InternalServiceError('Internal Service Error', {details: (error && error.cause) || error, stack: error && error.stack});164          });165    }166    termVectors(index, type, id) {167        const uri = `/${index}/${type}/${id}/_termvectors?fields=*`;168        return this.request({method: 'GET', uri})169          .then(response => Request.handleResponse(response))170          .catch((error) => {171              throw new InternalServiceError('Internal Service Error', {details: (error && error.cause) || error, stack: error && error.stack});172          });173    }174    didYouMean(index, query) {175        const uri = `/${index}/_didYouMean?q=${query}`;176        return this.request({method: 'GET', uri})177          .then(response => Request.handleResponse(response))178          .catch((error) => {179              throw new InternalServiceError('Internal Service Error', {details: (error && error.cause) || error, stack: error && error.stack});180          });181    }182    intent(index, query) {183        const startTime = performanceNow();184        const uri = `/${index}/_intent`;185        const queryKey = md5(JSON.stringify(query));186        const cacheKey = `${uri}:${queryKey}`;187        return this.retrieveFromCache(cacheKey)188          .then((cacheResponse) => {189              if (cacheResponse) {190                  cacheResponse.took = _.round(performanceNow() - startTime, 3);191                  console.log('intent: Retrieved from cache in (ms): ', cacheResponse.took);192                  return cacheResponse;193              }194              console.log('intent: ', uri, JSON.stringify(query));195              return this.request({method: 'POST', uri, body: query})196                .then(response => Request.handleResponse(response))197                .then((queryResponse) => {198                    console.log('intent: in (ms): ', _.round(performanceNow() - startTime, 3));199                    if (queryResponse) {200                        return this.storeInCache(cacheKey, queryResponse);201                    }202                    return null;203                });204          })205          .catch((error) => {206              console.error('Error: ', error, error.stack);207              throw new InternalServiceError('Internal Service Error', {details: (error && error.cause) || error, stack: error && error.stack});208          });209    }210    multiSearch(queriesOrPromise) {211        const startTime = performanceNow();212        return Promise.all(queriesOrPromise)213          .then((queries) => {214              const uri = '/_msearch';215              console.log('multiSearch: ', JSON.stringify(queries));216              const bulkQuery = ESClient.bulkFormat(queries);217              const queryKey = md5(bulkQuery);218              const cacheKey = `${uri}:${queryKey}`;219              return this.retrieveFromCache(cacheKey)220                .then((cacheResponse) => {221                    if (cacheResponse) {222                        cacheResponse.took = _.round(performanceNow() - startTime, 3);223                        if (cacheResponse.responses) {224                            // set response times225                            _.forEach(cacheResponse.responses, (response) => {226                                response.took = cacheResponse.took;227                            });228                        }229                        console.log('multiSearch: Retrieved from cache in (ms): ', cacheResponse.took);230                        return cacheResponse;231                    }232                    return this.request({method: 'POST', uri, body: bulkQuery, json: false})233                      .then(ESClient.processResponse)234                      .then((response) => {235                          if (!_.isUndefined(response) && !_.isNull(response) && _.isString(response)) {236                              return JSON.parse(response);237                          }238                          return null;239                      })240                      .then((queryResponse) => {241                          console.log('multiSearch: in (ms): ', _.round(performanceNow() - startTime, 3));242                          if (queryResponse) {243                              return this.storeInCache(cacheKey, queryResponse);244                          }245                          return null;246                      });247                });248          })249          .catch((error) => {250              console.error('Error: ', error, error.stack);251              throw new InternalServiceError('Internal Service Error', {details: (error && error.cause) || error, stack: error && error.stack});252          });253    }254    // analyze(index, analyzer, text) {255    //     const uri = `/${index}/_analyze?analyzer=${analyzer}&text=${encodeURIComponent(text)}`;256    //     return this.request({method: 'GET', uri})257    //       .then(ESClient.processResponse)258    //       .catch(error => {259    //           throw new InternalServiceError('Internal Service Error', {details: error && error.cause || error, stack: error && error.stack});260    //       });261    // }262//    curl -XGET 'http://localhost:9200/imdb/movies/_validate/query?rewrite=true' -d '263//{264//    "query": {265//      "fuzzy": {266//        "actors": "kyle"267//        }268//      }269//}'270//271//{272//    "valid": true,273//    "_shards": {274//      "total": 1,275//      "successful": 1,276//      "failed": 0277//      },278//    "explanations": [279//    {280//        "index": "imdb",281//        "valid": true,282//        "explanation": "plot:kyle plot:kylie^0.75 plot:kyne^0.75 plot:lyle^0.75 plot:pyle^0.75 #_type:movies"283//    }284//      ]285//}...

Full Screen

Full Screen

sw.js

Source:sw.js Github

copy

Full Screen

1const version = '-v2';2const coreCacheName = 'core' + version;3const apiCacheName = 'api' + version;4const coreAssets = [5    '/css/style.css',6    '/fonts/Asap-Italic-VariableFont_wght.woff2',7    '/fonts/Asap-VariableFont_wght.woff2',8    '/img/bnijenhuis.svg',9    '/favicon.ico',10    '/offline/',11    '/offline.json'12];13const localDomains = [14    'http://bnijenhuis-nl.test',15    'https://bnijenhuis.nl'16]17// install service worker and cache core assets18addEventListener('install', function (event) {19	event.waitUntil(20        caches.open(coreCacheName).then(function (cache) { 21            cache.addAll(coreAssets);22        })23    );24});25// make sure to remove old caches26addEventListener('activate', function (event) {27    event.waitUntil(28        caches.keys().then(function (keys) { 29            return Promise.all(keys30                .filter(key => key !== coreCacheName && key !== apiCacheName)31                .map(key => caches.delete(key))32            )33        })34    )35});36// fetch assets and serve from cache and update cache37addEventListener('fetch', function (event) {38    if (event.request.url.includes('/css/style.css')) {39        // (directly) respond with cached asset (if available)40        event.respondWith(serveFromCache(event, true, false));41        // update cache42        event.waitUntil(updateCache(event.request, coreCacheName));43    } else if (event.request.url.includes('https://webmention.io/api/')) {44        // we want to limit the requests to webmention.io45        // (directly) respond with cached asset (if available)46        event.respondWith(serveFromCache(event, false, true));47    } else {48        // (directly) respond with cached asset (if available)49        event.respondWith(serveFromCache(event, false, false));50        // update cache (only if in core assets)51        var requestUrl = event.request.url;52        for (const localDomain of localDomains) {53            requestUrl = requestUrl.replace(localDomain, '');54        }55        if (coreAssets.includes(requestUrl)) {56            event.waitUntil(updateCache(event.request, coreCacheName));57        }58    }59});60/**61 * serve request from cache62 * if file isn't cached longer than 24 hours, it's still valid63 * @param {Event} event the request event64 * @param {Boolean} ignoreSearch if true, ignore search parameters in request65 * @param {Boolean} checkExpiryHeader if true, check for custom expiry header66 * @return {Object} response object from cache or from fetch67 */68function serveFromCache(event, ignoreSearch, checkExpiryHeader) {69    // set the right match options70    var matchOptions = {};71    if (ignoreSearch) matchOptions = {ignoreSearch:true};72    return caches.match(event.request, matchOptions).then(function (cacheResponse) { 73        // if found return cache74        if (cacheResponse) {75            if (checkExpiryHeader) {76                if (isCacheResponseStillValid(cacheResponse)) {77                    return cacheResponse;78                }79            } else {80                return cacheResponse;81            }82        }83        84        // fetch it again, because cache was not found or was expired85        return fetch(event.request).then(function (response) {86            if (event.request.url.includes('/css/style.css')) {87                updateCache(event.request, coreCacheName);88            } else if (event.request.url.includes('https://webmention.io/api/')) {89                updateCache(event.request, apiCacheName);90            }91            return response;92        // if offline and not found in cache, return offline data93        }).catch(function (error) {94            if (event.request.url.endsWith('/')) {95                return caches.match('/offline/');96            } else if (event.request.url.includes('https://webmention.io/api/')) {97                return caches.match('/offline.json');98            }99        });100    })101}102/**103 * update cache104 * @param {Object} request the event request105 * @param {String} cacheName the cache to update106 * @return {Object} response object107 */108function updateCache(request, cacheName) {109    return caches.open(cacheName).then(function (cache) {110        return fetch(request).then(function (response) {111            112            var responseCopy = response.clone();113            var headers = new Headers(responseCopy.headers);114            headers.append('sw-fetched-on', new Date().getTime());115            var requestKey = request;116            // make sure the request with query params of style.css are not saved as a different asset117            if (request.url.includes('/css/style.css')) {118                requestKey = '/css/style.css';119            }120            return responseCopy.blob().then(function (body) {121                return cache.put(requestKey, new Response(body, {122                    status: responseCopy.status,123                    statusText: responseCopy.statusText,124                    headers: headers125                }));126            });127        });128    });129}130/**131 * check of cacheResponse is still valid132 * if file isn't cached longer than 24 hours, it's still valid133 * @param {Object} cacheResponse the cacheResponse object134 * @return {Boolean} if true, cacheResponse is valid135 */136 function isCacheResponseStillValid(cacheResponse) {137	if (!cacheResponse) {138        return false;139    }140	141    var fetched = cacheResponse.headers.get('sw-fetched-on');142	143    // ms * seconds * minutes * hours144    if (fetched && (parseFloat(fetched) + (1000 * 60 * 60 * 24)) > new Date().getTime()) {145        return true;146    }147	return false;...

Full Screen

Full Screen

helper.js

Source:helper.js Github

copy

Full Screen

1import { Message } from "element-ui";2export const formatSize = function(value, scale) {3  if (value == null || value == "") {4    return "0 Bytes";5  }6  var unitArr = new Array(7    "Bytes",8    "KB",9    "MB",10    "GB",11    "TB",12    "PB",13    "EB",14    "ZB",15    "YB"16  );17  var index = 0;18  index = Math.floor(Math.log(value) / Math.log(1024));19  var size = value / Math.pow(1024, index);20  size = size.toFixed(scale || 2);21  return size + " " + unitArr[index];22};23export const LimitResquest = function(limit, process) {24  let currentSum = 0;25  let requests = [];26  async function run() {27    let err, result;28    try {29      ++currentSum;30      handler.leftCount = requests.length;31      const fn = requests.shift();32      result = await fn();33    } catch (error) {34      err = error;35      // console.log("Error", err);36      handler.errorCount++;37    } finally {38      --currentSum;39      handler.requestCount++;40      handler.leftCount = requests.length;41      process && process(handler, result, err);42      if (requests.length > 0) {43        run();44      }45    }46  }47  const handler = reqFn => {48    if (!reqFn || !(reqFn instanceof Function)) {49      return;50    }51    requests.push(reqFn);52    handler.leftCount = requests.length;53    if (currentSum < limit) {54      run();55    }56  };57  handler.requestCount = 0;58  handler.leftCount = 0;59  handler.errorCount = 0;60  handler.cancel = () => {61    requests = [];62  };63  handler.isEnd = () => {64    return !handler.leftCount && !currentSum;65  };66  return handler;67};68export const networkFirstRequest = async function(69  requestFunc,70  cacheKey,71  forceCache72) {73  debugger;74  cacheKey = "localCache@" + cacheKey;75  const res = await requestFunc().catch(err => {76    // 请求出错,使用缓存77    if (forceCache || !window.serviceWorkerReady) {78      try {79        let cacheResponse =80          window.localStorage && window.localStorage.getItem(cacheKey);81        if (cacheResponse) {82          cacheResponse = JSON.parse(cacheResponse);83          if (cacheResponse) {84            return { data: cacheResponse };85          }86        }87      } catch (error) {88        //89      }90    }91    throw err;92  });93  if (94    (forceCache || !window.serviceWorkerReady) &&95    res.data &&96    res.data.isSuccess97  ) {98    try {99      window.localStorage &&100        window.localStorage.setItem(cacheKey, JSON.stringify(res.data));101    } catch (error) {102      Math.random() > 0.7 &&103        setTimeout(() => {104          Message.error({105            message: "本地空间已满,请去书架页面清空缓存",106            duration: 500107          });108        }, 1000);109    }110  }111  return res;112};113export const cacheFirstRequest = async function(114  requestFunc,115  cacheKey,116  validateCache,117  forceCache118) {119  cacheKey = "localCache@" + cacheKey;120  // validateCache === true 时,直接刷新缓存121  if (validateCache !== true) {122    if (forceCache || !window.serviceWorkerReady) {123      try {124        let cacheResponse =125          window.localStorage && window.localStorage.getItem(cacheKey);126        if (cacheResponse) {127          cacheResponse = JSON.parse(cacheResponse);128          if (cacheResponse) {129            if (130              !validateCache ||131              (validateCache && validateCache(cacheResponse))132            ) {133              return { data: cacheResponse };134            }135          }136        }137      } catch (error) {138        //139      }140    }141  }142  const res = await requestFunc();143  if (144    (forceCache || !window.serviceWorkerReady) &&145    res.data &&146    res.data.isSuccess147  ) {148    try {149      window.localStorage &&150        window.localStorage.setItem(cacheKey, JSON.stringify(res.data));151    } catch (error) {152      Math.random() > 0.7 &&153        setTimeout(() => {154          Message.error({155            message: "本地空间已满,请去书架页面清空缓存",156            duration: 500157          });158        }, 1000);159    }160  }161  return res;162};...

Full Screen

Full Screen

revalidate.js

Source:revalidate.js Github

copy

Full Screen

1import cache from 'memory-cache'2import { cache_postid_to_url, get_cache_postids_to_url } from '../../caching/tracker'3export default async function revalidate(req, res) {4    if(req.method.toLowerCase() !== 'post') {5        res.setHeader('Accept', ['POST'])6        res.status(400).json({'error': "Method Not Allowed"})7    }8    // What if cache expires but not the path related to postid (updation)9    // Validation of request that it actually comes from backend (Django)10    //   Client Key Access11  12    // const router = useRouter();13    const secret_key = req.headers['secret-key']14    if((secret_key ?? false) && secret_key === "98h(F*H(F$&*H87fH$*&gtoL:TW$)*HF*84f") {15        // Could be backend making the request16        //REVALIDATE POST VIEW17        const {target_post_id, target_field, data} = req.body;console.log(target_post_id, target_field, data);18      19        const hours = 1;  20        let cacheResponse;  21        const cache_postid_to_url = cache.get;22        console.log(cache_postid_to_url)23        // Object.entries(cache_postid_to_url).map(item => {24        //     console.log("AndarBahar")25        //     //Item = [key, val]26            cache.keys().forEach((url) => {27                console.log("Andar")28                switch(target_field){29                    case 'likes':30                        // Update Likes on every url-path31                        cacheResponse = cache.get(url) || [];32                        33                        if (cacheResponse.length === 0) {34                            cache.put(url, cacheResponse, hours * 1000 * 60 * 60);35                            break;36                        }37                        cacheResponse = cacheResponse.map((val, idx) => {38                            if(val.id === Number(target_post_id)){39                                val.likes = data40                            }41                            return val;42                        })43                        // const hours = 1;44                        cache.put(url, cacheResponse, hours * 1000 * 60 * 60);45                     46                        break;47                        // res.status(204).end()48                        49                    case 'dislikes':50                        // Update Dislikes on every url-path51                        cacheResponse = cache.get(url) || [];52                        if (cacheResponse.length === 0) {53                            cache.put(url, cacheResponse, hours * 1000 * 60 * 60);54                            break;55                        }56                        57                        cacheResponse = cacheResponse.map((val, idx) => {58                            if(val.id === Number(target_post_id)){59                                val.dislikes = data60                            }61                            return val;62                        })63                        // const hours = 1;64                        cache.put(url, cacheResponse, hours * 1000 * 60 * 60);65                        break;66                        67                        68                    case 'comments': 69                        // Update Comments on every url-path70                        cacheResponse = cache.get(url) || [];71                        if (cacheResponse.length === 0) {72                            cache.put(url, cacheResponse, hours * 1000 * 60 * 60);73                            break;74                        }75                        76                        cacheResponse = cacheResponse.map((val, idx) => {77                            if(val.id === Number(target_post_id)){78                                val.comments = data79                            }80                            return val;81                        })82                        // const hours = 1;83                        cache.put(url, cacheResponse, hours * 1000 * 60 * 60);84                        break;85                        // res.status(204).end()86                    87                }88            })89        //   })90        res.status(204).end()91    }...

Full Screen

Full Screen

clothe.js

Source:clothe.js Github

copy

Full Screen

...12    app.use('/api/clothe',router);13    const clothesServices = new ClothesServices();14    router.get('/', async function (req, res, next) {15      16        cacheResponse(res, FIVE_MINUTES_IN_SECONDS);17        const { tags } = req.query;18       19        try {20          const Clothes = await clothesServices.geClothes(/*{ tags }*/);21         22          // throw new Error("Error getting movies");23          res.status(200).json({24            data: Clothes,25            message: 'movies listed',26          });27        } catch (error) {28          next(error);29        }30        31      });32      33      34      router.get("/:clotheId",async function(req,res, next){35        //cacheResponse(res.FIVE_MINUTES_IN_SECONDS);36        console.log(req.params)37        const {clotheId}=req.params;38        try {39         40          const Clothe=await clothesServices.getClothe(clotheId)41          res.status(200).json({42            data:Clothe,43            message:'Clothe encontrado'44          });45        } catch (error) {46          next(error);47        }48      });49      router.get("/category/:categoryId",async function(req,res,next){50        cacheResponse(res.FIVE_MINUTES_IN_SECONDS);51        console.log(req.params)52        const {categoryId}=req.params;53        try {54          const clothes=await clothesServices.getClohtebyId(categoryId)55          res.status(200).json({56            data:clothes,57            message:'categorias encontrada'58          });59        } catch (error) {60          next(error)61        }62      });63      router.get("/category1/:female",async function(req,res,next){64        cacheResponse(res.FIVE_MINUTES_IN_SECONDS);65        const {female}=req.params;   66        try {67          const clothes=await clothesServices.getClohtebyGender(female);68          res.status(200).json({69            data:clothes,70            message:'categorias encontrada'71          });72        } catch (error) {73          next(error)74        }75      })76   77   78}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const isMockApi = process.env.MOCK === "true";2let api;3if (isMockApi) {4  console.log("Mock API is used");5  api = require("./nba-mock-api");6} else {7  const nbaApi = require("./nba-api");8  const apiCache = require("./nba-api-cache");9  api = {10    getAllPlayers: async function() {11      const cacheResponse = apiCache.getAllPlayers();12      if (cacheResponse) {13        return Promise.resolve(cacheResponse);14      } else {15        const response = await nbaApi.getAllPlayers();16        apiCache.setAllPlayers(response);17        return response;18      }19    },20    getAdvancedPlayerStats: async function(id) {21      const cacheResponse = apiCache.getAdvancedPlayerStats(id);22      if (cacheResponse) {23        return Promise.resolve(cacheResponse);24      } else {25        const response = await nbaApi.getAdvancedPlayerStats(id);26        apiCache.setAdvancedPlayerStats(id, response);27        return response;28      }29    },30    getSimplePlayerStats: async function(id) {31      const cacheResponse = apiCache.getSimplePlayerStats(id);32      if (cacheResponse) {33        return Promise.resolve(cacheResponse);34      } else {35        const response = await nbaApi.getSimplePlayerStats(id);36        apiCache.setSimplePlayerStats(id, response);37        return response;38      }39    },40    getPlayerInformation: async function(id) {41      const cacheResponse = apiCache.getPlayerInformation(id);42      if (cacheResponse) {43        return Promise.resolve(cacheResponse);44      } else {45        const response = await nbaApi.getPlayerInformation(id);46        apiCache.setPlayerInformation(id, response);47        return response;48      }49    }50  };51  console.log("NBA API is used");52}...

Full Screen

Full Screen

cacheResponse.test.js

Source:cacheResponse.test.js Github

copy

Full Screen

...12      const resStub = sinon.stub();13      const res = { set: resStub };14      const seconds = 'foo';15      // when16      cacheResponse(res, seconds);17      // then18      assert.strictEqual(19        resStub.calledWith('Cache-Control', 'public, max-age=foo'),20        true21      );22    });23  });24  describe('when the environment is development', () => {25    it("shouldn't set the cache header", () => {26      // given27      const configStub = { config: { dev: true } };28      const cacheResponse = proxyquire('../utils/cacheResponse', {29        '../config': configStub30      });31      const resStub = sinon.stub();32      const res = { set: resStub };33      const seconds = 'foo';34      // when35      cacheResponse(res, seconds);36      // then37      assert.strictEqual(resStub.called, false);38    });39  });...

Full Screen

Full Screen

routes.js

Source:routes.js Github

copy

Full Screen

...6  .prerender(prerenderRequests)7  .match('/service-worker.js', ({ serviceWorker }) => {8    serviceWorker('.next/static/service-worker.js')9  })10  .match('/', cacheResponse(SSR))11  .match('/api', cacheResponse(API))12  .match('/s/:categorySlug*', cacheResponse(SSR))13  .match('/api/s/:categorySlug*', cacheResponse(API))14  .match('/p/:productId', cacheResponse(SSR))15  .match('/api/p/:productId', cacheResponse(API))16  .use(nextRoutes)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const BaseDriver = require('appium-base-driver');2const driver = new BaseDriver();3const response = driver.cacheResponse('some response');4const BaseDriver = require('appium-base-driver');5const driver = new BaseDriver();6const response = driver.getCachedResponse('some response');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { cacheResponse } = require('appium-base-driver');2const { BaseDriver } = require('appium-base-driver');3const { AppiumDriver } = require('appium-base-driver');4const { AppiumService } = require('appium-base-driver');5const { AppiumPlugin } = require('appium-base-driver');6const { AppiumPluginDriver } = require('appium-base-driver');7const plugin = new AppiumPlugin();8const pluginDriver = new AppiumPluginDriver(plugin, null);9const driver = new AppiumDriver(pluginDriver, null);10const service = new AppiumService(driver, null);11cacheResponse(service, 'getSession', 200, {foo: 'bar'});12const { cacheResponse } = require('appium-base-driver');13const { BaseDriver } = require('appium-base-driver');14const { AppiumDriver } = require('appium-base-driver');15const { AppiumService } = require('appium-base-driver');16const { AppiumPlugin } = require('appium-base-driver');17const { AppiumPluginDriver } = require('appium-base-driver');18const plugin = new AppiumPlugin();19const pluginDriver = new AppiumPluginDriver(plugin, null);20const driver = new AppiumDriver(pluginDriver, null);21const service = new AppiumService(driver, null);22cacheResponse(service, 'getSession', 200, {foo: 'bar'});23const { cacheResponse } = require('appium-base-driver');24const { BaseDriver } = require('appium-base-driver');25const { AppiumDriver } = require('appium-base-driver');26const { AppiumService } = require('appium-base-driver');27const { AppiumPlugin } = require('appium-base-driver');28const { AppiumPluginDriver } = require('appium-base-driver');29const plugin = new AppiumPlugin();

Full Screen

Using AI Code Generation

copy

Full Screen

1const BaseDriver = require('appium-base-driver');2const driver = new BaseDriver();3driver.cacheResponse('test','test');4driver.getCachedResponse('test');5const BaseDriver = require('appium-base-driver');6const driver = new BaseDriver();7driver.cacheResponse('test','test');8driver.getCachedResponse('test');9const BaseDriver = require('appium-base-driver');10const driver = new BaseDriver();11driver.cacheResponse('test','test');12driver.getCachedResponse('test');13const BaseDriver = require('appium-base-driver');14const driver = new BaseDriver();15driver.cacheResponse('test','test');16driver.getCachedResponse('test');17const BaseDriver = require('appium-base-driver');18const driver = new BaseDriver();19driver.cacheResponse('test','test');20driver.getCachedResponse('test');21const BaseDriver = require('appium-base-driver');22const driver = new BaseDriver();23driver.cacheResponse('test','test');24driver.getCachedResponse('test');25const BaseDriver = require('appium-base-driver');26const driver = new BaseDriver();27driver.cacheResponse('test','test');28driver.getCachedResponse('test');29const BaseDriver = require('appium-base-driver');30const driver = new BaseDriver();31driver.cacheResponse('test','test');32driver.getCachedResponse('test');33const BaseDriver = require('appium-base-driver');34const driver = new BaseDriver();35driver.cacheResponse('test','test');36driver.getCachedResponse('test');37const BaseDriver = require('appium-base-driver');38const driver = new BaseDriver();39driver.cacheResponse('test','test');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var config = require('./config');4var driver = wd.promiseChainRemote(config.appiumServer);5driver.init(config.capabilities).then(function(){6}).then(function(){7}).then(function(){8}).then(function(){9}).then(function(response){10  assert(response == 'This is a response');11}).fin(function(){12  return driver.quit();13}).done();14exports.capabilities = {15  'chromeOptions': {16  }17};

Full Screen

Using AI Code Generation

copy

Full Screen

1var appium = require('appium-base-driver');2var baseDriver = new appium.Basedriver();3var response = baseDriver.cacheResponse('test', 'test');4console.log(response);5var appium = require('appium-base-driver');6var baseDriver = new appium.Basedriver();7var response = baseDriver.cacheResponse('test', 'test');8console.log(response);9var appium = require('appium-base-driver');10var baseDriver = new appium.Basedriver();11var response = baseDriver.cacheResponse('test', 'test');12console.log(response);13var appium = require('appium-base-driver');14var baseDriver = new appium.Basedriver();15var response = baseDriver.cacheResponse('test', 'test');16console.log(response);17var appium = require('appium-base-driver');18var baseDriver = new appium.Basedriver();19var response = baseDriver.cacheResponse('test', 'test');20console.log(response);21var appium = require('appium-base-driver');22var baseDriver = new appium.Basedriver();23var response = baseDriver.cacheResponse('test', 'test');24console.log(response);25var appium = require('appium-base-driver');26var baseDriver = new appium.Basedriver();27var response = baseDriver.cacheResponse('test', 'test');28console.log(response);29var appium = require('appium-base-driver');30var baseDriver = new appium.Basedriver();31var response = baseDriver.cacheResponse('test', 'test');32console.log(response);33var appium = require('appium-base-driver');34var baseDriver = new appium.Basedriver();35var response = baseDriver.cacheResponse('test', 'test');36console.log(response);37var appium = require('appium-base-driver');38var baseDriver = new appium.Basedriver();39var response = baseDriver.cacheResponse('

Full Screen

Using AI Code Generation

copy

Full Screen

1var cacheResponse = require('appium-base-driver').cacheResponse;2var driver = require('appium-base-driver').Driver;3var test = function(driver) {4    var test = cacheResponse(driver, 'test');5    return test;6};7module.exports = test;8var test = require('./test');9var driver = require('appium-base-driver').Driver;10var test2 = function(driver) {11    var test2 = test(driver);12    return test2;13};14module.exports = test2;15var test2 = require('./test2');16var driver = require('appium-base-driver').Driver;17var test3 = function(driver) {18    var test3 = test2(driver);19    return test3;20};21module.exports = test3;22var test3 = require('./test3');23var driver = require('appium-base-driver').Driver;24var test4 = function(driver) {25    var test4 = test3(driver);26    return test4;27};28module.exports = test4;29var test4 = require('./test4');30var driver = require('appium-base-driver').Driver;31var test5 = function(driver) {32    var test5 = test4(driver);33    return test5;34};35module.exports = test5;36var test5 = require('./test5');37var driver = require('appium-base-driver').Driver;38var test6 = function(driver) {39    var test6 = test5(driver);40    return test6;41};42module.exports = test6;43var test6 = require('./test6');44var driver = require('appium-base-driver').Driver;45var test7 = function(driver) {46    var test7 = test6(driver);47    return test7;48};49module.exports = test7;50var test7 = require('./test7');51var driver = require('appium-base-driver').Driver;52var test8 = function(driver) {53    var test8 = test7(driver);54    return test8;55};56module.exports = test8;57var test8 = require('./test8');58var driver = require('appium-base-driver').Driver;59var test9 = function(driver) {60    var test9 = test8(driver);

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Base Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful