Skip to content

Commit

Permalink
refactor 2
Browse files Browse the repository at this point in the history
  • Loading branch information
Romarionijim committed Apr 12, 2024
1 parent 8c74c9e commit d0195aa
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 107 deletions.
136 changes: 46 additions & 90 deletions infra/api/apiClient/ApiClient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ur } from '@faker-js/faker';
import { APIRequestContext, APIResponse } from '@playwright/test';

export enum RequestMethods {
export enum RequestMethod {
GET = 'GET',
POST = 'POST',
PUT = 'PUT',
Expand Down Expand Up @@ -65,7 +66,7 @@ export class ApiClient {
* @param options
* @returns
*/
private async makeRequest<T>(method: RequestMethods, url: string, options?: ApiOptionalParams<T>): Promise<APIResponse | undefined> {
private async makeRequest<T>(method: RequestMethod, url: string, options?: ApiOptionalParams<T>): Promise<APIResponse | undefined> {
let response: APIResponse | undefined
let headers: Record<string, string> = {
'Accept': '*/*'
Expand Down Expand Up @@ -99,20 +100,41 @@ export class ApiClient {
}


// private async paginateBy<T>(paginationType: PaginationType, options?: ApiOptionalParams<T>): Promise<{ [key: string]: any }> {
// let existingQueryParams = { ...options?.queryParams }
// let newParams = {}
// switch (paginationType) {
// case PaginationType.PAGE_PAGINATION:
// newParams = { ...existingQueryParams, 'page': options?.pageNumber }
// break;
// case PaginationType.OFFSET_PAGINATION:
// newParams = { ...existingQueryParams, 'limit': options?.limit, 'offset': options?.offset }
// break;
// }
// return newParams;
// }
private async paginateBy<T>(method: RequestMethod, url: string, paginationType: PaginationType, options?: ApiOptionalParams<T>) {
let response: APIResponse | undefined;
let responses: APIResponse[] = [];
let queryParams = options?.queryParams ? { ...options.queryParams } : {};

while (true) {
if (paginationType === PaginationType.PAGE_PAGINATION && options?.pageNumber !== undefined) {
queryParams = { ...queryParams, 'page': options.pageNumber };
} else if (paginationType === PaginationType.OFFSET_PAGINATION && options?.limit !== undefined && options.offset !== undefined) {
queryParams = { ...queryParams, 'limit': options.limit, 'offset': options.offset };
}
response = await this.makeRequest(method, url, { ...options, queryParams });
let responseObj = await response?.json();

if (!responseObj || responseObj.length === 0) {
break;
}
if (options?.responseKey) {
let responseKey = responseObj[options.responseKey];
if (responseKey.length === 0) {
break;
}
await this.handleResponseObject(responses, responseKey);
} else {
await this.handleResponseObject(responses, responseObj);
}
if (paginationType === PaginationType.PAGE_PAGINATION && options?.pageNumber !== undefined) {
options.pageNumber++;
} else if (paginationType === PaginationType.OFFSET_PAGINATION && options?.offset !== undefined && options.limit !== undefined) {
options.offset += options.limit;
}
}

return responses;
}
/**
* @description handle the response object by spreading it to an existing array if the response is already an array otherwise push directly
* to the array.
Expand All @@ -126,104 +148,38 @@ export class ApiClient {
}
}

public async paginateRequest<T>(method: RequestMethods, url: string, pagintionType: PaginationType, options: ApiOptionalParams<T>): Promise<APIResponse[] | undefined> {
let response: APIResponse | undefined
let responses: APIResponse[] = []
let existingQueryParams = { ...options.queryParams }
try {
while (true) {
response = await this.makeRequest(method, url, options);
let responseObj = await response?.json();
if (!responseObj || responseObj.length === 0) {
break;
}
if (options?.responseKey) {
let responseKey = responseObj[options.responseKey]
if (responseKey.length === 0) {
break;
}
await this.handleResponseObject(responseKey, responses);

} else {
await this.handleResponseObject(responseObj, responses);
}
switch (pagintionType) {
case PaginationType.PAGE_PAGINATION:
if (options.pageNumber !== undefined) {
existingQueryParams['page'] = options.pageNumber
options.pageNumber++

}
break;
case PaginationType.OFFSET_PAGINATION:
if (options.offset !== undefined && options.limit !== undefined) {
existingQueryParams['limit'] = options.limit
existingQueryParams['offset'] = options.offset
options.offset += options.limit;
}
break;
}
}
return responses;
} catch (error) {
throw new Error(`something went wrong in one of the paginateRequest function conditions - please refer to paginateRequest function `)
}
}

// private incrementPaginationParams<T>(paginationType: PaginationType, options: ApiOptionalParams<T>) {
// switch (paginationType) {
// case PaginationType.PAGE_PAGINATION:
// if (options.pageNumber !== undefined) {
// options.pageNumber++;
// }
// break;
// case PaginationType.OFFSET_PAGINATION:
// if (options.offset !== undefined && options.limit !== undefined) {
// options.offset += options.limit;
// }
// break;
// }
// }

public async paginateHttpRequest<T>(method: RequestMethods, url: string, paginationType: PaginationType, options?: ApiOptionalParams<T>) {
if (options?.paginateRequest) {
let responses = await this.paginateRequest(method, url, options.paginationType!, options);
if (responses === undefined) {
throw new Error('the response object is udnefined in the paginateHttpRequest ');
}
return responses;
} else {
throw new Error('pagination options may not have been provided in the makePaginatedHttpRequest');
}
public async paginateRequest<T>(method: RequestMethod, url: string, pagintionType: PaginationType, options: ApiOptionalParams<T>) {
let response = await this.paginateBy(method, url, pagintionType, options);
return response;
}

private async makeHttpRequest<T>(method: RequestMethods, url: string, options?: ApiOptionalParams<T>) {
private async makeHttpRequest<T>(method: RequestMethod, url: string, options?: ApiOptionalParams<T>) {
let response = await this.makeRequest(method, url, options)
return response;
}

public async get<T>(url: string, options?: ApiOptionalParams<T>) {
let response = await this.makeHttpRequest(RequestMethods.GET, url, options)
let response = await this.makeHttpRequest(RequestMethod.GET, url, options)
return response;
}

public async post<T>(url: string, options?: ApiOptionalParams<T>) {
let response = await this.makeHttpRequest(RequestMethods.POST, url, options)
let response = await this.makeHttpRequest(RequestMethod.POST, url, options)
return response;
}

public async put<T>(url: string, options?: ApiOptionalParams<T>) {
let response = await this.makeHttpRequest(RequestMethods.PUT, url, options)
let response = await this.makeHttpRequest(RequestMethod.PUT, url, options)
return response;
}

public async patch<T>(url: string, options?: ApiOptionalParams<T>) {
let response = await this.makeHttpRequest(RequestMethods.PATCH, url, options)
let response = await this.makeHttpRequest(RequestMethod.PATCH, url, options)
return response;
}

public async delete<T>(url: string, options?: ApiOptionalParams<T>) {
let response = await this.makeHttpRequest(RequestMethods.DELETE, url, options)
let response = await this.makeHttpRequest(RequestMethod.DELETE, url, options)
return response;
}
}
4 changes: 2 additions & 2 deletions infra/api/entities/gorestapi/Users.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { APIResponse } from "@playwright/test";
import { ApiClient, PaginationType, RequestMethods } from "../../apiClient/ApiClient";
import { ApiClient, PaginationType, RequestMethod } from "../../apiClient/ApiClient";
import Randomizer from "../../helpers/faker/Randomizer";
import { ApplicationUrl } from "../../helpers/urls/ApplicationUrl";

Expand Down Expand Up @@ -96,7 +96,7 @@ export class Users extends ApiClient {
* @returns
*/
public async getAllUsers(page: number) {
let response = await this.paginateHttpRequest(RequestMethods.GET, this.usersEnpoint, PaginationType.PAGE_PAGINATION, { paginateRequest: true, pagePagination: true, pageNumber: page })
let response = await this.paginateRequest(RequestMethod.GET, this.usersEnpoint, PaginationType.PAGE_PAGINATION, { paginateRequest: true, pagePagination: true, pageNumber: page })
return response;
}

Expand Down
5 changes: 2 additions & 3 deletions infra/api/entities/petStore/PetStoreCrudActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class PetStoreCrudActions extends ApiClient {
}

public async createNewPet<T>(petData: { [key: string]: T }) {
let response = await this.post(this.petStorePetEndpoint, petData)
let response = await this.post(this.petStorePetEndpoint, { requestData: petData })
return response;
}

Expand All @@ -39,13 +39,12 @@ export class PetStoreCrudActions extends ApiClient {
}

public async updatePet<T>(updatedData: { [key: string]: T }) {
let response = await this.put(this.petStorePetEndpoint, updatedData)
let response = await this.put(this.petStorePetEndpoint, { requestData: updatedData })
return response;
}

public async deletePet(petId: number) {
let response = await this.delete(`${this.petStorePetEndpoint}/${petId}`)
return response;
}

}
4 changes: 2 additions & 2 deletions infra/api/entities/pokemon/PokemonApi.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { APIRequestContext, APIResponse, expect } from "@playwright/test";
import { ApiClient, PaginationType, RequestMethods, StatusCode } from "../../apiClient/ApiClient";
import { ApiClient, PaginationType, RequestMethod, StatusCode } from "../../apiClient/ApiClient";
import { ApplicationUrl } from "../../helpers/urls/ApplicationUrl";

export class PokemonApi extends ApiClient {
Expand All @@ -15,7 +15,7 @@ export class PokemonApi extends ApiClient {
* @description get all pokemon recourses by using pagination - you can choose via page or limit and offset pagination mechanism
*/
public async getAllPokemonRecourses(limit: number, offset: number) {
let responses = await this.paginateHttpRequest(RequestMethods.GET, this.POKEMON_ENDPOINT, PaginationType.OFFSET_PAGINATION, { paginateRequest: true, limit: limit, offset: offset, responseKey: 'results' })
let responses = await this.paginateRequest(RequestMethod.GET, this.POKEMON_ENDPOINT, PaginationType.OFFSET_PAGINATION, { limitOffsetPagination: true, limit: limit, offset: offset, responseKey: 'results' })
return responses;
}
}
9 changes: 0 additions & 9 deletions tests/api_tests/goRestApi/GoRestApiTests.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,6 @@ test.describe('Api tests for GoRestApi endpoints', async () => {
users = new Users(request);
})


test.skip('get all users', { tag: ['@GO_REST_API'] }, async () => {
await test.step('get all users from all pages from users endpoint', async () => {
let res = await users.getAllUsers(pageNumber)
expect(res.every(res => res.status())).toBe(StatusCode.OK)
})
})


test('sanity check', { tag: ['@GO_REST_API'] }, async () => {
await test.step('get users endpoint - validate status, body type of obejct properties and default length of the response', async () => {
let response = await users.getUsers();
Expand Down
2 changes: 1 addition & 1 deletion tests/api_tests/petStore/PetStoreCrudTests.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ test.describe.serial('CRUD API tests for the Pet Store API', async () => {
let response = await petStoreCrudActions.getPet(id)
let responseJson: Ipet = await response?.json()
expect(response?.status()).toBe(StatusCode.OK)
expect(responseJson.name).toBe('doggie')
expect(responseJson.name).toBe('ZAP')
})
})

Expand Down

0 comments on commit d0195aa

Please sign in to comment.