-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add BaseGraphqlService, support [github] V4 API #3763
Merged
Merged
Changes from 4 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
2aeb24e
add base class for Graphql APIs
chris48s 063da6a
add GithubAuthV4Service + updates to GH token pool
chris48s 160569e
update github forks to use GithubAuthV4Service
chris48s 08c7d5d
rename GithubAuthService to GithubAuthV3Service
chris48s ab9ec5f
change function names
chris48s 2c19bb2
create new objects instead of modifying in-place
chris48s 9940d9a
use gql template strings
chris48s 2256db6
graphqlErrorHandler --> transformErrors
chris48s be8b655
add a comment about V3 vs V4 tradeoff
chris48s b4b5bf6
move parseJson out to a shared helper
chris48s ba974b0
Merge branch 'master' into base-graphql
chris48s File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
'use strict' | ||
|
||
const { parse } = require('graphql') | ||
const BaseJsonService = require('./base-json') | ||
const { InvalidResponse } = require('./errors') | ||
|
||
function defaultGraphqlErrorHandler(errors) { | ||
throw new InvalidResponse({ prettyMessage: errors[0].message }) | ||
} | ||
|
||
class BaseGraphqlService extends BaseJsonService { | ||
_validateQuery(query) { | ||
// Attempting to parse the query string | ||
// will throw a descriptive exception if it isn't valid | ||
parse(query) | ||
} | ||
|
||
async _requestGraphql({ | ||
schema, | ||
url, | ||
query, | ||
variables = {}, | ||
options = {}, | ||
httpErrorMessages = {}, | ||
graphqlErrorHandler = defaultGraphqlErrorHandler, | ||
chris48s marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}) { | ||
this._validateQuery(query) | ||
|
||
const mergedOptions = { | ||
...{ headers: { Accept: 'application/json' } }, | ||
...options, | ||
} | ||
mergedOptions.method = 'POST' | ||
mergedOptions.body = JSON.stringify({ query, variables }) | ||
const { buffer } = await this._request({ | ||
url, | ||
options: mergedOptions, | ||
errorMessages: httpErrorMessages, | ||
}) | ||
const json = this._parseJson(buffer) | ||
if (json.errors) { | ||
graphqlErrorHandler(json.errors) | ||
} | ||
return this.constructor._validate(json, schema) | ||
} | ||
} | ||
|
||
module.exports = BaseGraphqlService |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,196 @@ | ||
'use strict' | ||
|
||
const Joi = require('@hapi/joi') | ||
const { expect } = require('chai') | ||
const sinon = require('sinon') | ||
const BaseGraphqlService = require('./base-graphql') | ||
const { InvalidResponse } = require('./errors') | ||
|
||
const dummySchema = Joi.object({ | ||
requiredString: Joi.string().required(), | ||
}).required() | ||
|
||
class DummyGraphqlService extends BaseGraphqlService { | ||
static get category() { | ||
return 'cat' | ||
} | ||
|
||
static get route() { | ||
return { | ||
base: 'foo', | ||
} | ||
} | ||
|
||
async handle() { | ||
const { requiredString } = await this._requestGraphql({ | ||
schema: dummySchema, | ||
url: 'http://example.com/graphql', | ||
query: 'query { requiredString }', | ||
}) | ||
return { message: requiredString } | ||
} | ||
} | ||
|
||
describe('BaseGraphqlService', function() { | ||
describe('Making requests', function() { | ||
let sendAndCacheRequest | ||
beforeEach(function() { | ||
sendAndCacheRequest = sinon.stub().returns( | ||
Promise.resolve({ | ||
buffer: '{"some": "json"}', | ||
res: { statusCode: 200 }, | ||
}) | ||
) | ||
}) | ||
|
||
it('invokes _sendAndCacheRequest', async function() { | ||
await DummyGraphqlService.invoke( | ||
{ sendAndCacheRequest }, | ||
{ handleInternalErrors: false } | ||
) | ||
|
||
expect(sendAndCacheRequest).to.have.been.calledOnceWith( | ||
'http://example.com/graphql', | ||
{ | ||
body: '{"query":"query { requiredString }","variables":{}}', | ||
headers: { Accept: 'application/json' }, | ||
method: 'POST', | ||
} | ||
) | ||
}) | ||
|
||
it('forwards options to _sendAndCacheRequest', async function() { | ||
class WithOptions extends DummyGraphqlService { | ||
async handle() { | ||
const { value } = await this._requestGraphql({ | ||
schema: dummySchema, | ||
url: 'http://example.com/graphql', | ||
query: 'query { requiredString }', | ||
options: { qs: { queryParam: 123 } }, | ||
}) | ||
return { message: value } | ||
} | ||
} | ||
|
||
await WithOptions.invoke( | ||
{ sendAndCacheRequest }, | ||
{ handleInternalErrors: false } | ||
) | ||
|
||
expect(sendAndCacheRequest).to.have.been.calledOnceWith( | ||
'http://example.com/graphql', | ||
{ | ||
body: '{"query":"query { requiredString }","variables":{}}', | ||
headers: { Accept: 'application/json' }, | ||
method: 'POST', | ||
qs: { queryParam: 123 }, | ||
} | ||
) | ||
}) | ||
}) | ||
|
||
describe('Making badges', function() { | ||
it('handles valid json responses', async function() { | ||
const sendAndCacheRequest = async () => ({ | ||
buffer: '{"requiredString": "some-string"}', | ||
res: { statusCode: 200 }, | ||
}) | ||
expect( | ||
await DummyGraphqlService.invoke( | ||
{ sendAndCacheRequest }, | ||
{ handleInternalErrors: false } | ||
) | ||
).to.deep.equal({ | ||
message: 'some-string', | ||
}) | ||
}) | ||
|
||
it('handles json responses which do not match the schema', async function() { | ||
const sendAndCacheRequest = async () => ({ | ||
buffer: '{"unexpectedKey": "some-string"}', | ||
res: { statusCode: 200 }, | ||
}) | ||
expect( | ||
await DummyGraphqlService.invoke( | ||
{ sendAndCacheRequest }, | ||
{ handleInternalErrors: false } | ||
) | ||
).to.deep.equal({ | ||
isError: true, | ||
color: 'lightgray', | ||
message: 'invalid response data', | ||
}) | ||
}) | ||
|
||
it('handles unparseable json responses', async function() { | ||
const sendAndCacheRequest = async () => ({ | ||
buffer: 'not json', | ||
res: { statusCode: 200 }, | ||
}) | ||
expect( | ||
await DummyGraphqlService.invoke( | ||
{ sendAndCacheRequest }, | ||
{ handleInternalErrors: false } | ||
) | ||
).to.deep.equal({ | ||
isError: true, | ||
color: 'lightgray', | ||
message: 'unparseable json response', | ||
}) | ||
}) | ||
}) | ||
|
||
describe('Error handling', function() { | ||
it('handles generic error', async function() { | ||
const sendAndCacheRequest = async () => ({ | ||
buffer: '{ "errors": [ { "message": "oh noes!!" } ] }', | ||
res: { statusCode: 200 }, | ||
}) | ||
expect( | ||
await DummyGraphqlService.invoke( | ||
{ sendAndCacheRequest }, | ||
{ handleInternalErrors: false } | ||
) | ||
).to.deep.equal({ | ||
isError: true, | ||
color: 'lightgray', | ||
message: 'oh noes!!', | ||
}) | ||
}) | ||
|
||
it('handles custom error', async function() { | ||
class WithErrorHandler extends DummyGraphqlService { | ||
async handle() { | ||
const { requiredString } = await this._requestGraphql({ | ||
schema: dummySchema, | ||
url: 'http://example.com/graphql', | ||
query: 'query { requiredString }', | ||
graphqlErrorHandler: function(errors) { | ||
if (errors[0].message === 'oh noes!!') { | ||
throw new InvalidResponse({ | ||
prettyMessage: 'a terrible thing has happened', | ||
}) | ||
} | ||
}, | ||
}) | ||
return { message: requiredString } | ||
} | ||
} | ||
|
||
const sendAndCacheRequest = async () => ({ | ||
buffer: '{ "errors": [ { "message": "oh noes!!" } ] }', | ||
res: { statusCode: 200 }, | ||
}) | ||
expect( | ||
await WithErrorHandler.invoke( | ||
{ sendAndCacheRequest }, | ||
{ handleInternalErrors: false } | ||
) | ||
).to.deep.equal({ | ||
isError: true, | ||
color: 'lightgray', | ||
message: 'a terrible thing has happened', | ||
}) | ||
}) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
'use strict' | ||
/** | ||
* @module | ||
*/ | ||
|
||
const { parse } = require('graphql') | ||
const { print } = require('graphql/language/printer') | ||
|
||
/** | ||
* Utility function to merge two graphql queries together | ||
* This is basically copied from | ||
* [graphql-query-merge](https://www.npmjs.com/package/graphql-query-merge) | ||
* but can't use that due to incorrect packaging. | ||
* | ||
* @param {...string} queries queries to merge | ||
* @returns {string} merged query | ||
*/ | ||
function mergeQueries(...queries) { | ||
chris48s marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const merged = { | ||
kind: 'Document', | ||
definitions: [ | ||
{ | ||
directives: [], | ||
operation: 'query', | ||
variableDefinitions: [], | ||
kind: 'OperationDefinition', | ||
selectionSet: { kind: 'SelectionSet', selections: [] }, | ||
}, | ||
], | ||
} | ||
|
||
queries.forEach(query => { | ||
const parsedQuery = parse(query) | ||
parsedQuery.definitions.forEach(definition => { | ||
merged.definitions[0].directives = [ | ||
...merged.definitions[0].directives, | ||
...definition.directives, | ||
] | ||
|
||
merged.definitions[0].variableDefinitions = [ | ||
...merged.definitions[0].variableDefinitions, | ||
...definition.variableDefinitions, | ||
] | ||
|
||
merged.definitions[0].selectionSet.selections = [ | ||
...merged.definitions[0].selectionSet.selections, | ||
...definition.selectionSet.selections, | ||
] | ||
}) | ||
}) | ||
|
||
return print(merged) | ||
} | ||
|
||
module.exports = { mergeQueries } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
'use strict' | ||
|
||
const { expect } = require('chai') | ||
const { mergeQueries } = require('./graphql') | ||
|
||
require('../register-chai-plugins.spec') | ||
|
||
describe('mergeQueries function', function() { | ||
it('merges valid gql queries', function() { | ||
expect( | ||
mergeQueries('query ($param: String!) { foo(param: $param) { bar } }') | ||
).to.equalIgnoreSpaces( | ||
'query ($param: String!) { foo(param: $param) { bar } }' | ||
) | ||
|
||
expect( | ||
mergeQueries( | ||
'query ($param: String!) { foo(param: $param) { bar } }', | ||
'query { baz }' | ||
) | ||
).to.equalIgnoreSpaces( | ||
'query ($param: String!) { foo(param: $param) { bar } baz }' | ||
) | ||
|
||
expect( | ||
mergeQueries('query { foo }', 'query { bar }', 'query { baz }') | ||
).to.equalIgnoreSpaces('{ foo bar baz }') | ||
|
||
expect(mergeQueries('{ foo }', '{ bar }')).to.equalIgnoreSpaces( | ||
'{ foo bar }' | ||
) | ||
}) | ||
|
||
it('throws an error when passed invalid gql queries', function() { | ||
expect(() => mergeQueries('', '')).to.throw(Error) | ||
expect(() => mergeQueries(undefined, 17, true)).to.throw(Error) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've made
query
andvariables
top-level params here. I'm in 2 minds about whether it makes more sense to collect them into an object. Also note here I deliberately haven't implemented mutations. In general, calling a shields badge should read data from upstream service, not write data to it, so we shouldn't need mutations.