Skip to content

Commit

Permalink
api optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
sadabnepal committed Jul 16, 2023
1 parent b67b3a5 commit 6124058
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 38 deletions.
22 changes: 12 additions & 10 deletions test/helper/apiUtils.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,36 @@
import axios from 'axios';
import supertest from 'supertest';
import { URL } from '../env/manager';
import { apiOptions } from '../types/custom';
import { logRequest, logResponse } from './logger';

export const callGraphQlAPIUsingSuperTest = async (url: string, schema: any, logs?: { logRequest?: boolean, logResponse?: boolean, mochaContext?: Mocha.Context }) => {
const request = supertest(url);
const gqlData = { query: schema };
export const callGraphQlAPIUsingSuperTest = async (options: apiOptions) => {
const request = supertest(URL);
const gqlData = { query: options.schema };

if (logs?.logRequest) logRequest(url, schema, logs?.mochaContext);
if (options?.logRequest && options?.mochaContext) logRequest(URL, options.schema, options?.mochaContext);

const response = await request
.post("")
.send(gqlData)
.disableTLSCerts();

if (logs?.logResponse) logResponse(response.statusCode, response.body, logs?.mochaContext)
if (options?.logResponse && options?.mochaContext) logResponse(response.statusCode, response.body, options?.mochaContext)
return response;
}

export const callGraphQlAPIUsingAxios = async (url: string, schema: any, logs?: { logRequest?: boolean, logResponse?: boolean, mochaContext?: Mocha.Context }) => {
if (logs?.logRequest) logRequest(url, schema, logs?.mochaContext);
export const callGraphQlAPIUsingAxios = async (options: apiOptions) => {
if (options?.logRequest && options?.mochaContext) logRequest(URL, options.schema, options?.mochaContext);

let config = {
method: 'post',
maxBodyLength: Infinity,
url: url,
url: URL,
headers: { 'Content-Type': 'application/json' },
data: { query: schema }
data: { query: options.schema }
};
const response = await axios.request(config);

if (logs?.logResponse) logResponse(response.status, response.data, logs?.mochaContext)
if (options?.logResponse && options?.mochaContext) logResponse(response.status, response.data, options?.mochaContext)
return response;
}
2 changes: 1 addition & 1 deletion test/payload/mutation.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CustomerDetailsType } from '../types/customer';
import { CustomerDetailsType } from '../types/custom';

export const registerCustomerAccount = (customer: CustomerDetailsType) => {
return `mutation {
Expand Down
31 changes: 25 additions & 6 deletions test/specs/axios.spec.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,46 @@
import { faker } from '@faker-js/faker';
import { expect } from 'chai';
import { URL } from '../env/manager';
import { callGraphQlAPIUsingAxios } from '../helper/apiUtils';
import { getProductsWithFragment } from '../payload/fragments';
import { registerCustomerAccount } from '../payload/mutation';
import { getProductByName, getProducts } from '../payload/queries';
import { CustomerDetailsType } from '../types/customer';
import { CustomerDetailsType } from '../types/custom';

describe('test graphql api using axios', () => {

describe('query data', function () {
it('should fetch all products', async function () {
const response = await callGraphQlAPIUsingAxios(URL, getProducts, { logRequest: true, logResponse: true, mochaContext: this });
const response = await callGraphQlAPIUsingAxios({
schema: getProducts,
logRequest: true,
logResponse: true,
mochaContext: this
});

expect(response.status).equal(200);
expect(response.data.data.products.items).to.have.length.greaterThan(0);
});

it('should fetch all products using fragments', async function () {
const response = await callGraphQlAPIUsingAxios(URL, getProductsWithFragment, { logRequest: true, logResponse: true, mochaContext: this });
const response = await callGraphQlAPIUsingAxios({
schema: getProductsWithFragment,
logRequest: true,
logResponse: true,
mochaContext: this
});

expect(response.status).equal(200);
expect(response.data.data.products.items).to.have.length.greaterThan(0);
});

it('should fetch products by name', async function () {
let productName = "Laptop";
const response = await callGraphQlAPIUsingAxios(URL, getProductByName(productName), { logRequest: true, logResponse: true, mochaContext: this });
const response = await callGraphQlAPIUsingAxios({
schema: getProductByName(productName),
logRequest: true,
logResponse: true,
mochaContext: this
});

expect(response.status).equal(200)
expect(response.data.data.products.items).to.have.length(1)
Expand All @@ -48,7 +62,12 @@ describe('test graphql api using axios', () => {
password: faker.internet.password()
}

const response = await callGraphQlAPIUsingAxios(URL, registerCustomerAccount(customerData), { logRequest: true, logResponse: true, mochaContext: this });
const response = await callGraphQlAPIUsingAxios({
schema: registerCustomerAccount(customerData),
logRequest: true,
logResponse: true,
mochaContext: this
});

expect(response.status).equal(200);
expect(response.data.data.registerCustomerAccount.success).equal(true)
Expand Down
31 changes: 25 additions & 6 deletions test/specs/supertest.spec.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,48 @@
import { faker } from '@faker-js/faker';
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { URL } from '../env/manager';
import { callGraphQlAPIUsingSuperTest } from '../helper/apiUtils';
import { getProductsWithFragment } from '../payload/fragments';
import { registerCustomerAccount } from '../payload/mutation';
import { getProductByName, getProducts } from '../payload/queries';
import { CustomerDetailsType } from '../types/customer';
import { CustomerDetailsType } from '../types/custom';

describe('test graphql api using supertest', function () {

describe('query data', function () {

it('should fetch all products', async function () {
const response = await callGraphQlAPIUsingSuperTest(URL, getProducts, { logRequest: true, logResponse: true, mochaContext: this });
const response = await callGraphQlAPIUsingSuperTest({
schema: getProducts,
logRequest: true,
logResponse: true,
mochaContext: this
});

expect(response.statusCode).equal(200);
expect(response.body.data.products.items).to.have.length.greaterThan(0);
});

it('should fetch all products using fragments', async function () {
const response = await callGraphQlAPIUsingSuperTest(URL, getProductsWithFragment, { logRequest: true, logResponse: true, mochaContext: this });
const response = await callGraphQlAPIUsingSuperTest({
schema: getProductsWithFragment,
logRequest: true,
logResponse: true,
mochaContext: this
});

expect(response.statusCode).equal(200);
expect(response.body.data.products.items).to.have.length.greaterThan(0);
});

it('should fetch product using query parameter', async function () {
const productName = "Laptop";
const response = await callGraphQlAPIUsingSuperTest(URL, getProductByName(productName), { logRequest: true, logResponse: true, mochaContext: this });
const response = await callGraphQlAPIUsingSuperTest({
schema: getProductByName(productName),
logRequest: true,
logResponse: true,
mochaContext: this
});

expect(response.statusCode).equal(200);
expect(response.body.data.products.items).to.have.length(1);
Expand All @@ -53,7 +67,12 @@ describe('test graphql api using supertest', function () {
password: faker.internet.password()
}

const response = await callGraphQlAPIUsingSuperTest(URL, registerCustomerAccount(customerData), { logRequest: true, logResponse: true, mochaContext: this });
const response = await callGraphQlAPIUsingSuperTest({
schema: registerCustomerAccount(customerData),
logRequest: true,
logResponse: true,
mochaContext: this
});

expect(response.statusCode).equal(200);
expect(response.body.data.registerCustomerAccount.success).equal(true)
Expand Down
7 changes: 7 additions & 0 deletions test/types/customer.d.ts → test/types/custom.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,11 @@ export type CustomerDetailsType = {
lastName?: string,
phoneNumber?: string,
password?: string
}

export type apiOptions = {
schema: string,
logRequest?: boolean,
logResponse?: boolean,
mochaContext?: Mocha.Context
}
22 changes: 7 additions & 15 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */

/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */

/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
Expand All @@ -23,9 +21,8 @@
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */

/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
Expand All @@ -42,12 +39,10 @@
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
Expand All @@ -72,17 +67,15 @@
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */

"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
Expand All @@ -101,9 +94,8 @@
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */

/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
}

0 comments on commit 6124058

Please sign in to comment.