How to use performRequest method in strest-cli

Best JavaScript code snippet using strest-cli

Api.test.ts

Source:Api.test.ts Github

copy

Full Screen

1import { delay } from '../delay'2import { PushpayJwtApi } from '../PushpayJwtApi'3import { BasicOAuthApi } from '../BasicOAuthApi'4const url = 'testUrl'5const originalTokens = {6 accessToken: 'accessToken',7 refreshToken: 'refreshToken',8}9const newTokens = {10 accessToken: 'newAccessToken',11 refreshToken: 'newRefreshToken',12}13const defaultHeaders = {14 headers: {15 Authorization: 'Bearer accessToken',16 },17}18const defaultData = { data: 'data' }19const clientCredentials = { clientId: 'clientId', clientSecret: 'clientSecret' }20const jwtAuthContext = {21 authToken: 'authToken',22 orgKey: 'orgKey',23}24const getSharedMocks = (tokens = originalTokens) => {25 const performRequest = jest.fn()26 let mutableTokens = tokens27 const getTokens = jest.fn(() => mutableTokens)28 const setTokens = jest.fn(tokens => {29 mutableTokens = tokens30 })31 const onAuthFailure = jest.fn()32 return {33 performRequest,34 onAuthFailure,35 getTokens,36 setTokens,37 }38}39const instantiateBasicOauth = (40 tokens = originalTokens,41 getDefaultConfig?: any,42) => {43 const mocks = getSharedMocks(tokens)44 const api = new BasicOAuthApi({45 clientCredentials,46 getDefaultConfig,47 ...mocks,48 })49 return {50 api,51 ...mocks,52 }53}54const instantiatePushpayJwt = () => {55 const mocks = getSharedMocks()56 const api = new PushpayJwtApi({57 getJwtAuthContext: () => jwtAuthContext,58 ...mocks,59 })60 return {61 api,62 ...mocks,63 }64}65describe('Api', () => {66 test('should narrow the types for success/error', async () => {67 const { api, performRequest } = instantiateBasicOauth()68 const successData = { x: 1 }69 const errorData = { y: 2 }70 performRequest.mockResolvedValueOnce({ data: successData })71 const successResponse = await api.get<typeof successData, typeof errorData>(72 {73 url: '',74 },75 )76 const successExpecation = successResponse.error77 ? successResponse.data.y78 : successResponse.data.x79 expect(successExpecation).toBe(successData.x)80 performRequest.mockRejectedValueOnce({ data: { y: 2 } })81 const errorResponse = await api.get<typeof successData, typeof errorData>({82 url: '',83 })84 const errorExpectation = errorResponse.error85 ? errorResponse.data.y86 : errorResponse.data.x87 expect(errorExpectation).toBe(errorData.y)88 })89 describe('when there are no pending refresh requests', () => {90 describe('when the request is successful', () => {91 test('should return the formatted response', async () => {92 const { api, performRequest } = instantiateBasicOauth()93 performRequest.mockResolvedValueOnce(defaultData)94 const response = await api.get(url)95 expect(performRequest).toHaveBeenCalledTimes(1)96 expect(response).toEqual({97 ...defaultData,98 error: false,99 })100 })101 })102 describe('when the request is unsuccessful', () => {103 describe('when the response is authenticated or we are requesting a token', () => {104 test('should return the formatted error', async () => {105 const { api, performRequest } = instantiateBasicOauth()106 const data = {107 message: 'error',108 response: {109 status: 403,110 },111 }112 performRequest.mockRejectedValue(data)113 const response = await api.get(url)114 expect(performRequest).toHaveBeenCalledTimes(1)115 expect(response).toEqual({116 ...data,117 error: true,118 })119 })120 })121 describe('when the response is not authenticated and we are not requesting a token', () => {122 test('should execute the request after refreshing the token', async () => {123 const { api, performRequest, getTokens } = instantiateBasicOauth()124 performRequest125 .mockRejectedValueOnce({126 response: {127 status: 401,128 },129 })130 .mockResolvedValueOnce({ data: newTokens })131 .mockResolvedValueOnce(defaultData)132 const response = await api.get(url)133 expect(performRequest).toHaveBeenCalledTimes(4)134 expect(getTokens()).toEqual(newTokens)135 expect(performRequest).toHaveBeenNthCalledWith(2, {136 method: 'post',137 url: 'oauth/token',138 data: {139 refreshToken: originalTokens.refreshToken,140 grantType: 'refresh_token',141 ...clientCredentials,142 },143 headers: { Authorization: `Bearer ${originalTokens.accessToken}` },144 })145 expect(response).toEqual({146 ...defaultData,147 error: false,148 })149 })150 })151 })152 })153 describe('when there is a pending refresh request', () => {154 const testQueuedRequest = async (shouldHaveError: boolean) => {155 const { api, performRequest } = instantiateBasicOauth()156 // set up mock to force a refresh157 performRequest158 /* initial request fails */159 .mockRejectedValueOnce({160 response: {161 status: 401,162 },163 })164 /* refresh request takes two ms */165 .mockImplementationOnce(async () => {166 await delay(2)167 return { data: newTokens }168 })169 /* initial request retries successfully */170 .mockResolvedValueOnce({})171 // Send a request while refreshing172 if (shouldHaveError) {173 performRequest.mockRejectedValueOnce(defaultData)174 } else {175 performRequest.mockResolvedValueOnce(defaultData)176 }177 // execute request to force a refresh (without awaiting it)178 api.get(url)179 await delay(1)180 // execute request that should be queued until done refreshing181 const response = await api.get(url)182 expect(response).toEqual({183 ...defaultData,184 error: shouldHaveError,185 })186 }187 test('should queue the request', async () => {188 await testQueuedRequest(false)189 })190 test('should return with error when the queued request rejects', async () => {191 await testQueuedRequest(true)192 })193 test('should only send one refresh request when multiple fail at the same time', async () => {194 const { api, performRequest } = instantiateBasicOauth()195 performRequest196 /* initial request fails */197 .mockRejectedValue({198 response: {199 status: 401,200 },201 })202 await Promise.all([api.get(url), api.get(url)])203 const refreshes = performRequest.mock.calls.filter(204 ([{ url }]) => url === 'oauth/token',205 )206 expect(refreshes).toHaveLength(1)207 })208 })209 describe('when the refresh request fails', () => {210 test('should call the onAuthFailure handler', async () => {211 const { api, performRequest, onAuthFailure } = instantiateBasicOauth()212 performRequest213 /* initial request fails */214 .mockRejectedValueOnce({215 response: {216 status: 401,217 },218 })219 /* refresh request fails */220 .mockRejectedValueOnce({})221 await api.get(url)222 expect(onAuthFailure).toHaveBeenCalledTimes(1)223 })224 })225 describe('when a refresh is attempted without a refresh token', () => {226 test('should cancel pending requests', async () => {227 const { api, performRequest } = instantiateBasicOauth()228 performRequest229 /* initial request fails */230 .mockRejectedValueOnce({231 response: {232 status: 401,233 },234 })235 const response = await api.get(url)236 expect(response.error).toBe(true)237 })238 })239 test('should apply the default config to each request', async () => {240 const { api, performRequest } = instantiateBasicOauth(undefined, () => ({241 baseURL: 'http://new-default.com',242 }))243 await api.post('test')244 expect(performRequest).toHaveBeenCalledWith({245 baseURL: 'http://new-default.com',246 ...defaultHeaders,247 method: 'post',248 url: 'test',249 })250 })251 test('should be able to use both overloads of wrapped request methods', async () => {252 const { api, performRequest } = instantiateBasicOauth()253 await api.get({ url: 'get-url' })254 await api.post({ url: 'post-url' })255 await api.put({ url: 'put-url' })256 await api.delete({ url: 'delete-url' })257 expect(performRequest).toHaveBeenCalledWith({258 ...defaultHeaders,259 method: 'get',260 url: 'get-url',261 })262 expect(performRequest).toHaveBeenCalledWith({263 ...defaultHeaders,264 method: 'post',265 url: 'post-url',266 })267 expect(performRequest).toHaveBeenCalledWith({268 ...defaultHeaders,269 method: 'put',270 url: 'put-url',271 })272 expect(performRequest).toHaveBeenCalledWith({273 ...defaultHeaders,274 method: 'delete',275 url: 'delete-url',276 })277 })278 describe('#authenticate', () => {279 describe('when the authStrategy is basicOAuth', () => {280 const params = {281 password: 'password',282 username: 'username',283 subdomain: 'subdomain',284 }285 test('should be able to authenticate', async () => {286 const { api, performRequest, getTokens } = instantiateBasicOauth()287 performRequest.mockResolvedValueOnce({ data: newTokens })288 const { error, data } = await api.authenticate('password', params)289 expect(error).toBe(false)290 expect(data).toBe(newTokens)291 expect(getTokens()).toBe(newTokens)292 expect(performRequest).toHaveBeenCalledWith({293 ...defaultHeaders,294 method: 'post',295 url: 'oauth/token',296 data: {297 ...clientCredentials,298 ...params,299 grantType: 'password',300 },301 })302 })303 test('should call onAuthFailure when the request fails', async () => {304 const { api, performRequest, onAuthFailure } = instantiateBasicOauth()305 const errorResponse = { data: { message: 'failure' } }306 performRequest.mockRejectedValueOnce(errorResponse)307 const { error, data } = await api.authenticate('password', params)308 expect(error).toBe(true)309 expect(data).toBe(errorResponse.data)310 expect(onAuthFailure).toHaveBeenCalledWith(errorResponse)311 })312 })313 describe('when the authStrategy is pushpayJwt', () => {314 test('should be able to authenticate', async () => {315 const { api, performRequest, getTokens } = instantiatePushpayJwt()316 performRequest.mockResolvedValueOnce({ data: newTokens })317 const response = await api.authenticate()318 // ensure that types are correct for error statuses319 if (response.error) {320 response.data.errors[0]321 } else {322 response.data.accessToken323 }324 expect(response.error).toBe(false)325 expect(response.data).toBe(newTokens)326 expect(getTokens()).toBe(newTokens)327 expect(performRequest).toHaveBeenCalledWith({328 method: 'post',329 url: 'internal/identity',330 data: {331 organizationKey: jwtAuthContext.orgKey,332 },333 headers: {334 Authorization: `Bearer ${jwtAuthContext.authToken}`,335 },336 })337 })338 test('should be return errors', async () => {339 const { api, performRequest } = instantiatePushpayJwt()340 const errors = {341 errors: [{ type: 'ERROR', message: 'message ' }],342 }343 performRequest.mockRejectedValueOnce({344 data: errors,345 })346 const response = await api.authenticate()347 expect(response.error).toBe(true)348 expect(response.data).toBe(errors)349 })350 })351 })...

Full Screen

Full Screen

doctor-api.js

Source:doctor-api.js Github

copy

Full Screen

...20 let request = new Request(HOST.backend_api + endpoint.get_caregivers, {21 method: 'GET',22 });23 console.log(request.url);24 RestApiClient.performRequest(request, callback);25}26function getMedications(callback) {27 let request = new Request(HOST.backend_api + endpoint.get_medications, {28 method: 'GET',29 });30 console.log(request.url);31 RestApiClient.performRequest(request, callback);32}33function getPersonById(params, callback){34 let request = new Request(HOST.backend_api + endpoint.get_persons + params.id, {35 method: 'GET'36 });37 console.log(request.url);38 RestApiClient.performRequest(request, callback);39}40function postPatient(patient, callback){41 let request = new Request(HOST.backend_api + endpoint.post_patient , {42 method: 'POST',43 headers : {44 'Accept': 'application/json',45 'Content-Type': 'application/json',46 },47 body: JSON.stringify(patient)48 });49 console.log("URL: " + request.url);50 RestApiClient.performRequest(request, callback);51}52function postCaregiver(caregiver, callback){53 let request = new Request(HOST.backend_api + endpoint.post_caregiver , {54 method: 'POST',55 headers : {56 'Accept': 'application/json',57 'Content-Type': 'application/json',58 },59 body: JSON.stringify(caregiver)60 });61 console.log("URL: " + request.url);62 RestApiClient.performRequest(request, callback);63}64function postMedication(caregiver, callback){65 let request = new Request(HOST.backend_api + endpoint.post_medication , {66 method: 'POST',67 headers : {68 'Accept': 'application/json',69 'Content-Type': 'application/json',70 },71 body: JSON.stringify(caregiver)72 });73 console.log("URL: " + request.url);74 RestApiClient.performRequest(request, callback);75}76function postMedicationPlan(medicationPlan, callback){77 let request = new Request(HOST.backend_api + endpoint.post_medicationPlan , {78 method: 'POST',79 headers : {80 'Accept': 'application/json',81 'Content-Type': 'application/json',82 },83 body: JSON.stringify(medicationPlan)84 });85 console.log("URL: " + request.url);86 RestApiClient.performRequest(request, callback);87}88function postMedicationPerPlan(medicationPerPlan, callback){89 let request = new Request(HOST.backend_api + endpoint.post_medicationPerPlan , {90 method: 'POST',91 headers : {92 'Accept': 'application/json',93 'Content-Type': 'application/json',94 },95 body: JSON.stringify(medicationPerPlan)96 });97 console.log("URL: " + request.url);98 RestApiClient.performRequest(request, callback);99}100function updatePatient(patient, callback){101 let request = new Request(HOST.backend_api + endpoint.update_patient , {102 method: 'UPDATE',103 headers : {104 'Accept': 'application/json',105 'Content-Type': 'application/json',106 },107 body: JSON.stringify(patient)108 });109 console.log("URL: " + request.url);110 RestApiClient.performRequest(request, callback);111}112function getPatients(callback) {113 const loggedUser = sessionStorage.getItem('loggedUser');114 let request = new Request(HOST.backend_api + endpoint.get_patients, {115 method: 'GET',116 });117 console.log(request.url);118 RestApiClient.performRequest(request, callback);119}120function getMedicationPlans(callback) {121 let request = new Request(HOST.backend_api + endpoint.get_medications_plan, {122 method: 'GET',123 });124 console.log(request.url);125 RestApiClient.performRequest(request, callback);126}127function getMedicationPerPlans(callback) {128 let request = new Request(HOST.backend_api + endpoint.get_medications_per_plan, {129 method: 'GET',130 });131 console.log(request.url);132 RestApiClient.performRequest(request, callback);133}134function getActivities(username, date, callback) {135 let request = new Request(HOST.backend_api + endpoint.activity_for_pacient +'?patientUsername=' + username + '&date=' + date , {136 method: 'GET',137 headers : {138 'Accept': 'application/json',139 'Content-Type': 'application/json',140 }141 });142 console.log("URL: " + request.url);143 RestApiClient.performRequest(request, callback);144}145function getActivitiesForChart(username, date, callback) {146 let request = new Request(HOST.backend_api + endpoint.activity_for_chart +'?patientUsername=' + username + '&date=' + date , {147 method: 'GET',148 headers : {149 'Accept': 'application/json',150 'Content-Type': 'application/json',151 }152 });153 console.log("URL: " + request.url);154 RestApiClient.performRequest(request, callback);155}156function getPillDispenser(username, date, callback) {157 let request = new Request(HOST.backend_api + endpoint.pill_dispenser_for_pacient +'?patientUsername=' + username + '&date=' + date , {158 method: 'GET',159 headers : {160 'Accept': 'application/json',161 'Content-Type': 'application/json',162 }163 });164 console.log("URL: " + request.url);165 RestApiClient.performRequest(request, callback);166}167export {168 getCaregivers,169 getPersonById,170 postPatient,171 getPatients,172 updatePatient,173 postCaregiver,174 postMedication,175 postMedicationPlan,176 postMedicationPerPlan,177 getMedications,178 getMedicationPlans,179 getMedicationPerPlans,...

Full Screen

Full Screen

Reports.ts

Source:Reports.ts Github

copy

Full Screen

...22 });23};2425export const REPORT_ENDPOINTS: Record<string, any> = {26 consumes_by_client: performRequest('consumes_by_client'),27 charges_by_dealer: performRequest('charges_by_dealer'),28 consumes_ranking: performRequest('consumes_ranking'),29 charges_ranking: performRequest('charges_ranking'),30 charges_by_client: performRequest('charges_by_client'),31 clients_card_use: performRequest('clients_card_use'),32 clients_card_expiration: performRequest('clients_card_expiration'),33 consumes_by_business_area: performRequest('consumes_by_business_area'),34 consumes_by_economic: performRequest('consumes_by_economic'),35 client_consumes_by_dealer: performRequest('client_consumes_by_dealer'),36 refunds: performRequest('refunds'),37 pending_charges_refund: performRequest('pending_charges_refund'),38 unsigned_contacts: performRequest('unsigned_contacts'),39 chasis_detail: performRequest('chasis_detail'), ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var strest = require('strest-client');2var options = {3};4strest.performRequest(options, '', function (data) {5 console.log(data);6});7{"message":"Hello World"}

Full Screen

Using AI Code Generation

copy

Full Screen

1var strest = require('strest-client');2var options = {3};4strest.performRequest(options, '', function(statusCode, result) {5 console.log('Status Code: ' + statusCode);6 console.log('Result: ' + result);7});8var http = require('http');9var strest = require('strest-client');10http.createServer(function(req, res) {11 console.log('Request received: ' + req.url);12 strest.respond(res, 200, 'This is a test');13}).listen(3000);14var strest = require('strest-client');15var options = {16};17strest.performRequest(options, '', function(statusCode, result) {18 console.log('Status Code: ' + statusCode);19 console.log('Result: ' + result);20});21var http = require('http');22var strest = require('strest-client');23http.createServer(function(req, res) {24 console.log('Request received: ' + req.url);25 strest.respond(res, 200, 'This is a test');26}).listen(3000);27var strest = require('strest-client');28var options = {29};30strest.performRequest(options, 'This is a test', function(statusCode, result) {31 console.log('Status Code: ' + statusCode);32 console.log('Result: ' + result);33});34var http = require('http');35var strest = require('strest-client');36http.createServer(function(req, res) {37 console.log('Request received: ' + req.url);38 var body = '';39 req.on('data', function(data) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var strest = require('strest-client');2var request = strest.performRequest;3 if (err) {4 console.log(err);5 } else {6 console.log(res);7 }8});9var strest = require('strest-client');10var request = strest.performRequest;11 if (err) {12 console.log(err);13 } else {14 console.log(res);15 }16});17var strest = require('strest-client');18var request = strest.performRequest;19 if (err) {20 console.log(err);21 } else {22 console.log(res);23 }24});25var strest = require('strest-client');26var request = strest.performRequest;27 if (err) {28 console.log(err);29 } else {30 console.log(res);31 }32});33var strest = require('strest-client');34var request = strest.performRequest;35 if (err) {36 console.log(err);37 } else {38 console.log(res);39 }40});41var strest = require('strest-client');42var request = strest.performRequest;43 if (err) {44 console.log(err);45 } else {46 console.log(res);47 }48});49var strest = require('strest-client');50var request = strest.performRequest;51 if (err) {52 console.log(err);53 } else {54 console.log(res);55 }56});

Full Screen

Using AI Code Generation

copy

Full Screen

1var strest = require('strest-client');2var obj = new strest();3var options = {4};5obj.performRequest(options, function(statusCode, result) {6 console.log('Status Code: ' + statusCode);7 console.log('Result: ' + result);8});9var strest = require('strest-client');10var obj = new strest();11obj.setHost('localhost');12obj.setPort(3000);13var strest = require('strest-client');14var obj = new strest();15var options = {16 headers: {17 }18};19obj.performRequest(options, function(statusCode, result) {20 console.log('Status Code: ' + statusCode);21 console.log('Result: ' + result);22});

Full Screen

Using AI Code Generation

copy

Full Screen

1var strest = require('strest-client');2var req = {3};4strest.performRequest(req, function(err, res) {5 console.log(res);6});7var strest = require('strest-client');8var req = {9};10strest.performRequest(req, function(err, res) {11 console.log(res);12});

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var strest = require('./strest-client.js');3var options = {4 headers: {5 },6 body: JSON.stringify({message: 'hello world'})7};8strest.performRequest(options, function(statusCode, result) {9 console.log('Status Code: ' + statusCode);10 console.log('Result: ' + result);11});12var request = require('request');13exports.performRequest = function(options, callback) {14 request(options, function(error, response, body) {15 if (error) {16 callback(error);17 } else {18 callback(response.statusCode, body);19 }20 });21};

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run strest-cli automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful