Best JavaScript code snippet using frisby
api.ts
Source:api.ts
1import { toFormUrlencoded } from '../utils/utils';2import { IApiBooleanResult } from './IApiBooleanResult';3import { IApiGameResponse } from './IApiGameResponse';4import { IApiGamesResponse } from './IApiGamesResponse';5import { IApiGameStats } from './IApiGameStats';6import { IApiOpponent } from './IApiOpponent';7import { IApiPopup } from './IApiPopup';8import { IApiQuizAnswer } from './IApiQuiz';9import { IApiQuizResponse } from './IApiQuizResponse';10import { IApiSendMessageResponse } from './IApiSendMessageResponse';11import { IApiStateResponse } from './IApiStateResponse';12import { IApiStats } from './IApiStats';13import { IApiUser } from './IApiUser';14import { IApiUserSearchResponse } from './IApiUserSearchResponse';15import { MD5 } from './md5';16const CONTENT_TYPE_URLENCODED = 'application/x-www-form-urlencoded;charset=UTF-8';17export interface IRequestOptions {18 contentType?: string;19 body?: string;20 queryParams?: { [key: string]: string };21}22export type BackendRequestFn = (method: 'GET' | 'POST', path: string, options: IRequestOptions) => Promise<Response>;23export function apiLogin(requestFn: BackendRequestFn, userName: string, passwordSalt: string, password: string,24): Promise<IApiPopup | { cookie: string, body: IApiStateResponse }> {25 const passwordHash = getPasswordHash(passwordSalt, password);26 const body = toFormUrlencoded({27 name: userName,28 pwd: passwordHash,29 });30 return requestFn('POST', 'users/login', { body, contentType: CONTENT_TYPE_URLENCODED }).then(response =>31 response.json().then(responseBody => {32 if (responseBody.logged_in) {33 return {34 body: responseBody,35 cookie: response.headers.get('Set-Cookie') || response.headers.get('X-Set-Cookie'),36 };37 }38 return responseBody;39 }),40 );41}42export function apiCreateUser(requestFn: BackendRequestFn, userName: string, email: string, passwordSalt: string, password: string,43): Promise<IApiPopup | { cookie: string, body: IApiStateResponse }> {44 const passwordHash = getPasswordHash(passwordSalt, password);45 const body = toFormUrlencoded({46 email,47 name: userName,48 pwd: passwordHash,49 });50 return requestFn('POST', 'users/create', { body, contentType: CONTENT_TYPE_URLENCODED }).then(response =>51 response.json().then(responseBody => {52 if (responseBody.logged_in) {53 return {54 body: responseBody,55 cookie: response.headers.get('Set-Cookie') || response.headers.get('X-Set-Cookie'),56 };57 }58 return responseBody;59 }),60 );61}62export function apiUpdateUser(requestFn: BackendRequestFn, userName: string, email: string, passwordSalt: string, password: string | null,63): Promise<IApiPopup | { user: IApiUser }> {64 const passwordHash = password == null ? '' : getPasswordHash(passwordSalt, password);65 const body = toFormUrlencoded({66 email,67 name: userName,68 pwd: passwordHash,69 });70 return requestFn('POST', 'users/update_user', { body, contentType: CONTENT_TYPE_URLENCODED }).then(response => response.json());71}72export function apiUpdateAvatar(requestFn: BackendRequestFn, avatarCode: string): Promise<IApiBooleanResult> {73 const body = toFormUrlencoded({74 avatar_code: avatarCode,75 });76 return requestFn('POST', 'users/update_avatar', { body, contentType: CONTENT_TYPE_URLENCODED }).then(response => response.json());77}78export function apiAddDeviceTokenAndroid(requestFn: BackendRequestFn, deviceToken: string, deviceType: string): Promise<IApiBooleanResult> {79 const body = toFormUrlencoded({80 device_token: deviceToken,81 device_type: deviceType,82 });83 return requestFn('POST', 'users/add_device_token_android', { body, contentType: CONTENT_TYPE_URLENCODED })84 .then(response => response.json());85}86export function apiRequestState(requestFn: BackendRequestFn): Promise<IApiStateResponse> {87 return requestFn('POST', 'users/current_user_games_m', {}).then(response => response.json());88}89export function apiRequestGames(requestFn: BackendRequestFn, gameIds: number[]): Promise<IApiGamesResponse> {90 const body = toFormUrlencoded({91 gids: '[' + gameIds.join(',') + ']',92 });93 return requestFn('POST', 'games/short_games', { body, contentType: CONTENT_TYPE_URLENCODED })94 .then(response => response.json());95}96export function apiRequestGame(requestFn: BackendRequestFn, gameId: number): Promise<IApiGameResponse> {97 const body = toFormUrlencoded({98 gids: String(gameId),99 });100 return requestFn('POST', 'games_f', { body, contentType: CONTENT_TYPE_URLENCODED })101 .then(response => response.json());102}103export function apiRequestGameM(requestFn: BackendRequestFn, gameId: number): Promise<IApiGameResponse> {104 const body = toFormUrlencoded({105 gids: String(gameId),106 });107 return requestFn('POST', 'games_m', { body, contentType: CONTENT_TYPE_URLENCODED })108 .then(response => response.json());109}110export function apiCreateGame(requestFn: BackendRequestFn, opponentId: string, mode = 0, wasRecommended = 0): Promise<IApiGameResponse> {111 const body = toFormUrlencoded({112 mode: String(mode),113 opponent_id: opponentId,114 was_recommended: String(wasRecommended),115 });116 return requestFn('POST', 'games/create_game', { body, contentType: CONTENT_TYPE_URLENCODED })117 .then(response => response.json());118}119export function apiCreateRandomGame(requestFn: BackendRequestFn, mode = 0): Promise<IApiGameResponse> {120 const body = toFormUrlencoded({121 mode: String(mode),122 });123 return requestFn('POST', 'games/start_random_game', { body, contentType: CONTENT_TYPE_URLENCODED })124 .then(response => response.json());125}126export function apiDeclineGame(requestFn: BackendRequestFn, gameId: number): Promise<IApiBooleanResult> {127 const body = toFormUrlencoded({128 accept: '0',129 game_id: String(gameId),130 });131 return requestFn('POST', 'games/accept', { body, contentType: CONTENT_TYPE_URLENCODED })132 .then(response => response.json());133}134export function apiGiveUpGame(requestFn: BackendRequestFn, gameId: number): Promise<IApiGameResponse> {135 const body = toFormUrlencoded({136 game_id: String(gameId),137 });138 return requestFn('POST', 'games/give_up', { body, contentType: CONTENT_TYPE_URLENCODED })139 .then(response => response.json());140}141export function apiSendMessage(requestFn: BackendRequestFn, gameId: number, text: string): Promise<IApiSendMessageResponse> {142 const body = toFormUrlencoded({143 game_id: String(gameId),144 text,145 });146 return requestFn('POST', 'games/send_message', { body, contentType: CONTENT_TYPE_URLENCODED })147 .then(response => response.json());148}149export function apiRemoveFriend(requestFn: BackendRequestFn, userId: string): Promise<{ removed_id: string }> {150 const body = toFormUrlencoded({151 friend_id: userId,152 });153 return requestFn('POST', 'users/remove_friend', { body, contentType: CONTENT_TYPE_URLENCODED })154 .then(response => response.json());155}156export function apiAddFriend(requestFn: BackendRequestFn, userId: string): Promise<IApiPopup> {157 const body = toFormUrlencoded({158 friend_id: userId,159 });160 return requestFn('POST', 'users/add_friend', { body, contentType: CONTENT_TYPE_URLENCODED })161 .then(response => response.json());162}163export function apiFindUser(requestFn: BackendRequestFn, searchName: string): Promise<IApiUserSearchResponse | IApiPopup> {164 const body = toFormUrlencoded({165 opponent_name: searchName,166 });167 return requestFn('POST', 'users/find_user', { body, contentType: CONTENT_TYPE_URLENCODED })168 .then(response => response.json());169}170export function apiRequestUploadRound(171 requestFn: BackendRequestFn,172 gameId: number,173 isImageQuestionDisabled: 0 | 1,174 catChoice: number,175 answers: number[],176 questionTypes: number[],177): Promise<IApiGameResponse> {178 const body = toFormUrlencoded({179 answers: '[' + answers.join(',') + ']',180 cat_choice: String(catChoice),181 game_id: String(gameId),182 is_image_question_disabled: String(isImageQuestionDisabled),183 question_types: '[' + questionTypes.join(',') + ']',184 });185 return requestFn('POST', 'games/upload_round_answers', { body, contentType: CONTENT_TYPE_URLENCODED })186 .then(response => response.json());187}188export function apiRequestQuiz(189 requestFn: BackendRequestFn,190 quizId: string,191): Promise<IApiQuizResponse> {192 return requestFn('GET', 'quizzes/', {193 queryParams: { quiz_id: quizId },194 })195 .then(response => response.json());196}197export function apiRequestUploadQuizRound(198 requestFn: BackendRequestFn,199 quizId: string,200 answers: IApiQuizAnswer[],201 giveUp = false,202): Promise<IApiQuizResponse> {203 const body = toFormUrlencoded({204 answer_dicts: JSON.stringify(answers),205 give_up: giveUp ? '1' : '0',206 });207 return requestFn('POST', 'quizzes/my_answers', {208 body,209 contentType: CONTENT_TYPE_URLENCODED,210 queryParams: { quiz_id: quizId },211 })212 .then(response => response.json());213}214export interface IApiDailyChallengeQuestion {215 type: 'text';216 revision: string;217 revision_id: number;218 question: string;219 wrong1: string;220 wrong2: string;221 wrong3: string;222 correct: string;223 image: null;224 created: string; // 2018-07-06T13:02:52.000000+00:00225 locale: string; // "de_DE"226}227export interface IApiDailyChallengeResponse {228 todaysChallenge: {229 locale: string, // de-DE230 challengeDate: string, // "2019-01-20",231 questions: {232 id: number,233 name: string,234 color: string,235 questions: IApiDailyChallengeQuestion[],236 }[],237 };238 tomorrowsCategory: {239 id: number,240 name: string,241 color: string,242 };243}244export function apiRequestDailyChallenge(245 requestFn: BackendRequestFn,246 challengeSize: number,247): Promise<IApiDailyChallengeResponse> {248 return requestFn('GET', 'games/dailyChallenge', {249 queryParams: { challengeSize: challengeSize.toString() },250 })251 .then(response => response.json());252}253export interface IApiDailyChallengeUploadResponse {254 locale: string; // de-DE255 friendTopList: IApiRatingUser[];256 maxScore: number;257 topList: IApiRatingUser[];258}259export function apiUploadDailyChallenge(260 requestFn: BackendRequestFn,261 score: number,262): Promise<IApiDailyChallengeUploadResponse> {263 const body = toFormUrlencoded({264 facebook_ids: '[]',265 score: score.toString(),266 });267 return requestFn('POST', 'games/submitBlitzGame', {268 body,269 contentType: CONTENT_TYPE_URLENCODED,270 })271 .then(response => response.json());272}273export interface IApiRatingUser extends IApiOpponent {274 score: number;275}276export interface IApiTopListRatingResponse {277 users: IApiRatingUser[];278}279export function apiRequestTopListRating(280 requestFn: BackendRequestFn,281 mode = 2,282): Promise<IApiTopListRatingResponse> {283 return requestFn('GET', 'users/top_list_rating', {284 queryParams: {285 fids: '[]',286 mode: mode.toString(),287 },288 })289 .then(response => response.json());290}291export function apiRequestStats(requestFn: BackendRequestFn): Promise<IApiStats> {292 return requestFn('GET', 'stats/my_stats', {}).then(response => response.json());293}294export function apiRequestGameStats(requestFn: BackendRequestFn): Promise<IApiGameStats> {295 return requestFn('GET', 'stats/my_game_stats', {}).then(response => response.json());296}297function getPasswordHash(passwordSalt: string, password: string): string {298 const plain = passwordSalt + password;299 return MD5(plain);...
exampleStripeInvoice.js
Source:exampleStripeInvoice.js
1import { LightningElement, track, api } from 'lwc';2import makeGetCallout from '@salesforce/apex/StripeAPIHandler.makeGetCallout';3export default class ExampleInvoice extends LightningElement {4 5 async Invoiceurl(){6 //SetExample Vars7 var email = "myexampleCustomer@example.com";8 var amount = 76856.009 var currency = 'usd';10 //Get Customer11 var customerID;12 var url = "https://api.stripe.com//v1/customers?email=" + email + "&limit=1";13 var method = 'GET';14 var urlencoded = new URLSearchParams();15 let pgetcustomer = await makeGetCallout({urlencoded:null,url:url, method:method});16 var getcustomer = JSON.parse(pgetcustomer);17 if (getcustomer.data.length >= 1){18 customerID = getcustomer.data[0].id19 }20 //Create Customer if no customer is found21 if (getcustomer.data.length == 0){22 var urlencoded = new URLSearchParams();23 urlencoded.append("email", email);24 var url = "https://api.stripe.com//v1/customers";25 var method = "POST";26 let pcreatecustomer = await makeGetCallout({urlencoded:urlencoded.toString(),url:url, method:method});27 var createcustomer = JSON.parse(pcreatecustomer);28 customerID = createcustomer.id29 }30 //Create Line Item31 var urlencoded = new URLSearchParams();32 urlencoded.append("customer", customerID);33 urlencoded.append("amount", amount);34 urlencoded.append("currency", currency);35 urlencoded.append("description", "Sales Force Example Integration");36 var url = "https://api.stripe.com//v1/invoiceitems";37 var method = "POST";38 let plineitems = await makeGetCallout({urlencoded:urlencoded.toString(),url:url, method:method});39 var lineitems = JSON.parse(plineitems);40 41 //Create Invoice42 var urlencoded = new URLSearchParams();43 urlencoded.append("customer", customerID);44 urlencoded.append("collection_method", "send_invoice");45 urlencoded.append("days_until_due", 30);46 urlencoded.append("description", "SalesForce Example Integration");47 var url = "https://api.stripe.com//v1/invoices";48 var method = "POST";49 let pinvoice = await makeGetCallout({urlencoded:urlencoded.toString(),url:url, method:method});50 var invoice = JSON.parse(pinvoice);51 //Finalize Invoice52 var urlencoded = new URLSearchParams();53 var url = "https://api.stripe.com//v1/invoices/" + invoice.id + "/finalize"54 var method = "POST";55 let pfinvoice = await makeGetCallout({urlencoded:null,url:url, method:method});56 var finvoice = JSON.parse(pfinvoice);57 window.open(finvoice.hosted_invoice_url);58 59 } 60 ...
stripeExampleCheckout.js
Source:stripeExampleCheckout.js
1import { LightningElement } from 'lwc';2import makeGetCallout from '@salesforce/apex/StripeAPIHandler.makeGetCallout';3export default class StripeExampleCheckout extends LightningElement {4 customerEmail = 'exampleCustomer@example.com';5 amount = 76800.00;6 paymentMethodOne='card';7 paymentMethodTwo='klarna';8 customerID = '';9 currency = 'usd';10 async getCheckoutLink(){11 //Get Customer12 var customerID;13 var url = "https://api.stripe.com//v1/customers?email=" + this.customerEmail + "&limit=1";14 var method = 'GET';15 var urlencoded = new URLSearchParams();16 let pgetcustomer = await makeGetCallout({urlencoded:null,url:url, method:method});17 var getcustomer = JSON.parse(pgetcustomer);18 if (getcustomer.data.length >= 1){19 customerID = getcustomer.data[0].id20 }21 //Create Customer if no customer is found22 if (getcustomer.data.length == 0){23 var urlencoded = new URLSearchParams();24 urlencoded.append("email", this.customerEmail);25 var url = "https://api.stripe.com//v1/customers";26 var method = "POST";27 let pcreatecustomer = await makeGetCallout({urlencoded:urlencoded.toString(),url:url, method:method});28 var createcustomer = JSON.parse(pcreatecustomer);29 customerID = createcustomer.id30 }31 //Create link32 var urlencoded = new URLSearchParams();33 urlencoded.append("cancel_url", "https://www.google.com");34 urlencoded.append("success_url", "https://www.google.com");35 urlencoded.append("customer", customerID);36 urlencoded.append("customer_update[address]", "auto");37 urlencoded.append("customer_update[name]", "auto");38 urlencoded.append("line_items[0][price_data][currency]", this.currency);39 urlencoded.append("line_items[0][price_data][product_data][name]", "Sales Force Example");40 urlencoded.append("line_items[0][price_data][product_data][description]", "Sales Force Example");41 urlencoded.append("line_items[0][price_data][unit_amount_decimal]", this.amount);42 urlencoded.append("line_items[0][quantity]", "1");43 urlencoded.append("mode", "payment");44 urlencoded.append("payment_method_types[0]", this.paymentMethodOne);45 urlencoded.append("payment_method_types[1]", this.paymentMethodTwo);46 var method = 'POST';47 var url = 'https://api.stripe.com/v1/checkout/sessions'48 let pcheckout = await makeGetCallout({urlencoded:urlencoded.toString(),url:url, method:method});49 var checkout = JSON.parse(pcheckout);50 window.open(checkout.url);51 }...
Using AI Code Generation
1var frisby = require('frisby');2var FormData = require('form-data');3var fs = require('fs');4var form = new FormData();5form.append('file', fs.createReadStream('test.txt'));6form.append('file', fs.createReadStream('test.txt'));7frisby.create('Test POST with urlencoded')8 .expectStatus(200)9 .toss();
Using AI Code Generation
1var frisby = require('frisby');2frisby.create('Test POST')3 }, {json: false})4 .expectStatus(200)5 .toss();6frisby.create('Test POST')7 }, {json: true})8 .expectStatus(200)9 .toss();10frisby.create('Test POST')11 }, {json: true})12 .expectStatus(200)13 .toss();14frisby.create('Test POST')15 }, {json: true})16 .expectStatus(200)17 .toss();18frisby.create('Test POST')19 }, {json: true})20 .expectStatus(200)21 .toss();22frisby.create('Test POST')23 }, {json: true})24 .expectStatus(200)25 .toss();26frisby.create('Test POST')27 }, {json: true})28 .expectStatus(200)29 .toss();30frisby.create('Test POST')31 }, {json: true})32 .expectStatus(200)33 .toss();34frisby.create('Test POST')35 }, {json: true})36 .expectStatus(200)37 .toss();38frisby.create('Test POST')
Using AI Code Generation
1var frisby = require('frisby');2frisby.create('Get data from google')3 .expectStatus(200)4 .toss();5var frisby = require('frisby');6frisby.create('Get data from google')7 .expectStatus(200)8 .toss();9var frisby = require('frisby');10frisby.create('Get data from google')11 .expectStatus(200)12 .toss();13var frisby = require('frisby');14frisby.create('Get data from google')15 .expectStatus(200)16 .toss();17var frisby = require('frisby');18frisby.create('Get data from google')19 .expectStatus(200)20 .toss();21var frisby = require('frisby');22frisby.create('Get data from google')23 .expectStatus(200)24 .toss();25var frisby = require('frisby');26frisby.create('Get data from google')27 .expectStatus(200)28 .toss();29var frisby = require('frisby');30frisby.create('Get data from google')31 .expectStatus(200)32 .toss();33var frisby = require('frisby');34frisby.create('Get data from google')35 .expectStatus(200)36 .toss();
Using AI Code Generation
1var frisby = require('frisby');2var url = require('url');3var querystring = require('querystring');4var urlEncoded = require('./urlEncoded');5frisby.create('Test urlEncoded method')6 .expectStatus(200)7 .expectHeaderContains('content-type', 'application/x-www-form-urlencoded')8 .expectBodyContains('foo=bar&baz=qux')9 .toss();10var url = require('url');11var querystring = require('querystring');12module.exports = function (data) {13 return {14 url: url.format({15 }),16 headers: {17 },18 body: querystring.stringify(data)19 };20};21frisby.create('Test urlEncoded method')22 .expectStatus(200)23 .expectHeaderContains('content-type', 'application/x-www-form-urlencoded')24 .expectBodyContains('foo=bar&baz=qux')25 .toss();
Using AI Code Generation
1var frisby = require('frisby');2frisby.create('Test POST')3 {4 },5 {json: false}6 .expectStatus(200)7 .expectHeaderContains('content-type', 'application/json')8 .expectJSON({9 })10 .toss();11 ✓ Test POST (157ms)121 tests complete (157ms)
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!!