Skip to content

Commit

Permalink
Merge pull request #1 from GuildEducationInc/fix_my_js_mess
Browse files Browse the repository at this point in the history
Fix my js mess
  • Loading branch information
mjcastan89 authored Mar 23, 2023
2 parents b758c60 + 3ea2b55 commit e5f1817
Show file tree
Hide file tree
Showing 3 changed files with 128 additions and 87 deletions.
70 changes: 38 additions & 32 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,42 +20,48 @@ The graph-ql-client can be used as a node module. You would need to have the cor

A basic program that creates the client would look like the following:
```js
const compareGraphQlQueryResponse = require('@guildeducationinc/graph-ql-client')
import { GraphQlClient } from '@guildeducationinc/graphql-response-analysis';
class TestFailure extends Error {}

module.exports.run = async () => {
const query = `
mutation GenerateYearEndReport{
funding_generateYearEndReport(
input: {
employerId: "6637b2af-eceb-4de9-8789-82e5b8b36200",
type: EMPLOYEE,
start: "2021-01-01",
end: "2021-12-31",
}
) {
reportUrl
let client = GraphQlClient(
hostIp=<hostIp>,
clientId=<clientId>,
clientSecret=<clientSecret>,
audience=<audience>,
auth0Domain=<auth0Domain>,
publicKey=<publicKey>
)
const query = `
mutation GenerateYearEndReport{
funding_generateYearEndReport(
input: {
employerId: "6637b2af-eceb-4de9-8789-82e5b8b36200",
type: EMPLOYEE,
start: "2021-01-01",
end: "2021-12-31",
}
) {
reportUrl
}
`;
const expectedResponse = `
{
"funding_generateYearEndReport": {
"reportUrl": "[{\\"guildUuid\\":\\"2b52c459-ad19-4518-abf5-94ab165e6703\\",\\"externalId\\":\\"7yznm8p4y\\",\\"firstName\\":\\"Joseph\\",\\"lastName\\":\\"Patton\\",\\"roles\\":[\\"learner\\"],\\"archivedUserFound\\":false,\\"archivedUserIds\\":[],\\"userEmployers\\":[{\\"primary\\":true,\\"dependent\\":false,\\"entityId\\":null,\\"employeeId\\":\\"0216145\\",\\"verifiedOn\\":\\"2018-12-11T02:09:19Z\\",\\"employerUuid\\":\\"e7ae4770-6cf4-45c3-b489-697d7bf0eb2c\\"}],\\"userInstitutions\\":[{\\"studentId\\":\\"21257481\\",\\"verifiedOn\\":\\"2020-08-27T22:59:41Z\\",\\"institutionUuid\\":\\"f677f57f-5070-4edd-942b-a5140b96e4d4\\"}],\\"contactStrategies\\":[{\\"value\\":\\"+14582265608\\",\\"contactType\\":1},{\\"value\\":\\"jpatton323@gmail.com\\",\\"contactType\\":0}]},{\\"guildUuid\\":\\"7029083f-f162-45d7-80b1-93fd20a6f931\\",\\"externalId\\":\\"dywn74rdg\\",\\"firstName\\":\\"Fae\\",\\"lastName\\":\\"Dagonese\\",\\"roles\\":[\\"learner\\"],\\"archivedUserFound\\":false,\\"archivedUserIds\\":[],\\"userEmployers\\":[{\\"primary\\":true,\\"dependent\\":false,\\"entityId\\":null,\\"employeeId\\":\\"heyfae\\",\\"verifiedOn\\":\\"2020-04-03T13:25:01Z\\",\\"employerUuid\\":\\"177b508a-0ec5-4a12-89bb-ebf85e037b4f\\"},{\\"primary\\":true,\\"dependent\\":false,\\"entityId\\":null,\\"employeeId\\":\\"faesotherid\\",\\"verifiedOn\\":\\"2020-04-03T13:25:42Z\\",\\"employerUuid\\":\\"72b56457-4324-4ca3-89d3-a280f332f826\\"}],\\"userInstitutions\\":[{\\"studentId\\":\\"anotherstudentid\\",\\"verifiedOn\\":\\"2021-03-12T20:27:41Z\\",\\"institutionUuid\\":\\"e7ae4770-6cf4-45c3-b489-697d7bf0eb2c\\"}],\\"contactStrategies\\":null}]"
}
}
`;
let responseCompare;
try {
responseCompare = await compareGraphQlQueryResponse(query, expectedResponse)
} catch (error) {
throw new TestFailure(`generateYearEndReport raised the following error: ${error}.`)
}
if (responseCompare) {
return `generateYearEndReport Succeeded.`;
}
else {
throw new TestFailure(`Expected query response does not match expected response; generateYearEndReport Failed.`);
}
`;
const expectedResponse = `
{
"funding_generateYearEndReport": {
"reportUrl": "[{\\"guildUuid\\":\\"2b52c459-ad19-4518-abf5-94ab165e6703\\",\\"externalId\\":\\"7yznm8p4y\\",\\"firstName\\":\\"Joseph\\",\\"lastName\\":\\"Patton\\",\\"roles\\":[\\"learner\\"],\\"archivedUserFound\\":false,\\"archivedUserIds\\":[],\\"userEmployers\\":[{\\"primary\\":true,\\"dependent\\":false,\\"entityId\\":null,\\"employeeId\\":\\"0216145\\",\\"verifiedOn\\":\\"2018-12-11T02:09:19Z\\",\\"employerUuid\\":\\"e7ae4770-6cf4-45c3-b489-697d7bf0eb2c\\"}],\\"userInstitutions\\":[{\\"studentId\\":\\"21257481\\",\\"verifiedOn\\":\\"2020-08-27T22:59:41Z\\",\\"institutionUuid\\":\\"f677f57f-5070-4edd-942b-a5140b96e4d4\\"}],\\"contactStrategies\\":[{\\"value\\":\\"+14582265608\\",\\"contactType\\":1},{\\"value\\":\\"jpatton323@gmail.com\\",\\"contactType\\":0}]},{\\"guildUuid\\":\\"7029083f-f162-45d7-80b1-93fd20a6f931\\",\\"externalId\\":\\"dywn74rdg\\",\\"firstName\\":\\"Fae\\",\\"lastName\\":\\"Dagonese\\",\\"roles\\":[\\"learner\\"],\\"archivedUserFound\\":false,\\"archivedUserIds\\":[],\\"userEmployers\\":[{\\"primary\\":true,\\"dependent\\":false,\\"entityId\\":null,\\"employeeId\\":\\"heyfae\\",\\"verifiedOn\\":\\"2020-04-03T13:25:01Z\\",\\"employerUuid\\":\\"177b508a-0ec5-4a12-89bb-ebf85e037b4f\\"},{\\"primary\\":true,\\"dependent\\":false,\\"entityId\\":null,\\"employeeId\\":\\"faesotherid\\",\\"verifiedOn\\":\\"2020-04-03T13:25:42Z\\",\\"employerUuid\\":\\"72b56457-4324-4ca3-89d3-a280f332f826\\"}],\\"userInstitutions\\":[{\\"studentId\\":\\"anotherstudentid\\",\\"verifiedOn\\":\\"2021-03-12T20:27:41Z\\",\\"institutionUuid\\":\\"e7ae4770-6cf4-45c3-b489-697d7bf0eb2c\\"}],\\"contactStrategies\\":null}]"
}
}
`;
let responseCompare;
try {
responseCompare = await client.compareResponse(query, expectedResponse)
} catch (error) {
throw new TestFailure(`generateYearEndReport raised the following error: ${error}.`)
}
if (responseCompare) {
return `generateYearEndReport Succeeded.`;
}
else {
throw new TestFailure(`Expected query response does not match expected response; generateYearEndReport Failed.`);
}
```
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@guildeducationinc/graphql-response-analysis",
"version": "1.0.4",
"version": "1.0.5",
"description": "A module to facilitate a graphQL connection, making queries and processing the responses.",
"homepage": "https://github.com/guildeducationinc/graph-ql-client#readme",
"repository": {
Expand Down
143 changes: 89 additions & 54 deletions src/graphQlClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,68 +4,103 @@ const { FALSE, TRUE } = require('pg-format/lib/reserved');

class GraphqlError extends Error {}

class GraphQlClient {
constructor(authStrategy, host) {
this.authStrategy = authStrategy;
this.host = host;
// class GraphQlClient {
// constructor(authStrategy, host) {
// this.authStrategy = authStrategy;
// this.host = host;
// }

// async request(query) {
// const token = await this.authStrategy.requestToken();
// let response;
// try {
// const response = await fetch(this.host, {
// method: 'POST',
// headers: { 'Content-Type': 'application/json', Authorization: token },
// body: JSON.stringify({ query }),
// });
// } catch (error) {
// throw new GraphqlError(`Error integrating with Graphql Api: ${error}.`);
// }
// const responseBody = await response.json();
// if (!response.ok || containsErrors(responseBody))
// throw new GraphqlError(
// `Error in response from Graphql. Status: ${response.status}, body: ${JSON.stringify(
// responseBody
// )}`
// );
// return responseBody.data;
// }
// }

// function containsErrors(responseBody) {
// if (responseBody.errors !== undefined) if (responseBody.errors.length > 0) return true;
// return false;
// }

export class GraphQlClient {
constructor(hostIp, clientId, clientSecret, audience, auth0Domain, publicKey) {
this.host = hostIp;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.audience = audience;
this.auth0Client = auth0Domain;
this.publicKey = publicKey;
this.auth0Client = new AutoRefreshOnExpireAuth0Client(
{ clientId, clientSecret, audience, domain, publicKey },
fetch
);
this.client = new GraphQlClient(auth0Client, host);
}

async request(query) {
const token = await this.authStrategy.requestToken();
let response;
async query(query) {
try {
const response = await fetch(this.host, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: token },
body: JSON.stringify({ query }),
});
const response = this.client.request(query);
} catch (error) {
throw new GraphqlError(`Error integrating with Graphql Api: ${error}.`);
console.log('Query request failed.');
throw error;
}
const responseBody = await response.json();
if (!response.ok || containsErrors(responseBody))
throw new GraphqlError(
`Error in response from Graphql. Status: ${response.status}, body: ${JSON.stringify(
responseBody
)}`
);
return responseBody.data;
return response;
}
}

function containsErrors(responseBody) {
if (responseBody.errors !== undefined) if (responseBody.errors.length > 0) return true;
return false;
}

function GraphQlQueryReponse(query) {
const host = process.env.APPSYNC_HOST;
const clientId = process.env.FUNDING_ADMIN_CLIENT_ID;
const clientSecret = process.env.FUNDING_ADMIN_CLIENT_SECRET;
const audience = process.env.FUNDING_AUDIENCE;
const domain = process.env.AUTH0_DOMAIN;
const publicKey = process.env.AUTH0_GUILD_JWT_PEM;
const auth0Client = new AutoRefreshOnExpireAuth0Client(
{ clientId, clientSecret, audience, domain, publicKey },
fetch
);
const client = new GraphQlClient(auth0Client, host);
try {
const response = client.request(query);
} catch (error) {
console.log('Query request failed.');
throw error;
async compareResponse(query, expectedResponse) {
const expectedResponseJson = JSON.parse(expectedResponse);
const response = await this.client.query(query);
if (JSON.stringify(response) != JSON.stringify(expectedResponseJson)) {
return FALSE;
}
return TRUE;
}
return response;
}

async function compareGraphQlQueryResponse(query, expectedResponse) {
const expectedResponseJson = JSON.parse(expectedResponse);
const response = await GraphQlQueryReponse(query);
if (JSON.stringify(response) != JSON.stringify(expectedResponseJson)) {
return FALSE;
}
return TRUE;
}
// function GraphQlQueryReponse(query) {
// const host = process.env.APPSYNC_HOST;
// const clientId = process.env.FUNDING_ADMIN_CLIENT_ID;
// const clientSecret = process.env.FUNDING_ADMIN_CLIENT_SECRET;
// const audience = process.env.FUNDING_AUDIENCE;
// const domain = process.env.AUTH0_DOMAIN;
// const publicKey = process.env.AUTH0_GUILD_JWT_PEM;
// const auth0Client = new AutoRefreshOnExpireAuth0Client(
// { clientId, clientSecret, audience, domain, publicKey },
// fetch
// );
// const client = new GraphQlClient(auth0Client, host);
// try {
// const response = client.request(query);
// } catch (error) {
// console.log('Query request failed.');
// throw error;
// }
// return response;
// }

// async function compareGraphQlQueryResponse(query, expectedResponse) {
// const expectedResponseJson = JSON.parse(expectedResponse);
// const response = await GraphQlQueryReponse(query);
// if (JSON.stringify(response) != JSON.stringify(expectedResponseJson)) {
// return FALSE;
// }
// return TRUE;
// }

module.exports = { GraphQlClient, GraphQlQueryReponse, compareGraphQlQueryResponse };
// module.exports = { GraphQlClient, GraphQlQueryReponse, compareGraphQlQueryResponse };

0 comments on commit e5f1817

Please sign in to comment.