Best JavaScript code snippet using wpt
Wrapper.ts
Source:Wrapper.ts
...15 // Store the account ID of the channel we're accessing.16 this.accountId = accountId;17 }18 // Create a generic request wrapper.19 private makeRequest(method: string, path: string, body?: { message?: any; username?: any; level?: any; id?: string; role?: any; optionId?: any; amount?: any; winnerId?: any; tickets?: any; song?: any; volume?: number; rating?: any; }, qs?: { limit?: any; offset?: any; text?: any; voice?: string; pending?: any; }) {20 // Return a promise to allow developers to appropriately handle API responses.21 return new Promise((resolve, reject) => {22 request({23 method,24 qs,25 body,26 json: true,27 url: `${this.base}/${path}`,28 headers: {29 'Authorization': `Bearer ${this.jwt}`30 }31 }, (error: any, response: { statusCode: number; }, responseBody: any) => {32 // If there is a request error, reject the Promise.33 if (error) {34 return reject(error);35 }36 // If there is an error on the response body, reject the Promise.37 if (responseBody && responseBody.error) {38 return reject(responseBody.error);39 }40 // If we receive a status code other than 2XX range, reject the Promise.41 if (response.statusCode < 200 || response.statusCode > 299) {42 return reject(`Error encountered during request to StreamElements. Status Code: ${response.statusCode}`);43 }44 // If no errors have been encountered, resolve the Promise with the response body.45 return resolve(responseBody);46 });47 });48 }49 // /activities50 getActivities(channel = this.accountId) {51 return this.makeRequest(HTTP.GET, `activities/${channel}`);52 }53 getActivity(activityId: any, channel = this.accountId) {54 return this.makeRequest(HTTP.GET, `activities/${channel}/${activityId}`);55 }56 replayActivity(activityId: any, channel = this.accountId) {57 return this.makeRequest(HTTP.POST, `activities/${channel}/${activityId}/replay`);58 }59 // /bot60 getBotStatus(channel = this.accountId) {61 return this.makeRequest(HTTP.GET, `bot/${channel}`);62 }63 botPartChannel(channel = this.accountId) {64 return this.makeRequest(HTTP.POST, `bot/${channel}/part`);65 }66 botSay(message: any, channel = this.accountId) {67 return this.makeRequest(HTTP.POST, `bot/${channel}/say`, { message });68 }69 botJoinChannel(channel = this.accountId) {70 return this.makeRequest(HTTP.POST, `bot/${channel}/join`);71 }72 botMute(channel = this.accountId) {73 return this.makeRequest(HTTP.POST, `bot/${channel}/mute`);74 }75 botUnmute(channel = this.accountId) {76 return this.makeRequest(HTTP.POST, `bot/${channel}/unmute`);77 }78 getBotUserLevels(channel = this.accountId) {79 return this.makeRequest(HTTP.GET, `bot/${channel}/levels`);80 }81 setBotUserLevel(username: any, level: any, channel = this.accountId) {82 return this.makeRequest(HTTP.POST, `bot/${channel}/levels`, { username, level });83 }84 deleteBotUserLevel(username: any, channel = this.accountId) {85 return this.makeRequest(HTTP.DELETE, `bot/${channel}/levels/${username}`, { id: `levels` });86 }87 // /bot/commands88 getBotCommands(channel = this.accountId) {89 return this.makeRequest(HTTP.GET, `bot/commands/${channel}`);90 }91 createBotCommand(options: any, channel = this.accountId) {92 return this.makeRequest(HTTP.POST, `bot/commands/${channel}`, options);93 }94 getDefaultBotCommands(channel = this.accountId) {95 return this.makeRequest(HTTP.GET, `bot/commands/${channel}/default`);96 }97 updateDefaultBotCommand(commandId: any, options: any, channel = this.accountId) {98 return this.makeRequest(HTTP.PUT, `bot/commands/${channel}/default/${commandId}`, options);99 }100 // /bot/timers101 getBotTimers(channel = this.accountId) {102 return this.makeRequest(HTTP.GET, `bot/timers/${channel}`);103 }104 createBotTimer(options: any, channel = this.accountId) {105 return this.makeRequest(HTTP.POST, `bot/timers/${channel}`, options);106 }107 getBotTimer(timerId: any, channel = this.accountId) {108 return this.makeRequest(HTTP.GET, `bot/timers/${channel}/${timerId}`);109 }110 updateBotTimer(timerId: any, options: any, channel = this.accountId) {111 return this.makeRequest(HTTP.PUT, `bot/timers/${channel}/${timerId}`, options);112 }113 deleteBotTimer(timerId: any, channel = this.accountId) {114 return this.makeRequest(HTTP.DELETE, `bot/timers/${channel}/${timerId}`);115 }116 // /changelogs117 getLatestChangelog() {118 return this.makeRequest(HTTP.GET, `changelogs/latest`);119 }120 getFirstChangelog() {121 return this.makeRequest(HTTP.GET, `changelogs/first`);122 }123 // /channels124 getCurrentChannel() {125 return this.makeRequest(HTTP.GET, `channels/me`);126 }127 getChannel(channel = this.accountId) {128 return this.makeRequest(HTTP.GET, `channels/${channel}`);129 }130 getChannelEmotes(channel = this.accountId) {131 return this.makeRequest(HTTP.GET, `channels/${channel}/emotes`);132 }133 getChannelDetails(channel = this.accountId) {134 return this.makeRequest(HTTP.GET, `channels/${channel}/details`);135 }136 updateChannelProfile(options: any, channel = this.accountId) {137 return this.makeRequest(HTTP.PUT, `channels/${channel}/profile`, options);138 }139 getChannelUsers(channel = this.accountId) {140 return this.makeRequest(HTTP.GET, `channels/${channel}/users`);141 }142 updateUserAccessLevel(userId: any, role: any, channel = this.accountId) {143 return this.makeRequest(HTTP.PUT, `channels/${channel}/users/${userId}`, { role });144 }145 deleteUserAccess(userId: any, channel = this.accountId) {146 return this.makeRequest(HTTP.DELETE, `channels/${channel}/users/${userId}`);147 }148 roleplayAsUser(channel = this.accountId) {149 return this.makeRequest(HTTP.POST, `channels/${channel}/roleplay`);150 }151 // /contests152 getContests(channel = this.accountId) {153 return this.makeRequest(HTTP.GET, `contests/${channel}`);154 }155 createContest(options: any, channel = this.accountId) {156 return this.makeRequest(HTTP.POST, `contests/${channel}`, options);157 }158 getCompletedContests(channel = this.accountId) {159 return this.makeRequest(HTTP.GET, `contests/${channel}/history`);160 }161 getContest(contestId: any, channel = this.accountId) {162 return this.makeRequest(HTTP.GET, `contests/${channel}/${contestId}`);163 }164 updateContest(contestId: any, options: any, channel = this.accountId) {165 return this.makeRequest(HTTP.PUT, `contests/${channel}/${contestId}`, options);166 }167 deleteContest(contestId: any, channel = this.accountId) {168 return this.makeRequest(HTTP.DELETE, `contests/${channel}/${contestId}`);169 }170 createContestBet(contestId: any, optionId: any, amount: any, channel = this.accountId) {171 return this.makeRequest(HTTP.POST, `contests/${channel}/${contestId}/bet`, { optionId, amount });172 }173 getContestBet(contestId: any, channel = this.accountId) {174 return this.makeRequest(HTTP.GET, `contests/${channel}/${contestId}/bet`);175 }176 startContest(contestId: any, channel = this.accountId) {177 return this.makeRequest(HTTP.PUT, `contests/${channel}/${contestId}/start`);178 }179 setContestWinner(contestId: any, winnerId: any, channel = this.accountId) {180 return this.makeRequest(HTTP.PUT, `contests/${channel}/${contestId}/winner`, { winnerId });181 }182 refundContest(contestId: any, channel = this.accountId) {183 return this.makeRequest(HTTP.DELETE, `contests/${channel}/${contestId}/refund`);184 }185 closeContest(contestId: any, channel = this.accountId) {186 return this.makeRequest(HTTP.DELETE, `contests/${channel}/${contestId}/stop`);187 }188 // /giveaways189 getGiveaways(channel = this.accountId) {190 return this.makeRequest(HTTP.GET, `giveaways/${channel}`);191 }192 createGiveaway(options: any, channel = this.accountId) {193 return this.makeRequest(HTTP.POST, `giveaways/${channel}`);194 }195 getPastGiveaways(channel = this.accountId) {196 return this.makeRequest(HTTP.GET, `giveaways/${channel}/history`);197 }198 getGiveaway(giveawayId: any, channel = this.accountId) {199 return this.makeRequest(HTTP.GET, `giveaways/${channel}/${giveawayId}`);200 }201 buyGiveawayTickets(giveawayId: any, tickets: any, channel = this.accountId) {202 return this.makeRequest(HTTP.POST, `giveaways/${channel}/${giveawayId}`, { tickets });203 }204 updateGiveaway(giveawayId: any, options: any, channel = this.accountId) {205 return this.makeRequest(HTTP.PUT, `giveaways/${channel}/${giveawayId}`, options);206 }207 deleteGiveaway(giveawayId: any, channel = this.accountId) {208 return this.makeRequest(HTTP.DELETE, `giveaways/${channel}/${giveawayId}`);209 }210 getUserGiveawayStatus(giveawayId: any, channel = this.accountId) {211 return this.makeRequest(HTTP.GET, `giveaways/${channel}/${giveawayId}/joined`);212 }213 completeGiveaway(giveawayId: any, channel = this.accountId) {214 return this.makeRequest(HTTP.PUT, `giveaways/${channel}/${giveawayId}/complete`);215 }216 refundGiveaway(giveawayId: any, channel = this.accountId) {217 return this.makeRequest(HTTP.DELETE, `giveaways/${channel}/${giveawayId}/refund`);218 }219 closeGiveaway(giveawayId: any, channel = this.accountId) {220 return this.makeRequest(HTTP.DELETE, `giveaways/${channel}/${giveawayId}/close`);221 }222 // /logs223 getLogs(channel = this.accountId) {224 return this.makeRequest(HTTP.GET, `logs/${channel}`);225 }226 // /loyalty227 getLoyaltySettings(channel = this.accountId) {228 return this.makeRequest(HTTP.GET, `loyalty/${channel}`);229 }230 updateLoyaltySettings(options: any, channel = this.accountId) {231 return this.makeRequest(HTTP.PUT, `loyalty/${channel}`, options);232 }233 // /overlays234 getOverlays(channel = this.accountId) {235 return this.makeRequest(HTTP.GET, `overlays/${channel}`);236 }237 createOverlay(options: any, channel = this.accountId) {238 return this.makeRequest(HTTP.POST, `overlays/${channel}`, options);239 }240 getOverlay(overlayId: any, channel = this.accountId) {241 return this.makeRequest(HTTP.GET, `overlays/${channel}/${overlayId}`);242 }243 updateOverlay(overlayId: any, options: any, channel = this.accountId) {244 return this.makeRequest(HTTP.PUT, `overlays/${channel}/${overlayId}`, options);245 }246 deleteOverlay(overlayId: any, channel = this.accountId) {247 return this.makeRequest(HTTP.DELETE, `overlays/${channel}/${overlayId}`);248 }249 // /points250 updatePoints(options: any, channel = this.accountId) {251 return this.makeRequest(HTTP.PUT, `points/${channel}`, options);252 }253 getUserPoints(userId: any, channel = this.accountId) {254 return this.makeRequest(HTTP.GET, `points/${channel}/${userId}`);255 }256 deleteUserPoints(userId: any, channel = this.accountId) {257 return this.makeRequest(HTTP.DELETE, `points/${channel}/${userId}`);258 }259 addUserPoints(userId: any, amount: number, channel = this.accountId) {260 return this.makeRequest(HTTP.PUT, `points/${channel}/${userId}/${Math.abs(amount)}`);261 }262 removeUserPoints(userId: any, amount: number, channel = this.accountId) {263 return this.makeRequest(HTTP.PUT, `points/${channel}/${userId}/${-Math.abs(amount)}`);264 }265 getUserRank(userId: any, channel = this.accountId) {266 return this.makeRequest(HTTP.GET, `points/${channel}/${userId}/rank`);267 }268 resetPointsLeaderboard(channel = this.accountId) {269 return this.makeRequest(HTTP.DELETE, `points/${channel}/reset/current`);270 }271 resetAlltimePointsLeaderboard(channel = this.accountId) {272 return this.makeRequest(HTTP.DELETE, `points/${channel}/reset/alltime`);273 }274 getTopPointsUsersAlltime(limit: any, offset: any, channel = this.accountId) {275 return this.makeRequest(HTTP.GET, `points/${channel}/alltime`, {}, { limit, offset });276 }277 getTopPointsUsers(limit: any, offset: any, channel = this.accountId) {278 return this.makeRequest(HTTP.GET, `points/${channel}/top`, {}, { limit, offset });279 }280 // /sessions281 getUserSessionData(channel = this.accountId) {282 return this.makeRequest(HTTP.GET, `sessions/${channel}`);283 }284 updateUserSessionData(options: any, channel = this.accountId) {285 return this.makeRequest(HTTP.PUT, `sessions/${channel}`, options);286 }287 resetUserSessionData(channel = this.accountId) {288 return this.makeRequest(HTTP.PUT, `sessions/${channel}/reset`);289 }290 reloadUserSessionData(channel = this.accountId) {291 return this.makeRequest(HTTP.PUT, `sessions/${channel}/reload`);292 }293 // /songrequest294 getSongRequestSettings(channel = this.accountId) {295 return this.makeRequest(HTTP.GET, `songrequest/${channel}/settings`);296 }297 updateSongRequestSettings(options: any, channel = this.accountId) {298 return this.makeRequest(HTTP.PUT, `songrequest/${channel}/settings`, options);299 }300 getPublicSongRequestSettings(channel = this.accountId) {301 return this.makeRequest(HTTP.GET, `songrequest/${channel}/public`);302 }303 getSongRequestQueue(channel = this.accountId) {304 return this.makeRequest(HTTP.GET, `songrequest/${channel}/queue`);305 }306 createSongRequest(song: any, channel = this.accountId) {307 return this.makeRequest(HTTP.POST, `songrequest/${channel}/queue`, { song });308 }309 getSongRequestHistory(channel = this.accountId) {310 return this.makeRequest(HTTP.GET, `songrequest/${channel}/queue/history`);311 }312 skipCurrentSong(channel = this.accountId) {313 return this.makeRequest(HTTP.DELETE, `songrequest/${channel}/queue/skip`);314 }315 deleteSongRequest(songId: any, channel = this.accountId) {316 return this.makeRequest(HTTP.DELETE, `songrequest/${channel}/queue/${songId}`);317 }318 clearSongRequestQueue(channel = this.accountId) {319 return this.makeRequest(HTTP.DELETE, `songrequest/${channel}/clear`);320 }321 getCurrentSong(channel = this.accountId) {322 return this.makeRequest(HTTP.GET, `songrequest/${channel}/playing`);323 }324 setSongRequestVolume(volumeAmount: string, channel = this.accountId) {325 const volume = parseInt(volumeAmount, 10);326 if (isNaN(volume) || volume < 0 || volume > 100) {327 throw new Error(`volumeAmount should be a number between 0 and 100.`);328 }329 return this.makeRequest(HTTP.POST, `songrequest/${channel}/player/volume`, { volume });330 }331 // /speech332 generateSpeech(text: any, voice = `Joanna`) {333 return this.makeRequest(HTTP.GET, `speech`, {}, { text, voice });334 }335 getSpeechVoices() {336 return this.makeRequest(HTTP.GET, `speech/voices`);337 }338 // /stats339 getDailyStats(channel = this.accountId) {340 return this.makeRequest(HTTP.GET, `stats/${channel}/daily`);341 }342 getMonthlyStats(channel = this.accountId) {343 return this.makeRequest(HTTP.GET, `stats/${channel}/monthly`);344 }345 // /store346 getStoreItems(channel = this.accountId) {347 return this.makeRequest(HTTP.GET, `store/${channel}/items`);348 }349 createStoreItem(options: any, channel = this.accountId) {350 return this.makeRequest(HTTP.POST, `store/${channel}/items`, options);351 }352 getStoreItem(itemId: any, channel = this.accountId) {353 return this.makeRequest(HTTP.GET, `store/${channel}/items/${itemId}`);354 }355 updateStoreItem(itemId: any, options: any, channel = this.accountId) {356 return this.makeRequest(HTTP.PUT, `store/${channel}/items/${itemId}`);357 }358 deleteStoreItem(itemId: any, channel = this.accountId) {359 return this.makeRequest(HTTP.DELETE, `store/${channel}/items/${itemId}`);360 }361 getStoreRedemptions(limit: any, offset: any, pending: any, channel = this.accountId) {362 return this.makeRequest(HTTP.GET, `store/${channel}/redemptions`, {}, { limit, offset, pending });363 }364 getStoreRedemption(redemptionId: any, channel = this.accountId) {365 return this.makeRequest(HTTP.GET, `store/${channel}/redemptions/${redemptionId}`);366 }367 updateStoreRedemption(redemptionId: any, options: any, channel = this.accountId) {368 return this.makeRequest(HTTP.PUT, `store/${channel}/redemptions/${redemptionId}`, options);369 }370 deleteStoreRedemption(redemptionId: any, options: any, channel = this.accountId) {371 return this.makeRequest(HTTP.DELETE, `store/${channel}/redemptions/${redemptionId}`);372 }373 createStoreRedemption(itemId: any, channel = this.accountId) {374 return this.makeRequest(HTTP.POST, `store/${channel}/redemptions/${itemId}`);375 }376 // /streams377 getStreams(channel = this.accountId) {378 return this.makeRequest(HTTP.GET, `streams/${channel}`);379 }380 getStreamStatus(channel = this.accountId) {381 return this.makeRequest(HTTP.GET, `streams/${channel}/live`);382 }383 getStreamDetails(streamId: any, channel = this.accountId) {384 return this.makeRequest(HTTP.GET, `streams/${channel}/${streamId}`);385 }386 // /themes387 getThemes() {388 return this.makeRequest(HTTP.GET, `themes`);389 }390 getTheme(themeId: any) {391 return this.makeRequest(HTTP.GET, `themes/${themeId}`);392 }393 createOverlayFromTheme(themeId: any, options: any) {394 return this.makeRequest(HTTP.POST, `themes/${themeId}`, options);395 }396 rateTheme(themeId: any, rating: any) {397 return this.makeRequest(HTTP.POST, `themes/${themeId}/rate`, { rating });398 }399 getThemeRatingForChannel(themeId: any, channel = this.accountId) {400 return this.makeRequest(HTTP.GET, `themes/${themeId}/${channel}/rating`);401 }402 // /tipping403 getTippingExchangeRates() {404 return this.makeRequest(HTTP.GET, `tipping/rates`);405 }406 getTippingSettings(channel = this.accountId) {407 return this.makeRequest(HTTP.GET, `tipping/${channel}`);408 }409 updateTippingSettings(options: any, channel = this.accountId) {410 return this.makeRequest(HTTP.PUT, `tipping/${channel}`, options);411 }412 // /tips413 getTips(channel = this.accountId) {414 return this.makeRequest(HTTP.GET, `tips/${channel}`);415 }416 createTip(options: any, channel = this.accountId) {417 return this.makeRequest(HTTP.POST, `tips/${channel}`, options);418 }419 getTopTippers(channel = this.accountId) {420 return this.makeRequest(HTTP.GET, `tips/${channel}/top`);421 }422 getTipLeaderboard(channel = this.accountId) {423 return this.makeRequest(HTTP.GET, `tips/${channel}/leaderboard`);424 }425 getRecentTips(channel = this.accountId) {426 return this.makeRequest(HTTP.GET, `tips/${channel}/moderation`);427 }428 getTip(tipId: any, channel = this.accountId) {429 return this.makeRequest(HTTP.GET, `tips/${channel}/${tipId}`);430 }431 updateTip(tipId: any, options: any, channel = this.accountId) {432 return this.makeRequest(HTTP.PUT, `tips/${channel}/${tipId}`, options);433 }434 deleteTip(tipId: any, channel = this.accountId) {435 return this.makeRequest(HTTP.DELETE, `tips/${channel}/${tipId}`);436 }437 // /uploads438 getAssets(channel = this.accountId) {439 return this.makeRequest(HTTP.GET, `uploads/${channel}`);440 }441 deleteAsset(assetId: any, channel = this.accountId) {442 return this.makeRequest(HTTP.DELETE, `uploads/${channel}/${assetId}`);443 }444 // /users445 getCurrentUser() {446 return this.makeRequest(HTTP.GET, `users/current`);447 }448 getUserChannels() {449 return this.makeRequest(HTTP.GET, `users/channels`);450 }451 getChannelAccess() {452 return this.makeRequest(HTTP.GET, `users/access`);453 }...
Api.js
Source:Api.js
...3import { QUERY_LOGS_PAGE_LIMIT, HTML_PAGES, R_PATH_LAST_PART } from '../helpers/constants';4import { BASE_URL } from '../../constants';5class Api {6 baseUrl = BASE_URL;7 async makeRequest(path, method = 'POST', config) {8 const url = `${this.baseUrl}/${path}`;9 try {10 const response = await axios({11 url,12 method,13 ...config,14 });15 return response.data;16 } catch (error) {17 const errorPath = url;18 if (error.response) {19 const { pathname } = document.location;20 const shouldRedirect = pathname !== HTML_PAGES.LOGIN21 && pathname !== HTML_PAGES.INSTALL;22 if (error.response.status === 403 && shouldRedirect) {23 const loginPageUrl = window.location.href24 .replace(R_PATH_LAST_PART, HTML_PAGES.LOGIN);25 window.location.replace(loginPageUrl);26 return false;27 }28 throw new Error(`${errorPath} | ${error.response.data} | ${error.response.status}`);29 }30 throw new Error(`${errorPath} | ${error.message || error}`);31 }32 }33 // Global methods34 GLOBAL_STATUS = { path: 'status', method: 'GET' }35 GLOBAL_TEST_UPSTREAM_DNS = { path: 'test_upstream_dns', method: 'POST' };36 GLOBAL_VERSION = { path: 'version.json', method: 'POST' };37 GLOBAL_UPDATE = { path: 'update', method: 'POST' };38 getGlobalStatus() {39 const { path, method } = this.GLOBAL_STATUS;40 return this.makeRequest(path, method);41 }42 testUpstream(servers) {43 const { path, method } = this.GLOBAL_TEST_UPSTREAM_DNS;44 const config = {45 data: servers,46 headers: { 'Content-Type': 'application/json' },47 };48 return this.makeRequest(path, method, config);49 }50 getGlobalVersion(data) {51 const { path, method } = this.GLOBAL_VERSION;52 const config = {53 data,54 headers: { 'Content-Type': 'application/json' },55 };56 return this.makeRequest(path, method, config);57 }58 getUpdate() {59 const { path, method } = this.GLOBAL_UPDATE;60 return this.makeRequest(path, method);61 }62 // Filtering63 FILTERING_STATUS = { path: 'filtering/status', method: 'GET' };64 FILTERING_ADD_FILTER = { path: 'filtering/add_url', method: 'POST' };65 FILTERING_REMOVE_FILTER = { path: 'filtering/remove_url', method: 'POST' };66 FILTERING_SET_RULES = { path: 'filtering/set_rules', method: 'POST' };67 FILTERING_REFRESH = { path: 'filtering/refresh', method: 'POST' };68 FILTERING_SET_URL = { path: 'filtering/set_url', method: 'POST' };69 FILTERING_CONFIG = { path: 'filtering/config', method: 'POST' };70 FILTERING_CHECK_HOST = { path: 'filtering/check_host', method: 'GET' };71 getFilteringStatus() {72 const { path, method } = this.FILTERING_STATUS;73 return this.makeRequest(path, method);74 }75 refreshFilters(config) {76 const { path, method } = this.FILTERING_REFRESH;77 const parameters = {78 data: config,79 headers: { 'Content-Type': 'application/json' },80 };81 return this.makeRequest(path, method, parameters);82 }83 addFilter(config) {84 const { path, method } = this.FILTERING_ADD_FILTER;85 const parameters = {86 data: config,87 headers: { 'Content-Type': 'application/json' },88 };89 return this.makeRequest(path, method, parameters);90 }91 removeFilter(config) {92 const { path, method } = this.FILTERING_REMOVE_FILTER;93 const parameters = {94 data: config,95 headers: { 'Content-Type': 'application/json' },96 };97 return this.makeRequest(path, method, parameters);98 }99 setRules(rules) {100 const { path, method } = this.FILTERING_SET_RULES;101 const parameters = {102 data: rules,103 headers: { 'Content-Type': 'text/plain' },104 };105 return this.makeRequest(path, method, parameters);106 }107 setFiltersConfig(config) {108 const { path, method } = this.FILTERING_CONFIG;109 const parameters = {110 data: config,111 headers: { 'Content-Type': 'application/json' },112 };113 return this.makeRequest(path, method, parameters);114 }115 setFilterUrl(config) {116 const { path, method } = this.FILTERING_SET_URL;117 const parameters = {118 data: config,119 headers: { 'Content-Type': 'application/json' },120 };121 return this.makeRequest(path, method, parameters);122 }123 checkHost(params) {124 const { path, method } = this.FILTERING_CHECK_HOST;125 const url = getPathWithQueryString(path, params);126 return this.makeRequest(url, method);127 }128 // Parental129 PARENTAL_STATUS = { path: 'parental/status', method: 'GET' };130 PARENTAL_ENABLE = { path: 'parental/enable', method: 'POST' };131 PARENTAL_DISABLE = { path: 'parental/disable', method: 'POST' };132 getParentalStatus() {133 const { path, method } = this.PARENTAL_STATUS;134 return this.makeRequest(path, method);135 }136 enableParentalControl() {137 const { path, method } = this.PARENTAL_ENABLE;138 const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded139 const config = {140 data: parameter,141 headers: { 'Content-Type': 'text/plain' },142 };143 return this.makeRequest(path, method, config);144 }145 disableParentalControl() {146 const { path, method } = this.PARENTAL_DISABLE;147 return this.makeRequest(path, method);148 }149 // Safebrowsing150 SAFEBROWSING_STATUS = { path: 'safebrowsing/status', method: 'GET' };151 SAFEBROWSING_ENABLE = { path: 'safebrowsing/enable', method: 'POST' };152 SAFEBROWSING_DISABLE = { path: 'safebrowsing/disable', method: 'POST' };153 getSafebrowsingStatus() {154 const { path, method } = this.SAFEBROWSING_STATUS;155 return this.makeRequest(path, method);156 }157 enableSafebrowsing() {158 const { path, method } = this.SAFEBROWSING_ENABLE;159 return this.makeRequest(path, method);160 }161 disableSafebrowsing() {162 const { path, method } = this.SAFEBROWSING_DISABLE;163 return this.makeRequest(path, method);164 }165 // Safesearch166 SAFESEARCH_STATUS = { path: 'safesearch/status', method: 'GET' };167 SAFESEARCH_ENABLE = { path: 'safesearch/enable', method: 'POST' };168 SAFESEARCH_DISABLE = { path: 'safesearch/disable', method: 'POST' };169 getSafesearchStatus() {170 const { path, method } = this.SAFESEARCH_STATUS;171 return this.makeRequest(path, method);172 }173 enableSafesearch() {174 const { path, method } = this.SAFESEARCH_ENABLE;175 return this.makeRequest(path, method);176 }177 disableSafesearch() {178 const { path, method } = this.SAFESEARCH_DISABLE;179 return this.makeRequest(path, method);180 }181 // Language182 CURRENT_LANGUAGE = { path: 'i18n/current_language', method: 'GET' };183 CHANGE_LANGUAGE = { path: 'i18n/change_language', method: 'POST' };184 getCurrentLanguage() {185 const { path, method } = this.CURRENT_LANGUAGE;186 return this.makeRequest(path, method);187 }188 changeLanguage(lang) {189 const { path, method } = this.CHANGE_LANGUAGE;190 const parameters = {191 data: lang,192 headers: { 'Content-Type': 'text/plain' },193 };194 return this.makeRequest(path, method, parameters);195 }196 // DHCP197 DHCP_STATUS = { path: 'dhcp/status', method: 'GET' };198 DHCP_SET_CONFIG = { path: 'dhcp/set_config', method: 'POST' };199 DHCP_FIND_ACTIVE = { path: 'dhcp/find_active_dhcp', method: 'POST' };200 DHCP_INTERFACES = { path: 'dhcp/interfaces', method: 'GET' };201 DHCP_ADD_STATIC_LEASE = { path: 'dhcp/add_static_lease', method: 'POST' };202 DHCP_REMOVE_STATIC_LEASE = { path: 'dhcp/remove_static_lease', method: 'POST' };203 DHCP_RESET = { path: 'dhcp/reset', method: 'POST' };204 DHCP_LEASES_RESET = { path: 'dhcp/reset_leases', method: 'POST' };205 getDhcpStatus() {206 const { path, method } = this.DHCP_STATUS;207 return this.makeRequest(path, method);208 }209 getDhcpInterfaces() {210 const { path, method } = this.DHCP_INTERFACES;211 return this.makeRequest(path, method);212 }213 setDhcpConfig(config) {214 const { path, method } = this.DHCP_SET_CONFIG;215 const parameters = {216 data: config,217 headers: { 'Content-Type': 'application/json' },218 };219 return this.makeRequest(path, method, parameters);220 }221 findActiveDhcp(name) {222 const { path, method } = this.DHCP_FIND_ACTIVE;223 const parameters = {224 data: name,225 headers: { 'Content-Type': 'text/plain' },226 };227 return this.makeRequest(path, method, parameters);228 }229 addStaticLease(config) {230 const { path, method } = this.DHCP_ADD_STATIC_LEASE;231 const parameters = {232 data: config,233 headers: { 'Content-Type': 'application/json' },234 };235 return this.makeRequest(path, method, parameters);236 }237 removeStaticLease(config) {238 const { path, method } = this.DHCP_REMOVE_STATIC_LEASE;239 const parameters = {240 data: config,241 headers: { 'Content-Type': 'application/json' },242 };243 return this.makeRequest(path, method, parameters);244 }245 resetDhcp() {246 const { path, method } = this.DHCP_RESET;247 return this.makeRequest(path, method);248 }249 resetDhcpLeases() {250 const { path, method } = this.DHCP_LEASES_RESET;251 return this.makeRequest(path, method);252 }253 // Installation254 INSTALL_GET_ADDRESSES = { path: 'install/get_addresses', method: 'GET' };255 INSTALL_CONFIGURE = { path: 'install/configure', method: 'POST' };256 INSTALL_CHECK_CONFIG = { path: 'install/check_config', method: 'POST' };257 getDefaultAddresses() {258 const { path, method } = this.INSTALL_GET_ADDRESSES;259 return this.makeRequest(path, method);260 }261 setAllSettings(config) {262 const { path, method } = this.INSTALL_CONFIGURE;263 const parameters = {264 data: config,265 headers: { 'Content-Type': 'application/json' },266 };267 return this.makeRequest(path, method, parameters);268 }269 checkConfig(config) {270 const { path, method } = this.INSTALL_CHECK_CONFIG;271 const parameters = {272 data: config,273 headers: { 'Content-Type': 'application/json' },274 };275 return this.makeRequest(path, method, parameters);276 }277 // DNS-over-HTTPS and DNS-over-TLS278 TLS_STATUS = { path: 'tls/status', method: 'GET' };279 TLS_CONFIG = { path: 'tls/configure', method: 'POST' };280 TLS_VALIDATE = { path: 'tls/validate', method: 'POST' };281 getTlsStatus() {282 const { path, method } = this.TLS_STATUS;283 return this.makeRequest(path, method);284 }285 setTlsConfig(config) {286 const { path, method } = this.TLS_CONFIG;287 const parameters = {288 data: config,289 headers: { 'Content-Type': 'application/json' },290 };291 return this.makeRequest(path, method, parameters);292 }293 validateTlsConfig(config) {294 const { path, method } = this.TLS_VALIDATE;295 const parameters = {296 data: config,297 headers: { 'Content-Type': 'application/json' },298 };299 return this.makeRequest(path, method, parameters);300 }301 // Per-client settings302 GET_CLIENTS = { path: 'clients', method: 'GET' };303 FIND_CLIENTS = { path: 'clients/find', method: 'GET' };304 ADD_CLIENT = { path: 'clients/add', method: 'POST' };305 DELETE_CLIENT = { path: 'clients/delete', method: 'POST' };306 UPDATE_CLIENT = { path: 'clients/update', method: 'POST' };307 getClients() {308 const { path, method } = this.GET_CLIENTS;309 return this.makeRequest(path, method);310 }311 addClient(config) {312 const { path, method } = this.ADD_CLIENT;313 const parameters = {314 data: config,315 headers: { 'Content-Type': 'application/json' },316 };317 return this.makeRequest(path, method, parameters);318 }319 deleteClient(config) {320 const { path, method } = this.DELETE_CLIENT;321 const parameters = {322 data: config,323 headers: { 'Content-Type': 'application/json' },324 };325 return this.makeRequest(path, method, parameters);326 }327 updateClient(config) {328 const { path, method } = this.UPDATE_CLIENT;329 const parameters = {330 data: config,331 headers: { 'Content-Type': 'application/json' },332 };333 return this.makeRequest(path, method, parameters);334 }335 findClients(params) {336 const { path, method } = this.FIND_CLIENTS;337 const url = getPathWithQueryString(path, params);338 return this.makeRequest(url, method);339 }340 // DNS access settings341 ACCESS_LIST = { path: 'access/list', method: 'GET' };342 ACCESS_SET = { path: 'access/set', method: 'POST' };343 getAccessList() {344 const { path, method } = this.ACCESS_LIST;345 return this.makeRequest(path, method);346 }347 setAccessList(config) {348 const { path, method } = this.ACCESS_SET;349 const parameters = {350 data: config,351 headers: { 'Content-Type': 'application/json' },352 };353 return this.makeRequest(path, method, parameters);354 }355 // DNS rewrites356 REWRITES_LIST = { path: 'rewrite/list', method: 'GET' };357 REWRITE_ADD = { path: 'rewrite/add', method: 'POST' };358 REWRITE_DELETE = { path: 'rewrite/delete', method: 'POST' };359 getRewritesList() {360 const { path, method } = this.REWRITES_LIST;361 return this.makeRequest(path, method);362 }363 addRewrite(config) {364 const { path, method } = this.REWRITE_ADD;365 const parameters = {366 data: config,367 headers: { 'Content-Type': 'application/json' },368 };369 return this.makeRequest(path, method, parameters);370 }371 deleteRewrite(config) {372 const { path, method } = this.REWRITE_DELETE;373 const parameters = {374 data: config,375 headers: { 'Content-Type': 'application/json' },376 };377 return this.makeRequest(path, method, parameters);378 }379 // Blocked services380 BLOCKED_SERVICES_LIST = { path: 'blocked_services/list', method: 'GET' };381 BLOCKED_SERVICES_SET = { path: 'blocked_services/set', method: 'POST' };382 getBlockedServices() {383 const { path, method } = this.BLOCKED_SERVICES_LIST;384 return this.makeRequest(path, method);385 }386 setBlockedServices(config) {387 const { path, method } = this.BLOCKED_SERVICES_SET;388 const parameters = {389 data: config,390 headers: { 'Content-Type': 'application/json' },391 };392 return this.makeRequest(path, method, parameters);393 }394 // Settings for statistics395 GET_STATS = { path: 'stats', method: 'GET' };396 STATS_INFO = { path: 'stats_info', method: 'GET' };397 STATS_CONFIG = { path: 'stats_config', method: 'POST' };398 STATS_RESET = { path: 'stats_reset', method: 'POST' };399 getStats() {400 const { path, method } = this.GET_STATS;401 return this.makeRequest(path, method);402 }403 getStatsInfo() {404 const { path, method } = this.STATS_INFO;405 return this.makeRequest(path, method);406 }407 setStatsConfig(data) {408 const { path, method } = this.STATS_CONFIG;409 const config = {410 data,411 headers: { 'Content-Type': 'application/json' },412 };413 return this.makeRequest(path, method, config);414 }415 resetStats() {416 const { path, method } = this.STATS_RESET;417 return this.makeRequest(path, method);418 }419 // Query log420 GET_QUERY_LOG = { path: 'querylog', method: 'GET' };421 QUERY_LOG_CONFIG = { path: 'querylog_config', method: 'POST' };422 QUERY_LOG_INFO = { path: 'querylog_info', method: 'GET' };423 QUERY_LOG_CLEAR = { path: 'querylog_clear', method: 'POST' };424 getQueryLog(params) {425 const { path, method } = this.GET_QUERY_LOG;426 // eslint-disable-next-line no-param-reassign427 params.limit = QUERY_LOGS_PAGE_LIMIT;428 const url = getPathWithQueryString(path, params);429 return this.makeRequest(url, method);430 }431 getQueryLogInfo() {432 const { path, method } = this.QUERY_LOG_INFO;433 return this.makeRequest(path, method);434 }435 setQueryLogConfig(data) {436 const { path, method } = this.QUERY_LOG_CONFIG;437 const config = {438 data,439 headers: { 'Content-Type': 'application/json' },440 };441 return this.makeRequest(path, method, config);442 }443 clearQueryLog() {444 const { path, method } = this.QUERY_LOG_CLEAR;445 return this.makeRequest(path, method);446 }447 // Login448 LOGIN = { path: 'login', method: 'POST' };449 login(data) {450 const { path, method } = this.LOGIN;451 const config = {452 data,453 headers: { 'Content-Type': 'application/json' },454 };455 return this.makeRequest(path, method, config);456 }457 // Profile458 GET_PROFILE = { path: 'profile', method: 'GET' };459 getProfile() {460 const { path, method } = this.GET_PROFILE;461 return this.makeRequest(path, method);462 }463 // DNS config464 GET_DNS_CONFIG = { path: 'dns_info', method: 'GET' };465 SET_DNS_CONFIG = { path: 'dns_config', method: 'POST' };466 getDnsConfig() {467 const { path, method } = this.GET_DNS_CONFIG;468 return this.makeRequest(path, method);469 }470 setDnsConfig(data) {471 const { path, method } = this.SET_DNS_CONFIG;472 const config = {473 data,474 headers: { 'Content-Type': 'application/json' },475 };476 return this.makeRequest(path, method, config);477 }478}479const apiClient = new Api();...
useRequest.test.jsx
Source:useRequest.test.jsx
1import React from 'react';2import { act } from 'react-dom/test-utils';3import { mount } from 'enzyme';4import { mountWithContexts } from '../../testUtils/enzymeHelpers';5import useRequest, { useDeleteItems } from './useRequest';6function TestInner() {7 return <div />;8}9function Test({ makeRequest, initialValue = {} }) {10 const request = useRequest(makeRequest, initialValue);11 return <TestInner {...request} />;12}13function DeleteTest({ makeRequest, args = {} }) {14 const request = useDeleteItems(makeRequest, args);15 return <TestInner {...request} />;16}17describe('useRequest hooks', () => {18 describe('useRequest', () => {19 test('should return initial value as result', async () => {20 const makeRequest = jest.fn();21 makeRequest.mockResolvedValue({ data: 'foo' });22 const wrapper = mount(23 <Test24 makeRequest={makeRequest}25 initialValue={{26 initial: true,27 }}28 />29 );30 expect(wrapper.find('TestInner').prop('result')).toEqual({31 initial: true,32 });33 });34 test('should return result', async () => {35 const makeRequest = jest.fn();36 makeRequest.mockResolvedValue({ data: 'foo' });37 const wrapper = mount(<Test makeRequest={makeRequest} />);38 await act(async () => {39 wrapper.find('TestInner').invoke('request')();40 });41 wrapper.update();42 expect(wrapper.find('TestInner').prop('result')).toEqual({ data: 'foo' });43 });44 test('should is isLoading flag', async () => {45 const makeRequest = jest.fn();46 let resolve;47 const promise = new Promise(r => {48 resolve = r;49 });50 makeRequest.mockReturnValue(promise);51 const wrapper = mount(<Test makeRequest={makeRequest} />);52 await act(async () => {53 wrapper.find('TestInner').invoke('request')();54 });55 wrapper.update();56 expect(wrapper.find('TestInner').prop('isLoading')).toEqual(true);57 await act(async () => {58 resolve({ data: 'foo' });59 });60 wrapper.update();61 expect(wrapper.find('TestInner').prop('isLoading')).toEqual(false);62 expect(wrapper.find('TestInner').prop('result')).toEqual({ data: 'foo' });63 });64 test('should invoke request function', async () => {65 const makeRequest = jest.fn();66 makeRequest.mockResolvedValue({ data: 'foo' });67 const wrapper = mount(<Test makeRequest={makeRequest} />);68 expect(makeRequest).not.toHaveBeenCalled();69 await act(async () => {70 wrapper.find('TestInner').invoke('request')();71 });72 wrapper.update();73 expect(makeRequest).toHaveBeenCalledTimes(1);74 });75 test('should return error thrown from request function', async () => {76 const error = new Error('error');77 const makeRequest = () => {78 throw error;79 };80 const wrapper = mount(<Test makeRequest={makeRequest} />);81 await act(async () => {82 wrapper.find('TestInner').invoke('request')();83 });84 wrapper.update();85 expect(wrapper.find('TestInner').prop('error')).toEqual(error);86 });87 test('should reset error/result on each request', async () => {88 const error = new Error('error');89 const makeRequest = throwError => {90 if (throwError) {91 throw error;92 }93 return { data: 'foo' };94 };95 const wrapper = mount(<Test makeRequest={makeRequest} />);96 await act(async () => {97 wrapper.find('TestInner').invoke('request')(true);98 });99 wrapper.update();100 expect(wrapper.find('TestInner').prop('result')).toEqual({});101 expect(wrapper.find('TestInner').prop('error')).toEqual(error);102 await act(async () => {103 wrapper.find('TestInner').invoke('request')();104 });105 wrapper.update();106 expect(wrapper.find('TestInner').prop('result')).toEqual({ data: 'foo' });107 expect(wrapper.find('TestInner').prop('error')).toEqual(null);108 await act(async () => {109 wrapper.find('TestInner').invoke('request')(true);110 });111 wrapper.update();112 expect(wrapper.find('TestInner').prop('result')).toEqual({});113 expect(wrapper.find('TestInner').prop('error')).toEqual(error);114 });115 test('should not update state after unmount', async () => {116 const makeRequest = jest.fn();117 let resolve;118 const promise = new Promise(r => {119 resolve = r;120 });121 makeRequest.mockReturnValue(promise);122 const wrapper = mount(<Test makeRequest={makeRequest} />);123 expect(makeRequest).not.toHaveBeenCalled();124 await act(async () => {125 wrapper.find('TestInner').invoke('request')();126 });127 wrapper.unmount();128 await act(async () => {129 resolve({ data: 'foo' });130 });131 });132 });133 describe('useDeleteItems', () => {134 test('should invoke delete function', async () => {135 const makeRequest = jest.fn();136 makeRequest.mockResolvedValue({ data: 'foo' });137 const wrapper = mountWithContexts(138 <DeleteTest139 makeRequest={makeRequest}140 args={{141 qsConfig: {},142 fetchItems: () => {},143 }}144 />145 );146 expect(makeRequest).not.toHaveBeenCalled();147 await act(async () => {148 wrapper.find('TestInner').invoke('deleteItems')();149 });150 wrapper.update();151 expect(makeRequest).toHaveBeenCalledTimes(1);152 });153 test('should return error object thrown by function', async () => {154 const error = new Error('error');155 const makeRequest = () => {156 throw error;157 };158 const wrapper = mountWithContexts(159 <DeleteTest160 makeRequest={makeRequest}161 args={{162 qsConfig: {},163 fetchItems: () => {},164 }}165 />166 );167 await act(async () => {168 wrapper.find('TestInner').invoke('deleteItems')();169 });170 wrapper.update();171 expect(wrapper.find('TestInner').prop('deletionError')).toEqual(error);172 });173 test('should dismiss error', async () => {174 const error = new Error('error');175 const makeRequest = () => {176 throw error;177 };178 const wrapper = mountWithContexts(179 <DeleteTest180 makeRequest={makeRequest}181 args={{182 qsConfig: {},183 fetchItems: () => {},184 }}185 />186 );187 await act(async () => {188 wrapper.find('TestInner').invoke('deleteItems')();189 });190 wrapper.update();191 await act(async () => {192 wrapper.find('TestInner').invoke('clearDeletionError')();193 });194 wrapper.update();195 expect(wrapper.find('TestInner').prop('deletionError')).toEqual(null);196 });197 });...
Using AI Code Generation
1var wpt = require('wpt');2var options = {3};4wpt.makeRequest(options, function(err, data) {5 if (err) {6 console.log(err);7 } else {8 console.log(data);9 }10});11var wpt = require('wpt');12var options = {13};14wpt.makeRequest(options, function(err, data) {15 if (err) {16 console.log(err);17 } else {18 console.log(data);19 }20});
Using AI Code Generation
1var wpt = require('./wpt.js');2 if (err) {3 console.log(err);4 } else {5 console.log(data);6 }7});8var request = require('request');9var wpt = {};10wpt.makeRequest = function(url, location, callback) {11 var options = {12 };13 request(options, function(err, res, body) {14 if (err) {15 callback(err);16 } else {17 callback(null, body);18 }19 });20};21module.exports = wpt;
Using AI Code Generation
1var wpt = require('wpt.js');2var options = {3};4var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdefghijklmnopqrstu');5wpt.makeRequest(url, options, function(err, data) {6 if (err) {7 console.log(err);8 } else {9 console.log(data);10 }11});12var WebPageTest = require('webpagetest');13module.exports = function(apiKey, serverUrl) {14 var wpt = new WebPageTest(serverUrl, apiKey);15 return {16 makeRequest: function(url, options, callback) {17 wpt.runTest(url, options, callback);18 }19 };20};
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.8e7b2a2e1a7d2f9c1f7b6a2b2f3b3a3b');3wpt.makeRequest('www.google.com', function(err, data) {4 if (err) return console.error(err);5 console.log(data);6});7### WebPageTest(url, apiKey)8### WebPageTest.getLocations(callback)9with two arguments: `(err, data)`, where `err` is an error object, and `data` is10### WebPageTest.getTests(callback)11arguments: `(err, data)`, where `err` is an error object, and `data` is an array
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!!