Best JavaScript code snippet using wpt
communication.mjs
Source:communication.mjs
1function getCookie(name) {2 let cookieValue = null;3 if (document.cookie && document.cookie !== "") {4 const cookies = document.cookie.split(";");5 for (let i = 0; i < cookies.length; i++) {6 const cookie = cookies[i].trim();7 // Does this cookie string begin with the name we want?8 if (cookie.substring(0, name.length + 1) === (name + "=")) {9 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));10 break;11 }12 }13 }14 return cookieValue;15}16const csrftoken = getCookie("csrftoken");17/**18 * Creates skeleton settings for fetching.19 * @returns {object}: Common fetch settings.20 */21function makeFetchInit() {22 return {23 method: "POST",24 credentials: "same-origin",25 headers: {"X-CSRFToken": csrftoken, 'Content-Type': 'application/json'}26 };27}28/**29 * Fetches a list of available projects.30 * @param {string} projectsUrl URL to server's interface.31 * @returns {Promise} A promise that resolves to server's response.32 */33function fetchProjectList(projectsUrl) {34 const fetchInit = makeFetchInit();35 fetchInit["body"] = JSON.stringify({"type": "project list?"});36 return fetch(projectsUrl, fetchInit).then(function(response) {37 if (!response.ok) {38 return response.text().then(function(message) {39 throw new Error(`Failed to load project list: ${message}`);40 });41 }42 return response.json();43 });44}45/**46 * Creates a new project.47 * @param {string} projectName Project name.48 * @param {string} projectsUrl URL to server's interface.49 * @returns {Promise} A promise that resolves to server's response.50 */51function createProject(projectName, projectsUrl) {52 const fetchInit = makeFetchInit();53 fetchInit["body"] = JSON.stringify({type: "create project?", name: projectName});54 return fetch(projectsUrl, fetchInit).then(function(response) {55 if (!response.ok) {56 return response.text().then(function(message) {57 throw new Error(`Failed to create project: ${message}`);58 });59 }60 return response.json();61 });62}63/**64 * Deletes a project.65 * @param {number} projectId Project id.66 * @param {string} projectsUrl URL to server's interface.67 * @returns {Promise} A promise that resolves to server's response.68 */69function destroyProject(projectId, projectsUrl) {70 const fetchInit = makeFetchInit();71 fetchInit["body"] = JSON.stringify({type: "destroy project?", id: projectId});72 return fetch(projectsUrl, fetchInit).then(function(response) {73 if (!response.ok) {74 return response.text().then(function(message) {75 throw new Error(`Failed to delete project: ${message}`);76 });77 }78 return response.json();79 });80}81/**82 * Fetches model or analysis data from server.83 * @param {string} queryType Fetch query type.84 * @param {number} projectId Project id.85 * @param {string} url URL to server's interface.86 * @param {object} extraBody Additional fields for fetch query.87 * @returns {Promise} A promise that resolves to server's response.88 */89function fetchData(queryType, projectId, url, extraBody = {}) {90 const fetchInit = makeFetchInit();91 fetchInit["body"] = JSON.stringify({type: queryType, projectId: projectId, ...extraBody});92 return fetch(url, fetchInit).then(function(response) {93 if (!response.ok) {94 return response.text().then(function(message) {95 throw new Error(`Failed to fetch ${queryType}: ${message}`);96 });97 }98 return response.json();99 });100}101/**102 * Sends database commit data to server.103 * @param {Object} commitData Commit contents.104 * @param (string} message Commit message.105 * @param {number} projectId Project's id.106 * @param {string} modelUrl Model interface URL.107 * @returns {Promise} Promise that resolves to server's response object.108 */109function commit(commitData, message, projectId, modelUlr) {110 const fetchInit = makeFetchInit();111 fetchInit.body = JSON.stringify({type: "commit", projectId: projectId, message: message, ...commitData});112 return fetch(modelUlr, fetchInit).then(function(response) {113 if (!response.ok) {114 return response.text().then(function(message) {115 throw new Error(message);116 });117 }118 return response.json();119 });120}121/**122 * Fetches project's current execution.123 * @param {number} projectId Project id.124 * @param {string} executionsUrl URL to server's interface.125 * @returns {Promise} A promise that resolves to server's response.126 */127function fetchCurrentExecution(projectId, executionsUrl) {128 const fetchInit = makeFetchInit();129 fetchInit.body = JSON.stringify({type: "current execution?", projectId: projectId});130 return fetch(executionsUrl, fetchInit).then(function(response) {131 if (!response.ok) {132 return response.text().then(function(message) {133 throw new Error(`Failed to fetch current run: ${message}`);134 });135 }136 return response.json()137 });138}139/**140 * Starts execution.141 * @param {number} projectId Project id.142 * @param {string} executionsUrl URL to server's interface.143 * @param {string[]} scenarios Active scenario names.144 * @returns {Promise} A promise that resolves to server's response.145 */146function executeExecution(projectId, executionsUrl, scenarios) {147 const fetchInit = makeFetchInit();148 fetchInit["body"] = JSON.stringify({type: "execute?", projectId: projectId, scenarios: scenarios});149 return fetch(executionsUrl, fetchInit).then(function(response) {150 if (!response.ok) {151 return response.text().then(function(message) {152 throw new Error(`Failed to execute: ${message}`);153 });154 }155 return response.json();156 });157}158/**159 * Aborts execution.160 * @param {number} projectId Project id.161 * @param {string} executionsUrl URL to server's interface.162 * @returns {Promise} A promise that resolves to server's response.163 */164function abortExecution(projectId, executionsUrl) {165 const fetchInit = makeFetchInit();166 fetchInit["body"] = JSON.stringify({type: "abort?", projectId: projectId});167 return fetch(executionsUrl, fetchInit).then(function(response) {168 if (!response.ok) {169 return response.text().then(function(message) {170 throw new Error(`Failed to abort execution: ${message}`);171 });172 }173 return response.json();174 });175}176/**177 * Fetches execution status from server.178 * @param {number} projectId Project id.179 * @param {string} executionsUrl URL to server's interface.180 * @returns {Promise} A promise that resolves to server's response.181 */182function fetchExecutionBriefing(projectId, executionsUrl) {183 const fetchInit = makeFetchInit();184 fetchInit["body"] = JSON.stringify({type: "briefing?", projectId: projectId});185 return fetch(executionsUrl, fetchInit).then(function(response) {186 if (!response.ok) {187 return response.text().then(function(message) {188 throw new Error(`Failed to fetch execution status: ${message}`);189 });190 }191 return response.json();192 });193}194/**195 * Fetches summary data from server.196 * @param {number} projectId Project id.197 * @param {string} summaryUrl URL to server's interface.198 * @param {string} scenarioExecutionId Scenario execution id.199 * @returns {Promise} A promise that resolves to server's response.200 */201function fetchSummary(projectId, summaryUrl, scenarioExecutionId) {202 const fetchInit = makeFetchInit();203 fetchInit.body = JSON.stringify({204 type: "summary?",205 projectId: projectId,206 scenarioExecutionId: scenarioExecutionId,207 });208 return fetch(summaryUrl, fetchInit).then(function(response) {209 if (!response.ok) {210 return response.text().then(function(message) {211 throw new Error(`Failed to load summary: ${message}`);212 });213 }214 return response.json();215 });216}217/**218 * Fetches tool output directory path from server.219 * @param {number} projectId Project id.220 * @param {string} summaryUrl URL to server's interface.221 * @param {string} scenarioExecutionId Scenario execution id.222 * @returns {Promise} A promise that resolves to server's response.223 */224function fetchOutputDirectory(projectId, summaryUrl, scenarioExecutionId) {225 const fetchInit = makeFetchInit();226 fetchInit.body = JSON.stringify({227 type: "output directory?",228 projectId: projectId,229 scenarioExecutionId: scenarioExecutionId,230 });231 return fetch(summaryUrl, fetchInit).then(function(response) {232 if (!response.ok) {233 return response.text().then(function(message) {234 throw new Error(`Failed to load output directory path: ${message}`);235 });236 }237 return response.json();238 });239}240/**241 * Fetches executed scenarios from server.242 * @param {number} projectId Project id.243 * @param {string} summaryUrl URL to server's interface.244 * @returns {Promise} A promise that resolves to server's response.245 */246function fetchExecutedScenarioList(projectId, summaryUrl) {247 const fetchInit = makeFetchInit();248 fetchInit.body = JSON.stringify({type: "scenario list?", projectId: projectId});249 return fetch(summaryUrl, fetchInit).then(function(response) {250 if (!response.ok) {251 return response.text().then(function(message) {252 throw new Error(`Failed to load scenarios: ${message}`);253 });254 }255 return response.json();256 });257}258/**259 * Fetches result alternative from server.260 * @param {number} projectId Project id.261 * @param {string} summaryUrl URL to server's interface.262 * @param {string} scenarioExecutionId Scenario execution id.263 * @returns {Promise} A promise that resolves to server's response.264 */265function fetchResultAlternative(projectId, summaryUrl, scenarioExecutionId) {266 const fetchInit = makeFetchInit();267 fetchInit.body = JSON.stringify({type: "result alternative?",268 projectId: projectId,269 scenarioExecutionId: scenarioExecutionId,270 });271 return fetch(summaryUrl, fetchInit).then(function(response) {272 if (!response.ok) {273 return response.text().then(function(message) {274 throw new Error(`Failed to fetch result alternative: ${message}`);275 });276 }277 return response.json();278 });279}280/**281 * Requests server to delete a scenario execution.282 * @param {number} projectId Project id.283 * @param {string} summaryUrl URL to server's interface.284 * @param {string} scenarioExecutionId Scenario execution id.285 */286function destroyScenarioExecution(projectId, summaryUrl, scenarioExecutionId) {287 const fetchInit = makeFetchInit();288 fetchInit.body = JSON.stringify({type: "destroy execution?",289 projectId: projectId,290 scenarioExecutionId: scenarioExecutionId,291 });292 return fetch(summaryUrl, fetchInit).then(function(response) {293 if (!response.ok) {294 return response.text().then(function(message) {295 throw new Error(`Failed to destroy scenario execution: ${message}`);296 });297 }298 return;299 });300}301/**302 * Fetches a list of available examples.303 * @param {number} projectId Project id.304 * @param {string} examplesUrl URL to server's interface.305 * @returns {Promise} A promise that resolves to server's response.306 */307function fetchExampleList(projectId, examplesUrl) {308 const fetchInit = makeFetchInit();309 fetchInit["body"] = JSON.stringify({type: "example list?", projectId: projectId});310 return fetch(examplesUrl, fetchInit).then(function(response) {311 if (!response.ok) {312 return response.text().then(function(message) {313 throw new Error(`Failed to load example list: ${message}`);314 });315 }316 return response.json();317 });318}319/**320 * Requests to add an example to model database.321 * @param {number} projectId Project id.322 * @param {string} examplesUrl URL to server's interface.323 * @param {string} exampleName Name of the example to add.324 * @returns {Promise} A promise that resolves to server's response.325 */326function addExample(projectId, examplesUrl, exampleName) {327 const fetchInit = makeFetchInit();328 fetchInit["body"] = JSON.stringify({type: "add to model", name: exampleName, projectId: projectId});329 return fetch(examplesUrl, fetchInit).then(function(response) {330 if (!response.ok) {331 return response.text().then(function(message) {332 throw new Error(`Failed to add example to model: ${message}`);333 });334 }335 return response.json();336 });337}338export {339 csrftoken,340 makeFetchInit,341 fetchData,342 commit,343 fetchProjectList,344 createProject,345 destroyProject,346 fetchCurrentExecution,347 executeExecution,348 abortExecution,349 fetchExecutionBriefing,350 fetchExecutedScenarioList,351 fetchSummary,352 fetchOutputDirectory,353 fetchResultAlternative,354 destroyScenarioExecution,355 fetchExampleList,356 addExample,...
useAppQuery.js
Source:useAppQuery.js
1import { useAuthenticatedFetch } from "./useAuthenticatedFetch";2import { useMemo } from "react";3import { useQuery } from "react-query";4/**5 * A hook for querying your custom app data.6 * @desc A thin wrapper around useAuthenticatedFetch and react-query's useQuery.7 *8 * @param {Object} options - The options for your query. Accepts 3 keys:9 *10 * 1. url: The URL to query. E.g: /api/widgets/1`11 * 2. fetchInit: The init options for fetch. See: https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters12 * 3. reactQueryOptions: The options for `useQuery`. See: https://react-query.tanstack.com/reference/useQuery13 *14 * @returns Return value of useQuery. See: https://react-query.tanstack.com/reference/useQuery.15 */16export const useAppQuery = ({ url, fetchInit = {}, reactQueryOptions }) => {17 const authenticatedFetch = useAuthenticatedFetch();18 const fetch = useMemo(() => {19 return async () => {20 const response = await authenticatedFetch(url, fetchInit);21 return response.json();22 };23 }, [url, JSON.stringify(fetchInit)]);24 return useQuery(url, fetch, {25 ...reactQueryOptions,26 refetchOnWindowFocus: false,27 });...
fetch.ts
Source:fetch.ts
1interface ObjDate {2 [key: string]: unknown;3}4interface Init extends Omit<RequestInit, 'method'|'body' >{5 body?: BodyInit|ObjDate|null;6}7function isObjDate (body: BodyInit|ObjDate|undefined|null): body is ObjDate {8 return Boolean(body ?? typeof body === 'object')9}10export default function wahtFetch (input: RequestInfo, method: 'GET'|'POST'| 'PUT'| 'DELETE', init: Init|undefined): Promise<Response> {11 let fetchInit: RequestInit = { method }12 if (init !== undefined) {13 if (isObjDate(init.body)) {14 init.body = JSON.stringify(init.body)15 }16 fetchInit = { ...fetchInit, ...init, body: init.body }17 if (fetchInit.method !== 'GET') {18 fetchInit.headers = {19 'Content-Type': 'application/json',20 ...fetchInit.headers21 }22 }23 }24 return fetch(input, fetchInit)...
Using AI Code Generation
1const wptFetch = require('wpt-fetch');2const fetchInit = {3 headers: {4 },5 body: JSON.stringify({6 })7};8.then((response) => {9 console.log(response);10})11.catch((error) => {12 console.log(error);13});14### fetchUrl(url, options)15### fetchInit(url, fetchInit)
Using AI Code Generation
1const wptoolkit = require('wptoolkit');2wptoolkit.fetchInit();3.then(function(data){4 console.log(data)5})6.then(function(data){7 console.log(data)8})9### fetchInit(options)10Type: `object` Default: `{}`11### fetch(url, options)12Type: `object` Default: `{}`13Type: `object` Default: `{}`14### fetchAbort()15MIT © [Arun Kumar](
Using AI Code Generation
1const fetchInit = require('wpt-fetch').fetchInit;2fetchInit({3 fetch: require('node-fetch'),4 headers: {5 'Accept-Language': 'en-US,en;q=0.9'6 }7}).then((response) => {8 console.log(response);9}).catch((error) => {10 console.log(error);11});12const fetchInit = require('wpt-fetch').fetchInit;13fetchInit({14 fetch: require('node-fetch'),15 headers: {16 'Accept-Language': 'en-US,en;q=0.9'17 }18}).then((response) => {19 console.log(response);20}).catch((error) => {21 console.log(error);22});23const fetchInit = require('wpt-fetch').fetchInit;24fetchInit({25 fetch: require('node-fetch'),26 headers: {27 'Accept-Language': 'en-US,en;q=0.9'28 }29}).then((response) => {30 console.log(response);31}).catch((error) => {32 console.log(error);33});34const fetchInit = require('wpt-fetch').fetchInit;35fetchInit({36 fetch: require('node-fetch'),37 headers: {38 'Accept-Language': 'en-US,en;q=0.9'39 }40}).then((response) => {41 console.log(response);42}).catch((error) => {43 console.log(error);44});45const fetchInit = require('wpt-fetch').fetchInit;46fetchInit({47 fetch: require('node-fetch'),
Using AI Code Generation
1let wpt = require("./wpt.js");2wpt.fetchInit();3exports.fetchInit = async () => {4 let response = await fetch(url);5 let html = await response.text();6 console.log(html);7};8let wpt = require("./wpt.js");9wpt.fetchInit();10exports.fetchInit = async () => {11 let response = await fetch(url);
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.3a3af1f2d8b6a9a9f5e0e7d5e1b1d0b5');3var location = 'Dulles:Chrome';4var runs = 1;5var mobile = false;6var firstViewOnly = false;7var pollResults = 5;8var video = true;9var private = false;10var connectivity = 'Cable';11var bandwidthDown = 1000;12var bandwidthUp = 1000;13var latency = 28;14var packetLoss = 0;15var login = '';16var password = '';17var basicAuthUser = '';18var basicAuthPassword = '';19var label = '';20var notifyEmail = '';21var notifyCompare = false;22var block = '';23var standard = 'W3C';24var timeline = false;25var trace = false;26var script = '';27var scriptWait = 0;28wpt.fetchInit(testURL, {29}, function(err, data) {30 if (err) {31 console.log('Error: ' + err);32 } else {33 console.log(data);34 }35});
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!!