Best JavaScript code snippet using wpt
rest_client.js
Source:rest_client.js
1'use strict';2const OAuth = require('oauth-1.0a');3const request = require('request');4const logger = require('./log');5module.exports.RestClient = function (options) {6 let instance = {};7 var servelrUrl = options.url;8 var oauth = OAuth({9 consumer: {10 public: options.consumerKey,11 secret: options.consumerSecret12 },13 signature_method: 'HMAC-SHA1'14 });15 var token = {16 public: options.accessToken,17 secret: options.accessTokenSecret18 };19 function apiCall(request_data, request_token = '') {20 logger.debug('Calling API endpoint: ' + request_data.method + ' ' + request_data.url + ' token: ' + request_token);21 logger.info({22 url: request_data.url,23 method: request_data.method,24 headers: request_token ? { 'Authorization': 'Bearer ' + request_token } : oauth.toHeader(oauth.authorize(request_data, token)),25 json: true,26 body: request_data.body,27 });28 /* eslint no-undef: off*/29 return new Promise(function (resolve, reject) {30 request({31 url: request_data.url,32 method: request_data.method,33 headers: request_token ? { 'Authorization': 'Bearer ' + request_token } : oauth.toHeader(oauth.authorize(request_data, token)),34 json: true,35 body: request_data.body,36 }, function (error, response, body) {37 logger.debug('Response received')38 if (error) {39 logger.error('Error occured: ' + error);40 reject(error);41 return;42 } else if (!httpCallSucceeded(response)) {43 let errorMessage = ''44 if (body) {45 errorMessage = 'HTTP ERROR ' + body.code;46 } else {47 errorMessage = 'HTTP ERROR ' + response.code;48 }49 if (body && body.hasOwnProperty('message'))50 errorMessage = errorString(body.message, body.hasOwnProperty('parameters') ? body.parameters : {});51 logger.error('API call failed: ' + errorMessage);52 reject(errorMessage);53 }54 body.code = 200;55 resolve(body);56 });57 });58 }59 instance.consumerToken = function (login_data) {60 return apiCall({61 url: createUrl('/integration/customer/token'),62 method: 'POST',63 body: login_data64 })65 }66 function httpCallSucceeded(response) {67 return response.statusCode >= 200 && response.statusCode < 300;68 }69 function errorString(message, parameters) {70 if (parameters === null) {71 return message;72 }73 let parameterPlaceholder74 if (parameters instanceof Array) {75 for (let i = 0; i < parameters.length; i++) {76 parameterPlaceholder = '%' + (i + 1).toString();77 message = message.replace(parameterPlaceholder, parameters[i]);78 }79 } else if (parameters instanceof Object) {80 for (let key in parameters) {81 parameterPlaceholder = '%' + key;82 message = message.replace(parameterPlaceholder, parameters[key]);83 }84 }85 return message;86 }87 instance.get = function (resourceUrl, request_token = '') {88 const request_data = {89 url: createUrl(resourceUrl),90 method: 'GET'91 };92 return apiCall(request_data, request_token);93 }94 function createUrl(resourceUrl) {95 return servelrUrl + '/' + resourceUrl;96 }97 instance.post = function (resourceUrl, data, request_token = '') {98 const request_data = {99 url: createUrl(resourceUrl),100 method: 'POST',101 body: data102 };103 return apiCall(request_data, request_token);104 }105 instance.put = function (resourceUrl, data, request_token = '') {106 const request_data = {107 url: createUrl(resourceUrl),108 method: 'PUT',109 body: data110 };111 return apiCall(request_data, request_token);112 }113 instance.delete = function (resourceUrl, request_token = '') {114 const request_data = {115 url: createUrl(resourceUrl),116 method: 'DELETE'117 };118 return apiCall(request_data, request_token);119 }120 return instance;...
accountSlicer.js
Source:accountSlicer.js
1import AsyncStorage from '@react-native-async-storage/async-storage';2import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';3import { postApi, getApi } from '@app/api';4const initialState = {5 loading: false,6 request_token: null,7 access_token: null,8 account_id: null,9};10export const postRequestToken = createAsyncThunk('ACCOUNT_POST_REQUEST_TOKEN', async () => {11 try {12 const res = await postApi(4, `auth/request_token`, { redirect_to: 'http://www.themoviedb.org/' });13 return res.data;14 } catch (error) {15 throw error?.response?.data?.detail || error?.message;16 }17});18export const postAccessToken = createAsyncThunk('ACCOUNT_POST_ACCESS_TOKEN', async () => {19 const request_token = await AsyncStorage.getItem('request_token')20 try {21 const res = await postApi(4, `auth/access_token`, { request_token: request_token });22 return res.data;23 } catch (error) {24 throw error?.response?.data?.detail || error?.message;25 }26});27export const logout = createAsyncThunk('AUTH_LOGOUT', () => {28 console.log('Logout called!')29 AsyncStorage.clear();30});31export const accountSlicer = createSlice({32 name: 'account',33 initialState,34 reducers: {35 setLoading(state, action) {36 state.loading = action.payload;37 },38 removeRequestToken(state, action) {39 state.request_token = null;40 AsyncStorage.removeItem('request_token');41 },42 },43 extraReducers: builder => {44 builder.addCase(postRequestToken.pending, state => {45 state.loading = true;46 }),47 builder.addCase(postRequestToken.fulfilled, (state, action) => {48 state.loading = false;49 state.request_token = action.payload.request_token;50 AsyncStorage.setItem('request_token', action.payload.request_token);51 }),52 builder.addCase(postRequestToken.rejected, (state, action) => {53 state.loading = false;54 state.request_token = null;55 AsyncStorage.removeItem('request_token');56 }),57 builder.addCase(postAccessToken.pending, state => {58 state.loading = true;59 }),60 builder.addCase(postAccessToken.fulfilled, (state, action) => {61 state.loading = false;62 state.request_token = action.payload.request_token;63 state.account_id = action.payload.account_id;64 AsyncStorage.setItem('access_token', action.payload.access_token);65 AsyncStorage.setItem('account_id', action.payload.account_id);66 }),67 builder.addCase(postAccessToken.rejected, (state, action) => {68 state.loading = false;69 state.request_token = null;70 state.account_id = null;71 AsyncStorage.removeItem('access_token');72 AsyncStorage.removeItem('account_id');73 }),74 builder.addCase(logout.fulfilled, state => {75 state.loading = false;76 state.request_token = null;77 state.access_token = null;78 state.account_id = null;79 AsyncStorage.removeItem('request_token');80 AsyncStorage.removeItem('access_token');81 AsyncStorage.removeItem('account_id');82 })83 },84});85export const { setLoading, removeRequestToken } = accountSlicer.actions;...
Using AI Code Generation
1var request = require('request');2var options = {3 'headers': {4 },5 formData: {6 }7};8request(options, function (error, response) {9 if (error) throw new Error(error);10 console.log(response.body);11});12{ Error: socket hang up13 at connResetException (internal/errors.js:609:14)14 at TLSSocket.socketOnEnd (_http_client.js:474:23)15 at TLSSocket.emit (events.js:327:22)16 at endReadableNT (_stream_readable.js:1220:12)17 at processTicksAndRejections (internal/process/task_queues.js:84:21) code: 'ECONNRESET' }18{ Error: socket hang up19 at connResetException (internal/errors.js:609:14)20 at TLSSocket.socketOnEnd (_http_client.js:474:23)21 at TLSSocket.emit (events.js:327:22)22 at endReadableNT (_stream_readable.js:1220:12)23 at processTicksAndRejections (internal/process/task_queues.js:84:21) code: 'ECONNRESET' }24{ Error: socket hang up25 at connResetException (internal/errors.js:609:14)26 at TLSSocket.socketOnEnd (_http_client.js:474:23)27 at TLSSocket.emit (events.js:327:22)28 at endReadableNT (_stream_readable.js:1220:12)29 at processTicksAndRejections (internal/process/task_queues.js:84:21) code: 'ECONNRESET' }
Using AI Code Generation
1var wptools = require('wptools');2wptools.request_token(function(err, token) {3 if (err) {4 console.log(err);5 } else {6 console.log(token);7 }8});9var wptools = require('wptools');10wptools.request_token(function(err, token) {11 if (err) {12 console.log(err);13 } else {14 console.log(token);15 }16});17var wptools = require('wptools');18wptools.request_token(function(err, token) {19 if (err) {20 console.log(err);21 } else {22 console.log(token);23 }24});25var wptools = require('wptools');26wptools.request_token(function(err, token) {27 if (err) {28 console.log(err);29 } else {30 console.log(token);31 }32});33var wptools = require('wptools');34wptools.request_token(function(err, token) {35 if (err) {36 console.log(err);37 } else {38 console.log(token);39 }40});41var wptools = require('wptools');42wptools.request_token(function(err, token) {43 if (err) {44 console.log(err);45 } else {46 console.log(token);47 }48});49var wptools = require('wptools');50wptools.request_token(function(err, token) {51 if (err) {
Using AI Code Generation
1var wptools = require('wptools');2var request = require('request');3var options = {4};5wptools.request_token(options, function(err, response, body) {6 if (!err && response.statusCode == 200) {7 console.log(body);8 }9});10var request = require('request');11var options = {12 qs: {13 }14};15request(options, function(err, response, body) {16 if (!err && response.statusCode == 200) {17 console.log(body);18 }19});20class MenuBar(tk.Menu):21 def __init__(self, parent):22 tk.Menu.__init__(self, parent)23 file_menu = tk.Menu(self, tearoff=0)24 file_menu.add_command(label="New File", command=parent.new_file)25 file_menu.add_command(label="Open File", command=parent.open_file)26 file_menu.add_command(label="Save", command=parent.save)27 file_menu.add_command(label="Save As", command=parent.save_as)28 file_menu.add_separator()29 file_menu.add_command(label="Exit
Using AI Code Generation
1var wptools = require('wptools');2var request = require('request');3var fs = require('fs');4var options = {5};6var wiki = new wptools.page('Albert Einstein', options);7wiki.request_token(function(err, resp, body) {8 if (err) {9 console.log(err);10 } else {11 console.log(body);12 }13});14{ [Error: ENOENT: no such file or directory, open 'test.js']15 path: 'test.js' }
Using AI Code Generation
1var wptools = require('wptools');2var request = require('request');3request(url, function (error, response, body) {4 if (!error && response.statusCode == 200) {5 var info = JSON.parse(body);6 console.log(info);7 }8});9{10 "dependencies": {11 },12 "devDependencies": {13 },14 "scripts": {15 },16}
Using AI Code Generation
1var wptools = require('wptools');2var page = wptools.page('Albert Einstein');3page.get(function(err, resp) {4 console.log(resp);5});6{ pageid: 736,7 [ { contentformat: 'text/x-wiki',8 '*': '[[Category:People]]' } ] }
Using AI Code Generation
1var wptools = require('wptools');2wptools.request_token(function(token){3 console.log(token);4});5var wptools = require('wptools');6wptools.request_token(function(token){7 console.log(token);8 wptools.page('Barack Obama').then(function(page){9 console.log(page);10 });11});12If you want to get the content in JSON format, you can use the as_json() method. The code is given below:13var wptools = require('wptools');14wptools.request_token(function(token){15 console.log(token);16 wptools.page('Barack Obama').then(function(page){17 console.log(page.as_json());18 });19});20var wptools = require('wptools');21wptools.request_token(function(token){22 console.log(token);23 wptools.page('Donald Trump').then(function(page){24 console.log(page.as_json());25 });26});
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!!