Skip to content

Commit

Permalink
feat(RequestHandler): make class method arguments an object (#1761)
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Oct 6, 2023
1 parent e1e4bb3 commit eca6a9e
Show file tree
Hide file tree
Showing 9 changed files with 232 additions and 168 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,14 @@ export function createFallbackRequestListener(
options,
context.emitter,
{
onMockedResponse(_, { handler, parsedRequest }) {
onMockedResponse(_, { handler, parsedResult }) {
if (!options.quiet) {
context.emitter.once('response:mocked', ({ response }) => {
handler.log(requestCloneForLogs, response, parsedRequest)
handler.log({
request: requestCloneForLogs,
response,
parsedResult,
})
})
}
},
Expand Down
8 changes: 6 additions & 2 deletions src/browser/setupWorker/start/createRequestListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const createRequestListener = (
onPassthroughResponse() {
messageChannel.postMessage('NOT_FOUND')
},
async onMockedResponse(response, { handler, parsedRequest }) {
async onMockedResponse(response, { handler, parsedResult }) {
// Clone the mocked response so its body could be read
// to buffer to be sent to the worker and also in the
// ".log()" method of the request handler.
Expand All @@ -62,7 +62,11 @@ export const createRequestListener = (

if (!options.quiet) {
context.emitter.once('response:mocked', ({ response }) => {
handler.log(requestCloneForLogs, response, parsedRequest)
handler.log({
request: requestCloneForLogs,
response,
parsedResult,
})
})
}
},
Expand Down
77 changes: 53 additions & 24 deletions src/core/handlers/GraphQLHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ describe('parse', () => {
query: GET_USER,
})

expect(await handler.parse(request)).toEqual({
expect(await handler.parse({ request })).toEqual({
operationType: 'query',
operationName: 'GetUser',
query: GET_USER,
Expand All @@ -181,7 +181,7 @@ describe('parse', () => {
},
})

expect(await handler.parse(request)).toEqual({
expect(await handler.parse({ request })).toEqual({
operationType: 'query',
operationName: 'GetUser',
query: GET_USER,
Expand All @@ -202,7 +202,7 @@ describe('parse', () => {
query: GET_USER,
})

expect(await handler.parse(request)).toEqual({
expect(await handler.parse({ request })).toEqual({
operationType: 'query',
operationName: 'GetUser',
query: GET_USER,
Expand All @@ -224,7 +224,7 @@ describe('parse', () => {
},
})

expect(await handler.parse(request)).toEqual({
expect(await handler.parse({ request })).toEqual({
operationType: 'query',
operationName: 'GetUser',
query: GET_USER,
Expand All @@ -247,7 +247,7 @@ describe('parse', () => {
query: LOGIN,
})

expect(await handler.parse(request)).toEqual({
expect(await handler.parse({ request })).toEqual({
operationType: 'mutation',
operationName: 'Login',
query: LOGIN,
Expand All @@ -269,7 +269,7 @@ describe('parse', () => {
},
})

expect(await handler.parse(request)).toEqual({
expect(await handler.parse({ request })).toEqual({
operationType: 'mutation',
operationName: 'Login',
query: LOGIN,
Expand All @@ -290,7 +290,7 @@ describe('parse', () => {
query: LOGIN,
})

expect(await handler.parse(request)).toEqual({
expect(await handler.parse({ request })).toEqual({
operationType: 'mutation',
operationName: 'Login',
query: LOGIN,
Expand All @@ -312,7 +312,7 @@ describe('parse', () => {
},
})

expect(await handler.parse(request)).toEqual({
expect(await handler.parse({ request })).toEqual({
operationType: 'mutation',
operationName: 'Login',
query: LOGIN,
Expand All @@ -339,9 +339,17 @@ describe('predicate', () => {
query: LOGIN,
})

expect(handler.predicate(request, await handler.parse(request))).toBe(true)
expect(
handler.predicate(alienRequest, await handler.parse(alienRequest)),
handler.predicate({
request,
parsedResult: await handler.parse({ request }),
}),
).toBe(true)
expect(
handler.predicate({
request: alienRequest,
parsedResult: await handler.parse({ request: alienRequest }),
}),
).toBe(false)
})

Expand All @@ -365,9 +373,17 @@ describe('predicate', () => {
`,
})

expect(handler.predicate(request, await handler.parse(request))).toBe(true)
expect(
handler.predicate(alienRequest, await handler.parse(alienRequest)),
handler.predicate({
request,
parsedResult: await handler.parse({ request }),
}),
).toBe(true)
expect(
handler.predicate({
request: alienRequest,
parsedResult: await handler.parse({ request: alienRequest }),
}),
).toBe(false)
})

Expand All @@ -384,7 +400,12 @@ describe('predicate', () => {
`,
})

expect(handler.predicate(request, await handler.parse(request))).toBe(true)
expect(
handler.predicate({
request,
parsedResult: await handler.parse({ request }),
}),
).toBe(true)
})

test('respects custom endpoint', async () => {
Expand All @@ -404,9 +425,17 @@ describe('predicate', () => {
query: GET_USER,
})

expect(handler.predicate(request, await handler.parse(request))).toBe(true)
expect(
handler.predicate(alienRequest, await handler.parse(alienRequest)),
handler.predicate({
request,
parsedResult: await handler.parse({ request }),
}),
).toBe(true)
expect(
handler.predicate({
request: alienRequest,
parsedResult: await handler.parse({ request: alienRequest }),
}),
).toBe(false)
})
})
Expand All @@ -426,8 +455,8 @@ describe('test', () => {
query: LOGIN,
})

expect(await handler.test(request)).toBe(true)
expect(await handler.test(alienRequest)).toBe(false)
expect(await handler.test({ request })).toBe(true)
expect(await handler.test({ request: alienRequest })).toBe(false)
})

test('respects operation name', async () => {
Expand All @@ -450,8 +479,8 @@ describe('test', () => {
`,
})

expect(await handler.test(request)).toBe(true)
expect(await handler.test(alienRequest)).toBe(false)
expect(await handler.test({ request })).toBe(true)
expect(await handler.test({ request: alienRequest })).toBe(false)
})

test('respects custom endpoint', async () => {
Expand All @@ -471,8 +500,8 @@ describe('test', () => {
query: GET_USER,
})

expect(await handler.test(request)).toBe(true)
expect(await handler.test(alienRequest)).toBe(false)
expect(await handler.test({ request })).toBe(true)
expect(await handler.test({ request: alienRequest })).toBe(false)
})
})

Expand All @@ -490,7 +519,7 @@ describe('run', () => {
userId: 'abc-123',
},
})
const result = await handler.run(request)
const result = await handler.run({ request })

expect(result!.handler).toEqual(handler)
expect(result!.parsedResult).toEqual({
Expand Down Expand Up @@ -524,7 +553,7 @@ describe('run', () => {
const request = createPostGraphQLRequest({
query: LOGIN,
})
const result = await handler.run(request)
const result = await handler.run({ request })

expect(result).toBeNull()
})
Expand Down Expand Up @@ -571,7 +600,7 @@ describe('request', () => {
`,
})

await handler.run(request)
await handler.run({ request })

expect(matchAllResolver).toHaveBeenCalledTimes(1)
expect(matchAllResolver.mock.calls[0][0]).toHaveProperty(
Expand Down
59 changes: 31 additions & 28 deletions src/core/handlers/GraphQLHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,37 +114,40 @@ export class GraphQLHandler extends RequestHandler<
this.endpoint = endpoint
}

async parse(request: Request) {
return parseGraphQLRequest(request).catch((error) => {
async parse(args: { request: Request }) {
return parseGraphQLRequest(args.request).catch((error) => {
console.error(error)
return undefined
})
}

predicate(request: Request, parsedResult: ParsedGraphQLRequest) {
if (!parsedResult) {
predicate(args: { request: Request; parsedResult: ParsedGraphQLRequest }) {
if (!args.parsedResult) {
return false
}

if (!parsedResult.operationName && this.info.operationType !== 'all') {
const publicUrl = getPublicUrlFromRequest(request)
if (!args.parsedResult.operationName && this.info.operationType !== 'all') {
const publicUrl = getPublicUrlFromRequest(args.request)

devUtils.warn(`\
Failed to intercept a GraphQL request at "${request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
Failed to intercept a GraphQL request at "${args.request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
Consider naming this operation or using "graphql.operation()" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/operation`)
return false
}

const hasMatchingUrl = matchRequestUrl(new URL(request.url), this.endpoint)
const hasMatchingUrl = matchRequestUrl(
new URL(args.request.url),
this.endpoint,
)
const hasMatchingOperationType =
this.info.operationType === 'all' ||
parsedResult.operationType === this.info.operationType
args.parsedResult.operationType === this.info.operationType

const hasMatchingOperationName =
this.info.operationName instanceof RegExp
? this.info.operationName.test(parsedResult.operationName || '')
: parsedResult.operationName === this.info.operationName
? this.info.operationName.test(args.parsedResult.operationName || '')
: args.parsedResult.operationName === this.info.operationName

return (
hasMatchingUrl.matches &&
Expand All @@ -153,28 +156,28 @@ Consider naming this operation or using "graphql.operation()" request handler to
)
}

protected extendInfo(
_request: Request,
parsedResult: ParsedGraphQLRequest<GraphQLVariables>,
) {
protected extendResolverArgs(args: {
request: Request
parsedResult: ParsedGraphQLRequest<GraphQLVariables>
}) {
return {
query: parsedResult?.query || '',
operationName: parsedResult?.operationName || '',
variables: parsedResult?.variables || {},
query: args.parsedResult?.query || '',
operationName: args.parsedResult?.operationName || '',
variables: args.parsedResult?.variables || {},
}
}

async log(
request: Request,
response: Response,
parsedRequest: ParsedGraphQLRequest,
) {
const loggedRequest = await serializeRequest(request)
const loggedResponse = await serializeResponse(response)
async log(args: {
request: Request
response: Response
parsedResult: ParsedGraphQLRequest
}) {
const loggedRequest = await serializeRequest(args.request)
const loggedResponse = await serializeResponse(args.response)
const statusColor = getStatusCodeColor(loggedResponse.status)
const requestInfo = parsedRequest?.operationName
? `${parsedRequest?.operationType} ${parsedRequest?.operationName}`
: `anonymous ${parsedRequest?.operationType}`
const requestInfo = args.parsedResult?.operationName
? `${args.parsedResult?.operationType} ${args.parsedResult?.operationName}`
: `anonymous ${args.parsedResult?.operationType}`

console.groupCollapsed(
devUtils.formatMessage('%s %s (%c%s%c)'),
Expand Down
Loading

0 comments on commit eca6a9e

Please sign in to comment.