Best JavaScript code snippet using wpt
apifiClientJS.js
Source:apifiClientJS.js
1let apiUrl = location.origin + '/graphql';2let apiWsUrl = apiUrl.replace('http', 'ws');3let apiSseUrl = apiUrl + '/sse';4let includeCredentials = false;5let bearerToken;6// project specific client side API calls7export default{8 setBearerToken(token){9 bearerToken = token;10 },11 setApiUrl(url){12 apiUrl = url;13 },14 setApiWsUrl(url){15 apiWsUrl = url;16 },17 setApiSseUrl(url){18 apiSseUrl = url;19 },20 setIncludeCredentials(value){21 includeCredentials = value;22 },23 async addReactionsToPost(owner, input, selectionGraph, customHeaders){24 let requestHeaders = { "Content-Type": "application/json" }25 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);26 if(bearerToken) requestHeaders["Authorization"] = bearerToken;27 const requestInit = {28 method: "POST",29 credentials: !!includeCredentials ? 'include' : 'omit',30 headers: requestHeaders,31 body: JSON.stringify({32 query: `mutation addReactionsToPost($owner: PostInput, $input: [Reaction]) { addReactionsToPost(owner: $owner, input: $input)${selectionGraph} }`, 33 variables: {34 "owner": owner, 35 "input": input36 }37 })38 };39 return await (await fetch(apiUrl, requestInit)).json();40 },41 async removeReactionsFromPost(owner, input, selectionGraph, customHeaders){42 let requestHeaders = { "Content-Type": "application/json" }43 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);44 if(bearerToken) requestHeaders["Authorization"] = bearerToken;45 const requestInit = {46 method: "POST",47 credentials: !!includeCredentials ? 'include' : 'omit',48 headers: requestHeaders,49 body: JSON.stringify({50 query: `mutation removeReactionsFromPost($owner: PostInput, $input: [Reaction]) { removeReactionsFromPost(owner: $owner, input: $input)${selectionGraph} }`, 51 variables: {52 "owner": owner, 53 "input": input54 }55 })56 };57 return await (await fetch(apiUrl, requestInit)).json();58 },59 async reactionsOfPost(owner, input, selectionGraph, customHeaders){60 let requestHeaders = { "Content-Type": "application/json" }61 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);62 if(bearerToken) requestHeaders["Authorization"] = bearerToken;63 const requestInit = {64 method: "POST",65 credentials: !!includeCredentials ? 'include' : 'omit',66 headers: requestHeaders,67 body: JSON.stringify({68 query: `query reactionsOfPost($owner: PostInput, $input: PageRequestInput) { reactionsOfPost(owner: $owner, input: $input)${selectionGraph} }`, 69 variables: {70 "owner": owner, 71 "input": input72 }73 })74 };75 return await (await fetch(apiUrl, requestInit)).json();76 },77 async freeTextSearchReactionsOfPost(owner, input, selectionGraph, customHeaders){78 let requestHeaders = { "Content-Type": "application/json" }79 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);80 if(bearerToken) requestHeaders["Authorization"] = bearerToken;81 const requestInit = {82 method: "POST",83 credentials: !!includeCredentials ? 'include' : 'omit',84 headers: requestHeaders,85 body: JSON.stringify({86 query: `query freeTextSearchReactionsOfPost($owner: PostInput, $input: FreeTextSearchPageRequestInput) { freeTextSearchReactionsOfPost(owner: $owner, input: $input)${selectionGraph} }`, 87 variables: {88 "owner": owner, 89 "input": input90 }91 })92 };93 return await (await fetch(apiUrl, requestInit)).json();94 },95 async addTagCountToPost(owner, input, selectionGraph, customHeaders){96 let requestHeaders = { "Content-Type": "application/json" }97 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);98 if(bearerToken) requestHeaders["Authorization"] = bearerToken;99 const requestInit = {100 method: "POST",101 credentials: !!includeCredentials ? 'include' : 'omit',102 headers: requestHeaders,103 body: JSON.stringify({104 query: `mutation addTagCountToPost($owner: PostInput, $input: [Integer]) { addTagCountToPost(owner: $owner, input: $input)${selectionGraph} }`, 105 variables: {106 "owner": owner, 107 "input": input108 }109 })110 };111 return await (await fetch(apiUrl, requestInit)).json();112 },113 async removeTagCountFromPost(owner, input, selectionGraph, customHeaders){114 let requestHeaders = { "Content-Type": "application/json" }115 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);116 if(bearerToken) requestHeaders["Authorization"] = bearerToken;117 const requestInit = {118 method: "POST",119 credentials: !!includeCredentials ? 'include' : 'omit',120 headers: requestHeaders,121 body: JSON.stringify({122 query: `mutation removeTagCountFromPost($owner: PostInput, $input: [Integer>]) { removeTagCountFromPost(owner: $owner, input: $input)${selectionGraph} }`, 123 variables: {124 "owner": owner, 125 "input": input126 }127 })128 };129 return await (await fetch(apiUrl, requestInit)).json();130 },131 async tagCountOfPost(owner, input, selectionGraph, customHeaders){132 let requestHeaders = { "Content-Type": "application/json" }133 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);134 if(bearerToken) requestHeaders["Authorization"] = bearerToken;135 const requestInit = {136 method: "POST",137 credentials: !!includeCredentials ? 'include' : 'omit',138 headers: requestHeaders,139 body: JSON.stringify({140 query: `query tagCountOfPost($owner: PostInput, $input: PageRequestInput) { tagCountOfPost(owner: $owner, input: $input)${selectionGraph} }`, 141 variables: {142 "owner": owner, 143 "input": input144 }145 })146 };147 return await (await fetch(apiUrl, requestInit)).json();148 },149 async freeTextSearchTagCountOfPost(owner, input, selectionGraph, customHeaders){150 let requestHeaders = { "Content-Type": "application/json" }151 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);152 if(bearerToken) requestHeaders["Authorization"] = bearerToken;153 const requestInit = {154 method: "POST",155 credentials: !!includeCredentials ? 'include' : 'omit',156 headers: requestHeaders,157 body: JSON.stringify({158 query: `query freeTextSearchTagCountOfPost($owner: PostInput, $input: FreeTextSearchPageRequestInput) { freeTextSearchTagCountOfPost(owner: $owner, input: $input)${selectionGraph} }`, 159 variables: {160 "owner": owner, 161 "input": input162 }163 })164 };165 return await (await fetch(apiUrl, requestInit)).json();166 },167 async users(input, selectionGraph, customHeaders){168 let requestHeaders = { "Content-Type": "application/json" }169 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);170 if(bearerToken) requestHeaders["Authorization"] = bearerToken;171 const requestInit = {172 method: "POST",173 credentials: !!includeCredentials ? 'include' : 'omit',174 headers: requestHeaders,175 body: JSON.stringify({176 query: `query users($input: PageRequestInput) { users(input: $input)${selectionGraph} }`, 177 variables: {178 "input": input179 }180 })181 };182 return await (await fetch(apiUrl, requestInit)).json();183 },184 async countTotalUsers(customHeaders){185 let requestHeaders = { "Content-Type": "application/json" }186 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);187 if(bearerToken) requestHeaders["Authorization"] = bearerToken;188 const requestInit = {189 method: "POST",190 credentials: !!includeCredentials ? 'include' : 'omit',191 headers: requestHeaders,192 body: JSON.stringify({193 query: `query countTotalUsers { countTotalUsers }`, 194 })195 };196 return await (await fetch(apiUrl, requestInit)).json();197 },198 async countTotalArchivedUsers(customHeaders){199 let requestHeaders = { "Content-Type": "application/json" }200 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);201 if(bearerToken) requestHeaders["Authorization"] = bearerToken;202 const requestInit = {203 method: "POST",204 credentials: !!includeCredentials ? 'include' : 'omit',205 headers: requestHeaders,206 body: JSON.stringify({207 query: `query countTotalArchivedUsers { countTotalArchivedUsers }`, 208 })209 };210 return await (await fetch(apiUrl, requestInit)).json();211 },212 async getUserById(input, selectionGraph, customHeaders){213 let requestHeaders = { "Content-Type": "application/json" }214 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);215 if(bearerToken) requestHeaders["Authorization"] = bearerToken;216 const requestInit = {217 method: "POST",218 credentials: !!includeCredentials ? 'include' : 'omit',219 headers: requestHeaders,220 body: JSON.stringify({221 query: `query getUserById($input: Long) { getUserById(input: $input)${selectionGraph} }`, 222 variables: {223 "input": input224 }225 })226 };227 return await (await fetch(apiUrl, requestInit)).json();228 },229 async getUsersByIds(input, selectionGraph, customHeaders){230 let requestHeaders = { "Content-Type": "application/json" }231 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);232 if(bearerToken) requestHeaders["Authorization"] = bearerToken;233 const requestInit = {234 method: "POST",235 credentials: !!includeCredentials ? 'include' : 'omit',236 headers: requestHeaders,237 body: JSON.stringify({238 query: `query getUsersByIds($input: [Long]) { getUsersByIds(input: $input)${selectionGraph} }`, 239 variables: {240 "input": input241 }242 })243 };244 return await (await fetch(apiUrl, requestInit)).json();245 },246 async createUser(input, selectionGraph, customHeaders){247 let requestHeaders = { "Content-Type": "application/json" }248 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);249 if(bearerToken) requestHeaders["Authorization"] = bearerToken;250 const requestInit = {251 method: "POST",252 credentials: !!includeCredentials ? 'include' : 'omit',253 headers: requestHeaders,254 body: JSON.stringify({255 query: `mutation createUser($input: UserInput) { createUser(input: $input)${selectionGraph} }`, 256 variables: {257 "input": input258 }259 })260 };261 return await (await fetch(apiUrl, requestInit)).json();262 },263 async createUsers(input, selectionGraph, customHeaders){264 let requestHeaders = { "Content-Type": "application/json" }265 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);266 if(bearerToken) requestHeaders["Authorization"] = bearerToken;267 const requestInit = {268 method: "POST",269 credentials: !!includeCredentials ? 'include' : 'omit',270 headers: requestHeaders,271 body: JSON.stringify({272 query: `mutation createUsers($input: [UserInput]) { createUsers(input: $input)${selectionGraph} }`, 273 variables: {274 "input": input275 }276 })277 };278 return await (await fetch(apiUrl, requestInit)).json();279 },280 async updateUser(input, selectionGraph, customHeaders){281 let requestHeaders = { "Content-Type": "application/json" }282 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);283 if(bearerToken) requestHeaders["Authorization"] = bearerToken;284 const requestInit = {285 method: "POST",286 credentials: !!includeCredentials ? 'include' : 'omit',287 headers: requestHeaders,288 body: JSON.stringify({289 query: `mutation updateUser($input: UserInput) { updateUser(input: $input)${selectionGraph} }`, 290 variables: {291 "input": input292 }293 })294 };295 return await (await fetch(apiUrl, requestInit)).json();296 },297 async updateUsers(input, selectionGraph, customHeaders){298 let requestHeaders = { "Content-Type": "application/json" }299 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);300 if(bearerToken) requestHeaders["Authorization"] = bearerToken;301 const requestInit = {302 method: "POST",303 credentials: !!includeCredentials ? 'include' : 'omit',304 headers: requestHeaders,305 body: JSON.stringify({306 query: `mutation updateUsers($input: [UserInput]) { updateUsers(input: $input)${selectionGraph} }`, 307 variables: {308 "input": input309 }310 })311 };312 return await (await fetch(apiUrl, requestInit)).json();313 },314 async deleteUser(input, selectionGraph, customHeaders){315 let requestHeaders = { "Content-Type": "application/json" }316 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);317 if(bearerToken) requestHeaders["Authorization"] = bearerToken;318 const requestInit = {319 method: "POST",320 credentials: !!includeCredentials ? 'include' : 'omit',321 headers: requestHeaders,322 body: JSON.stringify({323 query: `mutation deleteUser($input: UserInput) { deleteUser(input: $input)${selectionGraph} }`, 324 variables: {325 "input": input326 }327 })328 };329 return await (await fetch(apiUrl, requestInit)).json();330 },331 async deleteUsers(input, selectionGraph, customHeaders){332 let requestHeaders = { "Content-Type": "application/json" }333 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);334 if(bearerToken) requestHeaders["Authorization"] = bearerToken;335 const requestInit = {336 method: "POST",337 credentials: !!includeCredentials ? 'include' : 'omit',338 headers: requestHeaders,339 body: JSON.stringify({340 query: `mutation deleteUsers($input: [UserInput]) { deleteUsers(input: $input)${selectionGraph} }`, 341 variables: {342 "input": input343 }344 })345 };346 return await (await fetch(apiUrl, requestInit)).json();347 },348 async archiveUser(input, selectionGraph, customHeaders){349 let requestHeaders = { "Content-Type": "application/json" }350 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);351 if(bearerToken) requestHeaders["Authorization"] = bearerToken;352 const requestInit = {353 method: "POST",354 credentials: !!includeCredentials ? 'include' : 'omit',355 headers: requestHeaders,356 body: JSON.stringify({357 query: `mutation archiveUser($input: UserInput) { archiveUser(input: $input)${selectionGraph} }`, 358 variables: {359 "input": input360 }361 })362 };363 return await (await fetch(apiUrl, requestInit)).json();364 },365 async archiveUsers(input, selectionGraph, customHeaders){366 let requestHeaders = { "Content-Type": "application/json" }367 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);368 if(bearerToken) requestHeaders["Authorization"] = bearerToken;369 const requestInit = {370 method: "POST",371 credentials: !!includeCredentials ? 'include' : 'omit',372 headers: requestHeaders,373 body: JSON.stringify({374 query: `mutation archiveUsers($input: [UserInput]) { archiveUsers(input: $input)${selectionGraph} }`, 375 variables: {376 "input": input377 }378 })379 };380 return await (await fetch(apiUrl, requestInit)).json();381 },382 async deArchiveUser(input, selectionGraph, customHeaders){383 let requestHeaders = { "Content-Type": "application/json" }384 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);385 if(bearerToken) requestHeaders["Authorization"] = bearerToken;386 const requestInit = {387 method: "POST",388 credentials: !!includeCredentials ? 'include' : 'omit',389 headers: requestHeaders,390 body: JSON.stringify({391 query: `mutation deArchiveUser($input: UserInput) { deArchiveUser(input: $input)${selectionGraph} }`, 392 variables: {393 "input": input394 }395 })396 };397 return await (await fetch(apiUrl, requestInit)).json();398 },399 async deArchiveUsers(input, selectionGraph, customHeaders){400 let requestHeaders = { "Content-Type": "application/json" }401 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);402 if(bearerToken) requestHeaders["Authorization"] = bearerToken;403 const requestInit = {404 method: "POST",405 credentials: !!includeCredentials ? 'include' : 'omit',406 headers: requestHeaders,407 body: JSON.stringify({408 query: `mutation deArchiveUsers($input: [UserInput]) { deArchiveUsers(input: $input)${selectionGraph} }`, 409 variables: {410 "input": input411 }412 })413 };414 return await (await fetch(apiUrl, requestInit)).json();415 },416 async archivedUsers(input, selectionGraph, customHeaders){417 let requestHeaders = { "Content-Type": "application/json" }418 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);419 if(bearerToken) requestHeaders["Authorization"] = bearerToken;420 const requestInit = {421 method: "POST",422 credentials: !!includeCredentials ? 'include' : 'omit',423 headers: requestHeaders,424 body: JSON.stringify({425 query: `query archivedUsers($input: PageRequestInput) { archivedUsers(input: $input)${selectionGraph} }`, 426 variables: {427 "input": input428 }429 })430 };431 return await (await fetch(apiUrl, requestInit)).json();432 },433 onUsersCreated(input){434 const queryParam = encodeURIComponent(435 JSON.stringify({436 query: `subscription onUsersCreated($backPressureStrategy: OverflowStrategy) { onUsersCreated(backPressureStrategy: $backPressureStrategy)${input.selectionGraph} }`, 437 variables: {438 "backPressureStrategy": input.backPressureStrategy || 'BUFFER'439 }440 }));441 const timeoutParam = input.timeout ? `&timeout=${input.timeout}` : '';442 const eventSourceUrl = `${apiSseUrl}?queryString=${queryParam}${timeoutParam}`;443 return new SubscriptionEventsEmitter(eventSourceUrl);444 },445 onUserUpdated(input){446 const queryParam = encodeURIComponent(447 JSON.stringify({448 query: `subscription onUserUpdated($toObserve: [User], $backPressureStrategy: OverflowStrategy) { onUserUpdated(toObserve: $toObserve, backPressureStrategy: $backPressureStrategy)${input.selectionGraph} }`, 449 variables: {450 "toObserve": input.toObserve, 451 "backPressureStrategy": input.backPressureStrategy || 'BUFFER'452 }453 }));454 const timeoutParam = input.timeout ? `&timeout=${input.timeout}` : '';455 const eventSourceUrl = `${apiSseUrl}?queryString=${queryParam}${timeoutParam}`;456 return new SubscriptionEventsEmitter(eventSourceUrl);457 },458 onUserDeleted(input){459 const queryParam = encodeURIComponent(460 JSON.stringify({461 query: `subscription onUserDeleted($toObserve: [User], $backPressureStrategy: OverflowStrategy) { onUserDeleted(toObserve: $toObserve, backPressureStrategy: $backPressureStrategy)${input.selectionGraph} }`, 462 variables: {463 "toObserve": input.toObserve, 464 "backPressureStrategy": input.backPressureStrategy || 'BUFFER'465 }466 }));467 const timeoutParam = input.timeout ? `&timeout=${input.timeout}` : '';468 const eventSourceUrl = `${apiSseUrl}?queryString=${queryParam}${timeoutParam}`;469 return new SubscriptionEventsEmitter(eventSourceUrl);470 },471 onUserArchived(input){472 const queryParam = encodeURIComponent(473 JSON.stringify({474 query: `subscription onUserArchived($toObserve: [User], $backPressureStrategy: OverflowStrategy) { onUserArchived(toObserve: $toObserve, backPressureStrategy: $backPressureStrategy)${input.selectionGraph} }`, 475 variables: {476 "toObserve": input.toObserve, 477 "backPressureStrategy": input.backPressureStrategy || 'BUFFER'478 }479 }));480 const timeoutParam = input.timeout ? `&timeout=${input.timeout}` : '';481 const eventSourceUrl = `${apiSseUrl}?queryString=${queryParam}${timeoutParam}`;482 return new SubscriptionEventsEmitter(eventSourceUrl);483 },484 onUserDeArchived(input){485 const queryParam = encodeURIComponent(486 JSON.stringify({487 query: `subscription onUserDeArchived($toObserve: [User], $backPressureStrategy: OverflowStrategy) { onUserDeArchived(toObserve: $toObserve, backPressureStrategy: $backPressureStrategy)${input.selectionGraph} }`, 488 variables: {489 "toObserve": input.toObserve, 490 "backPressureStrategy": input.backPressureStrategy || 'BUFFER'491 }492 }));493 const timeoutParam = input.timeout ? `&timeout=${input.timeout}` : '';494 const eventSourceUrl = `${apiSseUrl}?queryString=${queryParam}${timeoutParam}`;495 return new SubscriptionEventsEmitter(eventSourceUrl);496 },497 async associatePostsWithUser(owner, input, selectionGraph, customHeaders){498 let requestHeaders = { "Content-Type": "application/json" }499 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);500 if(bearerToken) requestHeaders["Authorization"] = bearerToken;501 const requestInit = {502 method: "POST",503 credentials: !!includeCredentials ? 'include' : 'omit',504 headers: requestHeaders,505 body: JSON.stringify({506 query: `mutation associatePostsWithUser($owner: UserInput, $input: [PostInput]) { associatePostsWithUser(owner: $owner, input: $input)${selectionGraph} }`, 507 variables: {508 "owner": owner, 509 "input": input510 }511 })512 };513 return await (await fetch(apiUrl, requestInit)).json();514 },515 async removePostsFromUser(owner, input, selectionGraph, customHeaders){516 let requestHeaders = { "Content-Type": "application/json" }517 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);518 if(bearerToken) requestHeaders["Authorization"] = bearerToken;519 const requestInit = {520 method: "POST",521 credentials: !!includeCredentials ? 'include' : 'omit',522 headers: requestHeaders,523 body: JSON.stringify({524 query: `mutation removePostsFromUser($owner: UserInput, $input: [PostInput]) { removePostsFromUser(owner: $owner, input: $input)${selectionGraph} }`, 525 variables: {526 "owner": owner, 527 "input": input528 }529 })530 };531 return await (await fetch(apiUrl, requestInit)).json();532 },533 async postsOfUser(owner, input, selectionGraph, customHeaders){534 let requestHeaders = { "Content-Type": "application/json" }535 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);536 if(bearerToken) requestHeaders["Authorization"] = bearerToken;537 const requestInit = {538 method: "POST",539 credentials: !!includeCredentials ? 'include' : 'omit',540 headers: requestHeaders,541 body: JSON.stringify({542 query: `query postsOfUser($owner: UserInput, $input: PageRequestInput) { postsOfUser(owner: $owner, input: $input)${selectionGraph} }`, 543 variables: {544 "owner": owner, 545 "input": input546 }547 })548 };549 return await (await fetch(apiUrl, requestInit)).json();550 },551 async postsOfUserFreeTextSearch(owner, input, selectionGraph, customHeaders){552 let requestHeaders = { "Content-Type": "application/json" }553 if(customHeaders) requestHeaders = Object.assign({}, requestHeaders, customHeaders);554 if(bearerToken) requestHeaders["Authorization"] = bearerToken;555 const requestInit = {556 method: "POST",557 credentials: !!includeCredentials ? 'include' : 'omit',558 headers: requestHeaders,559 body: JSON.stringify({560 query: `query postsOfUserFreeTextSearch($owner: UserInput, $input: FreeTextSearchPageRequestInput) { postsOfUserFreeTextSearch(owner: $owner, input: $input)${selectionGraph} }`, 561 variables: {562 "owner": owner, 563 "input": input564 }565 })566 };567 return await (await fetch(apiUrl, requestInit)).json();568 },569 onAssociatePostsWithUser(input){570 const queryParam = encodeURIComponent(571 JSON.stringify({572 query: `subscription onAssociatePostsWithUser($owner: User, $backPressureStrategy: OverflowStrategy) { onAssociatePostsWithUser(owner: $owner, backPressureStrategy: $backPressureStrategy)${input.selectionGraph} }`, 573 variables: {574 "owner": input.owner, 575 "backPressureStrategy": input.backPressureStrategy || 'BUFFER'576 }577 }));578 const timeoutParam = input.timeout ? `&timeout=${input.timeout}` : '';579 const eventSourceUrl = `${apiSseUrl}?queryString=${queryParam}${timeoutParam}`;580 return new SubscriptionEventsEmitter(eventSourceUrl);581 },582 onRemovePostsFromUser(input){583 const queryParam = encodeURIComponent(584 JSON.stringify({585 query: `subscription onRemovePostsFromUser($owner: User, $backPressureStrategy: OverflowStrategy) { onRemovePostsFromUser(owner: $owner, backPressureStrategy: $backPressureStrategy)${input.selectionGraph} }`, 586 variables: {587 "owner": input.owner, 588 "backPressureStrategy": input.backPressureStrategy || 'BUFFER'589 }590 }));591 const timeoutParam = input.timeout ? `&timeout=${input.timeout}` : '';592 const eventSourceUrl = `${apiSseUrl}?queryString=${queryParam}${timeoutParam}`;593 return new SubscriptionEventsEmitter(eventSourceUrl);594 },595}596export class SubscriptionEventsEmitter{597 constructor(eventSourceUrl) {598 this.eventSource = new EventSource(eventSourceUrl, { withCredentials: includeCredentials } );599 this.eventSource.addEventListener('EXECUTION_RESULT', (event) => {600 this.onExecutionResultConsumer && this.onExecutionResultConsumer(JSON.parse(event.data));601 }, false); 602 this.eventSource.addEventListener('COMPLETE', (event) => {603 this.onCompleteConsumer && this.onCompleteConsumer();604 console.log('completed event stream - terminating connection');605 this.eventSource.close();606 }, false); 607 this.eventSource.addEventListener('FATAL_ERROR', (event) => {608 this.onFatalErrorConsumer && this.onFatalErrorConsumer(event.data['MESSAGE']);609 console.log(`encountered fatal error: ${event.data['MESSAGE']} - terminating connection`);610 this.eventSource.close();611 }, false);612 }613 eventSource;614 onExecutionResultConsumer;615 onCompleteConsumer;616 onFatalErrorConsumer;617 onExecutionResult(onExecutionResultConsumer){618 this.onExecutionResultConsumer = onExecutionResultConsumer;619 return this;620 }621 onComplete(onCompleteConsumer){622 this.onCompleteConsumer = onCompleteConsumer;623 return this;624 }625 onFatalError(onFatalErrorConsumer){626 this.onFatalErrorConsumer = onFatalErrorConsumer;627 return this;628 }629 terminate(){630 this.eventSource.close();631 }...
apifiClient.js
Source:apifiClient.js
1let apiUrl = 'http://localhost:5000/api';2let bearerToken = undefined;34export default{56 setBearerToken(token){7 bearerToken = token;8 },910 setApiUrl(url){11 apiUrl = url;12 },13 async getMediaTagsByIds(input, expectedReturn, customHeaders){14 let requestHeaders = { "Content-Type": "application/json" }15 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);16 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;17 const opts = {18 method: "POST",19 credentials: "include",20 headers: requestHeaders,21 body: JSON.stringify({22 query: `query getMediaTagsByIds($input: [Long]) { getMediaTagsByIds(input: $input)${expectedReturn} }`,23 variables: {24 "input": input25 },26 operationName: "getMediaTagsByIds"27 })28 };29 return await (await fetch(apiUrl, opts)).json();30 },31 async associateLinkedContentWithMediaTag(owner, input, expectedReturn, customHeaders){32 let requestHeaders = { "Content-Type": "application/json" }33 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);34 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;35 const opts = {36 method: "POST",37 credentials: "include",38 headers: requestHeaders,39 body: JSON.stringify({40 query: `mutation associateLinkedContentWithMediaTag($owner: MediaTagInput, $input: [MediaContentInput]) { associateLinkedContentWithMediaTag(owner: $owner, input: $input)${expectedReturn} }`,41 variables: {42 "owner": owner,43 "input": input44 },45 operationName: "associateLinkedContentWithMediaTag"46 })47 };48 return await (await fetch(apiUrl, opts)).json();49 },5051 async getZipFileWithMediaKeys(input,customHeaders){52 let requestHeaders = { "Content-Type": "application/json" }53 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);54 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;55 const opts = {56 method: "POST",57 credentials: "include",58 headers: { "Content-Type": "application/json" },59 body:input60 };61 return await (await fetch(apiUrl, opts)).json();62 },6364 async updateLinkedContentOfMediaTag(owner, input, expectedReturn, customHeaders){65 let requestHeaders = { "Content-Type": "application/json" }66 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);67 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;68 const opts = {69 method: "POST",70 credentials: "include",71 headers: requestHeaders,72 body: JSON.stringify({73 query: `mutation updateLinkedContentOfMediaTag($owner: MediaTagInput, $input: [MediaContentInput]) { updateLinkedContentOfMediaTag(owner: $owner, input: $input)${expectedReturn} }`,74 variables: {75 "owner": owner,76 "input": input77 },78 operationName: "updateLinkedContentOfMediaTag"79 })80 };81 return await (await fetch(apiUrl, opts)).json();82 },8384 async removeLinkedContentFromMediaTag(owner, input, expectedReturn, customHeaders){85 let requestHeaders = { "Content-Type": "application/json" }86 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);87 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;88 const opts = {89 method: "POST",90 credentials: "include",91 headers: requestHeaders,92 body: JSON.stringify({93 query: `mutation removeLinkedContentFromMediaTag($owner: MediaTagInput, $input: [MediaContentInput]) { removeLinkedContentFromMediaTag(owner: $owner, input: $input)${expectedReturn} }`,94 variables: {95 "owner": owner,96 "input": input97 },98 operationName: "removeLinkedContentFromMediaTag"99 })100 };101 return await (await fetch(apiUrl, opts)).json();102 },103104 async findChapterByUniquePath(path, expectedReturn, customHeaders){105 let requestHeaders = { "Content-Type": "application/json" }106 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);107 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;108 const opts = {109 method: "POST",110 credentials: "include",111 headers: requestHeaders,112 body: JSON.stringify({113 query: `query findChapterByUniquePath($path: String!) { findChapterByUniquePath(path: $path)${expectedReturn} }`,114 variables: {115 "path": path116 },117 operationName: "findChapterByUniquePath"118 })119 };120 return await (await fetch(apiUrl, opts)).json();121 },122123 async associateMediaTagsWithVerse(owner, input, expectedReturn, customHeaders){124 let requestHeaders = { "Content-Type": "application/json" }125 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);126 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;127 const opts = {128 method: "POST",129 credentials: "include",130 headers: requestHeaders,131 body: JSON.stringify({132 query: `mutation associateMediaTagsWithVerse($owner: VerseInput, $input: [MediaTagInput]) { associateMediaTagsWithVerse(owner: $owner, input: $input)${expectedReturn} }`,133 variables: {134 "owner": owner,135 "input": input136 },137 operationName: "associateMediaTagsWithVerse"138 })139 };140 return await (await fetch(apiUrl, opts)).json();141 },142143 async updateMediaTagsOfVerse(owner, input, expectedReturn, customHeaders){144 let requestHeaders = { "Content-Type": "application/json" }145 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);146 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;147 const opts = {148 method: "POST",149 credentials: "include",150 headers: requestHeaders,151 body: JSON.stringify({152 query: `mutation updateMediaTagsOfVerse($owner: VerseInput, $input: [MediaTagInput]) { updateMediaTagsOfVerse(owner: $owner, input: $input)${expectedReturn} }`,153 variables: {154 "owner": owner,155 "input": input156 },157 operationName: "updateMediaTagsOfVerse"158 })159 };160 return await (await fetch(apiUrl, opts)).json();161 },162163 async removeMediaTagsFromVerse(owner, input, expectedReturn, customHeaders){164 let requestHeaders = { "Content-Type": "application/json" }165 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);166 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;167 const opts = {168 method: "POST",169 credentials: "include",170 headers: requestHeaders,171 body: JSON.stringify({172 query: `mutation removeMediaTagsFromVerse($owner: VerseInput, $input: [MediaTagInput]) { removeMediaTagsFromVerse(owner: $owner, input: $input)${expectedReturn} }`,173 variables: {174 "owner": owner,175 "input": input176 },177 operationName: "removeMediaTagsFromVerse"178 })179 };180 return await (await fetch(apiUrl, opts)).json();181 },182183 async verseFreeTextSearch(input, expectedReturn, customHeaders){184 let requestHeaders = { "Content-Type": "application/json" }185 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);186 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;187 const opts = {188 method: "POST",189 credentials: "include",190 headers: requestHeaders,191 body: JSON.stringify({192 query: `query verseFreeTextSearch($input: FreeTextSearchPageRequestInput) { verseFreeTextSearch(input: $input)${expectedReturn} }`,193 variables: {194 "input": input195 },196 operationName: "verseFreeTextSearch"197 })198 };199 return await (await fetch(apiUrl, opts)).json();200 },201202 async findVerseByUniquePath(path, expectedReturn, customHeaders){203 let requestHeaders = { "Content-Type": "application/json" }204 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);205 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;206 const opts = {207 method: "POST",208 credentials: "include",209 headers: requestHeaders,210 body: JSON.stringify({211 query: `query findVerseByUniquePath($path: String!) { findVerseByUniquePath(path: $path)${expectedReturn} }`,212 variables: {213 "path": path214 },215 operationName: "findVerseByUniquePath"216 })217 };218 return await (await fetch(apiUrl, opts)).json();219 },220221 async errorReports(input, expectedReturn, customHeaders){222 let requestHeaders = { "Content-Type": "application/json" }223 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);224 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;225 const opts = {226 method: "POST",227 credentials: "include",228 headers: requestHeaders,229 body: JSON.stringify({230 query: `query errorReports($input: PageRequestInput) { errorReports(input: $input)${expectedReturn} }`,231 variables: {232 "input": input233 },234 operationName: "errorReports"235 })236 };237 return await (await fetch(apiUrl, opts)).json();238 },239240 async createErrorReport(input, expectedReturn, customHeaders){241 let requestHeaders = { "Content-Type": "application/json" }242 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);243 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;244 const opts = {245 method: "POST",246 credentials: "include",247 headers: requestHeaders,248 body: JSON.stringify({249 query: `mutation createErrorReport($input: ErrorReportInput) { createErrorReport(input: $input)${expectedReturn} }`,250 variables: {251 "input": input252 },253 operationName: "createErrorReport"254 })255 };256 return await (await fetch(apiUrl, opts)).json();257 },258259 async findBookByUniquePath(path, expectedReturn, customHeaders){260 let requestHeaders = { "Content-Type": "application/json" }261 if(customHeaders !== undefined) requestHeaders = Object.assign({}, requestHeaders, customHeaders);262 if(bearerToken !== undefined) requestHeaders["Authorization"] = bearerToken;263 const opts = {264 method: "POST",265 credentials: "include",266 headers: requestHeaders,267 body: JSON.stringify({268 query: `query findBookByUniquePath($path: String!) { findBookByUniquePath(path: $path)${expectedReturn} }`,269 variables: {270 "path": path271 },272 operationName: "findBookByUniquePath"273 })274 };275 return await (await fetch(apiUrl, opts)).json();276 },277
...
admin.js
Source:admin.js
1import fetcher from "./fetchJson";2import { Cookies } from 'react-cookie';3const cookies = new Cookies();4export async function partnerList(){5 var requestHeaders = new Headers();6 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);7 var requestOptions = {8 method: 'GET',9 headers: requestHeaders,10 redirect: 'follow'11 };12 const resp = await fetcher('/admin/partner/list', requestOptions)13 return resp14}15export async function partnerInfo(id){16 var requestHeaders = new Headers();17 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);18 var requestOptions = {19 method: 'GET',20 headers: requestHeaders,21 redirect: 'follow'22 };23 const resp = await fetcher('/admin/partner/info?id='+id, requestOptions)24 return resp25}26export async function leadsList(){27 var requestHeaders = new Headers();28 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);29 var requestOptions = {30 method: 'GET',31 headers: requestHeaders,32 redirect: 'follow'33 };34 const resp = await fetcher('/admin/partner/lead/list/all', requestOptions)35 return resp36}37export async function applyLeadToPartner(id){38 var requestHeaders = new Headers();39 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);40 var requestOptions = {41 method: 'GET',42 headers: requestHeaders,43 redirect: 'follow'44 };45 const resp = await fetcher('/admin/partner/lead/apply?id='+id, requestOptions)46 return resp47}48export async function partnerFunnelList(){49 var requestHeaders = new Headers();50 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);51 var requestOptions = {52 method: 'GET',53 headers: requestHeaders,54 redirect: 'follow'55 };56 const resp = await fetcher('/admin/partner/partner_funnel/list', requestOptions)57 return resp58}59export async function partnerFunnelInfo(id){60 var requestHeaders = new Headers();61 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);62 var requestOptions = {63 method: 'GET',64 headers: requestHeaders,65 redirect: 'follow'66 };67 const resp = await fetcher('/admin/partner/partner_funnel/info?id='+id, requestOptions)68 return resp69}70export async function editPartnerFunnel(id, name, closed){71 var requestHeaders = new Headers();72 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);73 requestHeaders.append("Content-Type", `application/json`);74 var requestOptions = {75 method: 'PUT',76 headers: requestHeaders,77 redirect: 'follow',78 body:JSON.stringify({id, name, closed})79 };80 const resp = await fetcher('/admin/partner/partner_funnel', requestOptions)81 return resp82}83export async function createPartnerFunnel(name, closed){84 var requestHeaders = new Headers();85 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);86 requestHeaders.append("Content-Type", `application/json`);87 var requestOptions = {88 method: 'POST',89 headers: requestHeaders,90 redirect: 'follow',91 body:JSON.stringify({name, closed})92 };93 const resp = await fetcher('/admin/partner/partner_funnel', requestOptions)94 return resp95}96export async function deletePartnerFunnel(id){97 var requestHeaders = new Headers();98 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);99 var requestOptions = {100 method: 'DELETE',101 headers: requestHeaders,102 redirect: 'follow'103 };104 const resp = await fetcher('/admin/partner/partner_funnel?id='+id, requestOptions)105 return resp106}107export async function applyPartnerToNextStage(funnel_id, partner_id){108 var requestHeaders = new Headers();109 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);110 var requestOptions = {111 method: 'GET',112 headers: requestHeaders,113 redirect: 'follow'114 };115 const resp = await fetcher(`/admin/partner/partner_funnel/apply_next_stage?partner_id=${partner_id}&funnel_id=${funnel_id}`, requestOptions)116 return resp117}118export async function landingRefferList(){119 var requestHeaders = new Headers();120 requestHeaders.append("Content-Type", `application/json`);121 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);122 var requestOptions = {123 method: 'GET',124 headers: requestHeaders,125 redirect: 'follow'126 };127 const resp = await fetcher('/admin/landingreffer/list', requestOptions)128 return resp129}130export async function editLandingReffer(id, landing_id, name, price, default_funnel_id){131 var requestHeaders = new Headers();132 requestHeaders.append("Content-Type", `application/json`);133 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);134 var requestOptions = {135 method: 'POST',136 headers: requestHeaders,137 redirect: 'follow',138 body:JSON.stringify({id, landing_id, name, price, default_funnel_id})139 };140 const resp = await fetcher('/admin/landingreffer/edit', requestOptions)141 return resp142}143export async function statistics(period){144 var requestHeaders = new Headers();145 requestHeaders.append("Content-Type", `application/json`);146 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);147 var requestOptions = {148 method: 'GET',149 headers: requestHeaders,150 redirect: 'follow'151 };152 const resp = await fetcher('/admin/statistics?days='+period, requestOptions)153 return resp...
TargetManager.js
Source:TargetManager.js
1const DOI = require('doi-regex')2// PVSCL:IFCOND(ScienceDirect, LINE)3const URLUtils = require('../utils/URLUtils')4// PVSCL:ENDCOND5const Config = require('../Config')6const _ = require('lodash')7class TargetManager {8 constructor () {9 // PVSCL:IFCOND(DOI, LINE)10 this.doiUrlFilterObject = { 'urls': ['*://*.doi.org/*', '*://doi.org/*'] }11 // PVSCL:ENDCOND12 // PVSCL:IFCOND(ScienceDirect, LINE)13 this.scienceDirect = { 'urls': ['*://www.sciencedirect.com/science/article/pii/*'] }14 // PVSCL:ENDCOND15 // PVSCL:IFCOND(Dropbox, LINE)16 this.dropbox = {'urls': ['*://www.dropbox.com/s/*?raw=1*']}17 this.dropboxContent = {'urls': ['*://*.dropboxusercontent.com/*']}18 this.tabs = {}19 // PVSCL:ENDCOND20 }21 init () {22 // PVSCL:IFCOND(DOI, LINE)23 // Requests to doi.org24 chrome.webRequest.onHeadersReceived.addListener((responseDetails) => {25 console.debug(responseDetails)26 let locationIndex = _.findIndex(responseDetails.responseHeaders, (header) => header.name === 'location')27 let locationUrl = responseDetails.responseHeaders[locationIndex].value28 try {29 let redirectUrl = new URL(locationUrl)30 // Retrieve doi from call31 let doi = ''32 if (_.isArray(DOI.groups(responseDetails.url))) {33 doi = DOI.groups(responseDetails.url)[1]34 }35 let annotationId = this.extractAnnotationId(responseDetails.url)36 if (doi) {37 if (_.isEmpty(redirectUrl.hash)) {38 redirectUrl.hash += '#doi:' + doi39 } else {40 redirectUrl.hash += '&doi:' + doi41 }42 }43 if (annotationId) {44 if (_.isEmpty(redirectUrl.hash)) {45 redirectUrl.hash += '#' + Config.urlParamName + ':' + annotationId46 } else {47 redirectUrl.hash += '&' + Config.urlParamName + ':' + annotationId48 }49 }50 responseDetails.responseHeaders[locationIndex].value = redirectUrl.toString()51 this.tabs[responseDetails.tabId] = {doi: doi, annotationId: annotationId}52 return {responseHeaders: responseDetails.responseHeaders}53 } catch (e) {54 return {responseHeaders: responseDetails.responseHeaders}55 }56 }, this.doiUrlFilterObject, ['responseHeaders', 'blocking'])57 // PVSCL:ENDCOND58 // PVSCL:IFCOND(ScienceDirect, LINE)59 // Requests to sciencedirect, redirection from linkinghub.elsevier.com (parse doi and annotation hash param if present)60 chrome.webRequest.onBeforeSendHeaders.addListener((requestHeaders) => {61 let referer = _.find(requestHeaders.requestHeaders, (requestHeader) => { return requestHeader.name === 'Referer' })62 if (referer && referer.value.includes('linkinghub.elsevier.com')) {63 chrome.tabs.get(requestHeaders.tabId, (tab) => {64 let doi = null65 let annotationId = null66 let url = tab.url67 // Retrieve doi68 let doiGroups = DOI.groups(url)69 if (doiGroups && doiGroups[1]) {70 doi = doiGroups[1]71 doi = doi.split('&' + Config.urlParamName)[0] // If doi-regex inserts also the annotation hash parameter, remove it, is not part of the doi72 }73 let params = URLUtils.extractHashParamsFromUrl(url)74 if (params && params[Config.urlParamName]) {75 annotationId = params[Config.urlParamName]76 }77 console.debug(requestHeaders)78 if (doi && annotationId) {79 let redirectUrl = requestHeaders.url + '#doi:' + doi + '&' + Config.urlParamName + ':' + annotationId80 chrome.tabs.update(requestHeaders.tabId, {url: redirectUrl})81 } else if (doi) {82 let redirectUrl = requestHeaders.url + '#doi:' + doi83 chrome.tabs.update(requestHeaders.tabId, {url: redirectUrl})84 } else if (annotationId) {85 let redirectUrl = requestHeaders.url + '#' + Config.urlParamName + ':' + annotationId86 chrome.tabs.update(requestHeaders.tabId, {url: redirectUrl})87 }88 })89 }90 }, this.scienceDirect, ['requestHeaders', 'blocking', 'extraHeaders'])91 // PVSCL:ENDCOND92 // PVSCL:IFCOND(Dropbox, LINE)93 // Request to dropbox94 chrome.webRequest.onHeadersReceived.addListener((responseDetails) => {95 this.tabs[responseDetails.tabId] = {96 url: responseDetails.url.split('#')[0],97 annotationId: this.extractAnnotationId(responseDetails.url)98 }99 }, this.dropbox, ['responseHeaders', 'blocking'])100 // Request dropbox pdf files101 chrome.webRequest.onBeforeSendHeaders.addListener((details) => {102 let index = _.findIndex(details.requestHeaders, (header) => { return header.name.toLowerCase() === 'accept' })103 details.requestHeaders[index].value = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'104 return {requestHeaders: details.requestHeaders}105 }, this.dropboxContent, ['blocking', 'requestHeaders'])106 chrome.webRequest.onCompleted.addListener((details) => {107 if (this.tabs[details.tabId]) {108 chrome.tabs.sendMessage(details.tabId, this.tabs[details.tabId])109 }110 }, this.dropboxContent)111 // PVSCL:ENDCOND112 }113 extractAnnotationId (url) {114 if (url.includes('#')) {115 let parts = url.split('#')[1].split(':')116 if (parts[0] === Config.urlParamName) {117 return parts[1] || null118 }119 } else {120 return null121 }122 }123}...
partner.js
Source:partner.js
1import fetcher from "./fetchJson";2import { Cookies } from 'react-cookie';3const cookies = new Cookies();4export async function leadInfo(id){5 var requestHeaders = new Headers();6 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);7 var requestOptions = {8 method: 'GET',9 headers: requestHeaders,10 redirect: 'follow'11 };12 const resp = await fetcher('/partner/lead/info?id='+id, requestOptions)13 return resp14}15export async function createStudyModule(name, text, pub=0){16 var requestHeaders = new Headers();17 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);18 requestHeaders.append("Content-Type", `application/json`);19 var requestOptions = {20 method: 'POST',21 headers: requestHeaders,22 redirect: 'follow',23 body:JSON.stringify({name, text, public:pub})24 };25 const resp = await fetcher('/partner/study_module', requestOptions)26 return resp27}28export async function setStudyModuleOrder(funnel_id, study_modules){29 var requestHeaders = new Headers();30 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);31 requestHeaders.append("Content-Type", `application/json`);32 var requestOptions = {33 method: 'POST',34 headers: requestHeaders,35 redirect: 'follow',36 body:JSON.stringify({funnel_id, study_modules})37 };38 const resp = await fetcher('/partner/study_module/order', requestOptions)39 return resp40}41export async function leadFunnelInfo(id){42 var requestHeaders = new Headers();43 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);44 requestHeaders.append("Content-Type", `application/json`);45 var requestOptions = {46 method: 'GET',47 headers: requestHeaders,48 redirect: 'follow',49 };50 const resp = await fetcher('/partner/funnel/info?id='+id, requestOptions)51 return resp52}53export async function leadFunnelList(){54 var requestHeaders = new Headers();55 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);56 requestHeaders.append("Content-Type", `application/json`);57 var requestOptions = {58 method: 'GET',59 headers: requestHeaders,60 redirect: 'follow',61 };62 const resp = await fetcher('/partner/funnel/list', requestOptions)63 return resp64}65export async function editLeadFunnel(id, name, study_time, mode, entryVideos, business_offer=0, preset=0){66 console.log(JSON.stringify({id, name, study_time, mode, entryVideos, business_offer, preset}))67 var requestHeaders = new Headers();68 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);69 requestHeaders.append("Content-Type", `application/json`);70 var requestOptions = {71 method: 'PUT',72 headers: requestHeaders,73 redirect: 'follow',74 body:JSON.stringify({id, name, study_time, mode, entryVideos, business_offer, preset})75 };76 const resp = await fetcher('/partner/funnel', requestOptions)77 return resp78}79export async function createLeadFunnel(name, study_time, mode, entryVideos, business_offer=0, preset=0){80 console.log(JSON.stringify({name, study_time, mode, entryVideos, business_offer, preset}))81 var requestHeaders = new Headers();82 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);83 requestHeaders.append("Content-Type", `application/json`);84 var requestOptions = {85 method: 'POST',86 headers: requestHeaders,87 redirect: 'follow',88 body:JSON.stringify({name, study_time, mode, entryVideos, business_offer, preset})89 };90 const resp = await fetcher('/partner/funnel', requestOptions)91 console.l92 return resp93}94export async function deleteLeadFunnel(id){95 var requestHeaders = new Headers();96 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);97 var requestOptions = {98 method: 'DELETE',99 headers: requestHeaders,100 redirect: 'follow',101 };102 const resp = await fetcher('/partner/funnel?id='+id, requestOptions)103 return resp104}105export async function updateStudyModule(id, name, text, pub=0){106 var requestHeaders = new Headers();107 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);108 requestHeaders.append("Content-Type", `application/json`);109 var requestOptions = {110 method: 'PUT',111 headers: requestHeaders,112 redirect: 'follow',113 body:JSON.stringify({id, name, text, public:pub})114 };115 const resp = await fetcher('/partner/study_module', requestOptions)116 return resp117}118export async function deleteStudyModule(id){119 var requestHeaders = new Headers();120 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);121 var requestOptions = {122 method: 'DELETE',123 headers: requestHeaders,124 redirect: 'follow',125 };126 const resp = await fetcher('/partner/study_module?id='+id, requestOptions)127 return resp128}129export async function landingList(){130 var requestHeaders = new Headers();131 requestHeaders.append("Authorization", `Token ${cookies.get('token')}`);132 var requestOptions = {133 method: 'GET',134 headers: requestHeaders,135 redirect: 'follow',136 };137 const resp = await fetcher('/partner/landing/list', requestOptions)138 return resp...
background.js
Source:background.js
1function configAble(urlStr) {2 return urlStr.search("crm_portal_war_exploded") !== -13 || urlStr.search("dev-crm-mng.bilibili.co") !== -1;4}5function extracted(request) {6 if (configAble(request.url)) {7 chrome.cookies.getAll(8 {url: "http://cm-mng.bilibili.co"},9 // {url: request.url},10 (cks) => {11 let cookie = cks.map((item) => {12 setCookies("http://localhost", item.name, item.value, 3600 * 365 * 24);13 return item.name + "=" + item.value14 }).join(";") + ";";15 console.log(cookie);16 });17 }18}19function extractedWithUrl(urlStr) {20 if (configAble(urlStr)) {21 chrome.cookies.getAll(22 {url: "http://cm-mng.bilibili.co"},23 // {url: request.url},24 function (cks) {25 // 注æ var åletçåºå«26 let cookie = cks.map((item) => {27 setCookies("http://localhost", item.name, item.value, 3600 * 365 * 24);28 return item.name + "=" + item.value29 }).join(";") + ";";30 console.log(cookie);31 });32 }33}34chrome.runtime.onMessage.addListener(35 (request, sender, sendResponse) => {36 // console.log(request.url);37 extracted(request);38 sendResponse(request.url + "cookie update are trigger");39 return true;40 });41function setCookies(url, name, value, expireSecond) {42 //var exdate = new Date();43 var param = {44 url: url,45 name: name,46 value: value,47 path: '/'48 };49 console.log("name :" + name + "value :" + value);50 if (!!expireSecond) {51 param.expirationDate = new Date().getTime() / 1000 + expireSecond;52 }53 chrome.cookies.set(param, function (cookie) {54 console.log(cookie);55 });56}57chrome.webRequest.onBeforeSendHeaders.addListener(58 function (details) {59 if (configAble(details.url)) {60 // let cookies = extractedWithUrl(details.url);61 let cookieExist = false;62 for (var i = 0; i < details.requestHeaders.length; ++i) {63 if (details.requestHeaders[i].name === 'User-Agent') {64 details.requestHeaders.splice(i, 1);65 }66 if (details.requestHeaders[i].name === 'Cookie') {67 cookieExist = true;68 chrome.cookies.getAll(69 {url: "http://cm-mng.bilibili.co"},70 // {url: request.url},71 function (cks) {72 // 注æ var åletçåºå«73 let cookie = cks.map((item) => {74 setCookies("http://localhost", item.name, item.value, 3600 * 365 * 24);75 return item.name + "=" + item.value76 }).join(";") + ";";77 details.requestHeaders[i].value = cookie78 console.log(cookie);79 });80 // details.requestHeaders[i].value = cookies81 // console.log("details.requestHeaders[i].value", details.requestHeaders[i].value);82 break;83 }84 }85 if (!cookieExist) {86 chrome.cookies.getAll(87 {url: "http://cm-mng.bilibili.co"},88 // {url: request.url},89 function (cks) {90 // 注æ var åletçåºå«91 let cookie = cks.map((item) => {92 setCookies("http://localhost", item.name, item.value, 3600 * 365 * 24);93 return item.name + "=" + item.value94 }).join(";") + ";";95 //todo error96 // details.requestHeaders[details.requestHeaders.length + 1].name = 'Cookie'97 // details.requestHeaders[details.requestHeaders.length + 1].value = cookie98 console.log(cookie);99 });100 }101 }102 return {requestHeaders: details.requestHeaders};103 },104 {urls: ["<all_urls>"]},105 ["blocking", "requestHeaders", "extraHeaders"]);106// chrome.webRequest.onSendHeaders.addListener(107// function (details) {108//109// if (details.url.search("crm_portal_war_exploded") !== -1) {110// let cookies = extractedWithUrl(details.url);111// for (var i = 0; i < details.requestHeaders.length; ++i) {112// if (details.requestHeaders[i].name === 'User-Agent') {113// details.requestHeaders.splice(i, 1);114// }115// if (details.requestHeaders[i].name === 'Cookie') {116// details.requestHeaders[i].value = cookies117// console.log("details.requestHeaders[i].value", details.requestHeaders[i].value);118// console.log(details.requestHeaders);119// break;120// }121//122// }123// }124// return {requestHeaders: details.requestHeaders};125// },126// {urls: ["<all_urls>"]},...
request-headers.any.js
Source:request-headers.any.js
...13 else if (body instanceof URLSearchParams)14 expectedContentType = "application/x-www-form-urlencoded;charset=UTF-8";15 assert_equals(contentType , expectedContentType, "Request should have header content-type: " + expectedContentType);16}17function requestHeaders(desc, url, method, body, expectedOrigin, expectedContentLength) {18 var urlParameters = "?headers=origin|user-agent|accept-charset|content-length|content-type";19 var requestInit = {"method": method}20 promise_test(function(test){21 if (typeof body === "function")22 body = body();23 if (body)24 requestInit["body"] = body;25 return fetch(url + urlParameters, requestInit).then(function(resp) {26 assert_equals(resp.status, 200, "HTTP status is 200");27 assert_equals(resp.type , "basic", "Response's type is basic");28 assert_true(resp.headers.has("x-request-user-agent"), "Request has header user-agent");29 assert_false(resp.headers.has("accept-charset"), "Request has header accept-charset");30 assert_equals(resp.headers.get("x-request-origin") , expectedOrigin, "Request should have header origin: " + expectedOrigin);31 if (expectedContentLength !== undefined)32 assert_equals(resp.headers.get("x-request-content-length") , expectedContentLength, "Request should have header content-length: " + expectedContentLength);33 checkContentType(resp.headers.get("x-request-content-type"), body);34 });35 }, desc);36}37var url = RESOURCES_DIR + "inspect-headers.py"38requestHeaders("Fetch with GET", url, "GET", null, null, null);39requestHeaders("Fetch with HEAD", url, "HEAD", null, null, null);40requestHeaders("Fetch with PUT without body", url, "POST", null, location.origin, "0");41requestHeaders("Fetch with PUT with body", url, "PUT", "Request's body", location.origin, "14");42requestHeaders("Fetch with POST without body", url, "POST", null, location.origin, "0");43requestHeaders("Fetch with POST with text body", url, "POST", "Request's body", location.origin, "14");44requestHeaders("Fetch with POST with FormData body", url, "POST", function() { return new FormData(); }, location.origin);45requestHeaders("Fetch with POST with URLSearchParams body", url, "POST", function() { return new URLSearchParams("name=value"); }, location.origin, "10");46requestHeaders("Fetch with POST with Blob body", url, "POST", new Blob(["Test"]), location.origin, "4");47requestHeaders("Fetch with POST with ArrayBuffer body", url, "POST", new ArrayBuffer(4), location.origin, "4");48requestHeaders("Fetch with POST with Uint8Array body", url, "POST", new Uint8Array(4), location.origin, "4");49requestHeaders("Fetch with POST with Int8Array body", url, "POST", new Int8Array(4), location.origin, "4");50requestHeaders("Fetch with POST with Float32Array body", url, "POST", new Float32Array(1), location.origin, "4");51requestHeaders("Fetch with POST with Float64Array body", url, "POST", new Float64Array(1), location.origin, "8");52requestHeaders("Fetch with POST with DataView body", url, "POST", new DataView(new ArrayBuffer(8), 0, 4), location.origin, "4");53requestHeaders("Fetch with POST with Blob body with mime type", url, "POST", new Blob(["Test"], { type: "text/maybe" }), location.origin, "4");54requestHeaders("Fetch with Chicken", url, "Chicken", null, location.origin, null);55requestHeaders("Fetch with Chicken with body", url, "Chicken", "Request's body", location.origin, "14");56function requestOriginHeader(method, mode, needsOrigin) {57 promise_test(function(test){58 return fetch(url + "?headers=origin", {method:method, mode:mode}).then(function(resp) {59 assert_equals(resp.status, 200, "HTTP status is 200");60 assert_equals(resp.type , "basic", "Response's type is basic");61 if(needsOrigin)62 assert_equals(resp.headers.get("x-request-origin") , location.origin, "Request should have an Origin header with origin: " + location.origin);63 else64 assert_equals(resp.headers.get("x-request-origin"), null, "Request should not have an Origin header")65 });66 }, "Fetch with " + method + " and mode \"" + mode + "\" " + (needsOrigin ? "needs" : "does not need") + " an Origin header");67}68requestOriginHeader("GET", "cors", false);69requestOriginHeader("POST", "same-origin", true);...
http.js
Source:http.js
1import 'isomorphic-fetch';2const requestHeaders = {3 Accept: 'application/json',4 'Content-Type': 'application/json',5};6export const getAllComments = () => {7 const options = {8 method: 'GET',9 headers: requestHeaders,10 credentials: 'include',11 };12 return fetch(`/api/comments`, options);13};14export const saveComment = ({ postId, content }) => {15 const options = {16 method: 'POST',17 headers: requestHeaders,18 credentials: 'include',19 body: JSON.stringify({ postId, content }),20 };21 return fetch(`/api/comments`, options);22};23export const saveReply = ({ postId, commentId, content }) => {24 const options = {25 method: 'POST',26 headers: requestHeaders,27 credentials: 'include',28 body: JSON.stringify({ postId, commentId, content }),29 };30 return fetch(`/api/comments`, options);31};32export const updateComment = ({ postId, commentId, content }) => {33 const options = {34 method: 'PUT',35 headers: requestHeaders,36 credentials: 'include',37 body: JSON.stringify({ commentId, content }),38 };39 return fetch(`/api/posts/${postId}/comments/${commentId}`, options);40};41export const deleteComment = ({ postId, commentId }) => {42 const options = {43 method: 'DELETE',44 headers: requestHeaders,45 credentials: 'include',46 };47 return fetch(`/api/posts/${postId}/comments/${commentId}`, options);48};49export const getAllPosts = () => {50 const options = {51 method: 'GET',52 headers: requestHeaders,53 credentials: 'include',54 };55 return fetch(`/api/posts`, options);56};57export const getPostById = id => {58 const options = {59 method: 'GET',60 headers: requestHeaders,61 credentials: 'include',62 };63 return fetch(`/api/posts/${id}`, options);64};65export const deleteViewer = () => {66 const options = {67 method: 'DELETE',68 headers: requestHeaders,69 credentials: 'include',70 };71 return fetch(`/api/viewer/delete`, options);72};73export const deletePost = id => {74 const options = {75 method: 'DELETE',76 headers: requestHeaders,77 credentials: 'include',78 };79 return fetch(`/api/posts/${id}`, options);80};81export const updatePost = ({ content, title, postId }) => {82 const options = {83 method: 'PUT',84 credentials: 'include',85 headers: requestHeaders,86 body: JSON.stringify({ content, title }),87 };88 return fetch(`/api/posts/${postId}`, options);89};90export const savePost = ({ content, title }) => {91 const options = {92 method: 'POST',93 credentials: 'include',94 headers: requestHeaders,95 body: JSON.stringify({ content, title }),96 };97 return fetch(`/api/posts`, options);98};99export const getAllUsers = () => {100 const options = {101 method: 'GET',102 headers: requestHeaders,103 credentials: 'include',104 };105 return fetch(`/api/users`, options);106};107export const login = ({ username, password }) => {108 const options = {109 method: 'POST',110 headers: requestHeaders,111 credentials: 'include',112 body: JSON.stringify({ username: username.toLowerCase(), password }),113 };114 return fetch(`/api/login`, options);115};116export const logout = () => {117 const options = {118 method: 'POST',119 credentials: 'include',120 headers: requestHeaders,121 };122 return fetch(`/api/logout`, options);123};124export const signup = ({ username, password, verify }) => {125 const options = {126 method: 'POST',127 headers: requestHeaders,128 credentials: 'include',129 body: JSON.stringify({130 username: username.toLowerCase(),131 password,132 verify,133 }),134 };135 return fetch(`/api/signup`, options);...
Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3 videoParams: {4 }5};6var test = wpt('www.webpagetest.org', options);7 test.getTestResults(data.data.testId, function (err, data) {8 console.log(data);9 });10});11var wpt = require('webpagetest');12var options = {13 videoParams: {14 }15};16var test = wpt('www.webpagetest.org', options);17 test.getTestResults(data.data.testId, function (err, data) {18 console.log(data);19 });20});21var wpt = require('webpagetest');22var options = {
Using AI Code Generation
1var wptHook = require('wptHook');2var wptHookObj = new wptHook();3wptHookObj.requestHeaders(function(headers){4 console.log(headers);5});6var wptHook = require('wptHook');7var wptHookObj = new wptHook();8wptHookObj.responseHeaders(function(headers){9 console.log(headers);10});11var wptHook = require('wptHook');12var wptHookObj = new wptHook();13wptHookObj.requestCookies(function(cookies){14 console.log(cookies);15});16var wptHook = require('wptHook');17var wptHookObj = new wptHook();18wptHookObj.responseCookies(function(cookies){19 console.log(cookies);20});21var wptHook = require('wptHook');22var wptHookObj = new wptHook();23wptHookObj.requestPostData(function(postData){24 console.log(postData);25});26var wptHook = require('wptHook');27var wptHookObj = new wptHook();28wptHookObj.responsePostData(function(postData){29 console.log(postData);30});31var wptHook = require('wptHook');32var wptHookObj = new wptHook();33wptHookObj.requestPostData(function(postData){34 console.log(postData);35});36var wptHook = require('wptHook');37var wptHookObj = new wptHook();38wptHookObj.responsePostData(function(postData){39 console.log(postData);40});
Using AI Code Generation
1var wpt = require('./wpt.js');2var wpt = new wpt('API_KEY');3var options = {4};5wpt.runTest(options, function(err, data) {6 if (err) return console.log(err);7 console.log(data);8});
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!!