Skip to content

Commit

Permalink
WIP Re-designs the RequestHandler API
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Jan 27, 2021
1 parent b15ba73 commit 663d96c
Show file tree
Hide file tree
Showing 15 changed files with 425 additions and 165 deletions.
14 changes: 0 additions & 14 deletions src/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,20 +286,6 @@ function graphQLRequestHandler<QueryType, VariablesType = Record<string, any>>(
console.log('Response:', loggedResponse)
console.groupEnd()
},

getMetaInfo() {
const header =
expectedOperationType === 'all'
? `[graphql] ${expectedOperationType} (origin: ${mask.toString()})`
: `[graphql] ${expectedOperationType} ${expectedOperationName} (origin: ${mask.toString()})`

return {
type: 'graphql',
header,
mask,
callFrame,
}
},
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,13 @@ export {
defaultContext,
MockedRequest,
RequestHandler,
RequestHandlerMetaInfo,
RequestParams,
RequestQuery,
ResponseResolver,
ResponseResolverReturnType,
AsyncResponseResolverReturnType,
} from './utils/handlers/requestHandler'
export {
rest,
restContext,
RestContext,
RESTMethods,
Expand All @@ -47,3 +45,5 @@ export { matchRequestUrl } from './utils/matching/matchRequestUrl'
/* Utils */
export { compose } from './utils/internal/compose'
export { DelayMode } from './context/delay'

export { rest } from './utils/handlers/2.0/rest'
16 changes: 7 additions & 9 deletions src/node/createSetupServer.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import * as cookieUtils from 'cookie'
import { bold } from 'chalk'
import * as cookieUtils from 'cookie'
import { Headers, flattenHeadersObject } from 'headers-utils'
import { StrictEventEmitter } from 'strict-event-emitter'
import {
RequestInterceptor,
MockedResponse as MockedInterceptedResponse,
Interceptor,
} from 'node-request-interceptor'
import { RequestHandlersList } from '../setupWorker/glossary'
import { RequestApplicator, RequestHandlersList } from '../setupWorker/glossary'
import { MockedRequest } from '../utils/handlers/requestHandler'
import { getResponse } from '../utils/getResponse'
import { parseBody } from '../utils/request/parseBody'
Expand All @@ -17,7 +17,6 @@ import { onUnhandledRequest } from '../utils/request/onUnhandledRequest'
import { ServerLifecycleEventsMap, SetupServerApi } from './glossary'
import { SharedOptions } from '../sharedOptions'
import { uuidv4 } from '../utils/internal/uuidv4'
import { request } from 'express'

const DEFAULT_LISTEN_OPTIONS: SharedOptions = {
onUnhandledRequest: 'bypass',
Expand All @@ -31,7 +30,7 @@ export function createSetupServer(...interceptors: Interceptor[]) {
const emitter = new StrictEventEmitter<ServerLifecycleEventsMap>()

return function setupServer(
...requestHandlers: RequestHandlersList
...requestHandlers: RequestApplicator[]
): SetupServerApi {
requestHandlers.forEach((handler) => {
if (Array.isArray(handler))
Expand All @@ -50,7 +49,7 @@ export function createSetupServer(...interceptors: Interceptor[]) {

// Store the list of request handlers for the current server instance,
// so it could be modified at a runtime.
let currentHandlers: RequestHandlersList = [...requestHandlers]
let currentHandlers: RequestApplicator[] = [...requestHandlers]

interceptor.on('response', (req, res) => {
const requestId = req.headers?.['x-msw-request-id'] as string
Expand Down Expand Up @@ -91,7 +90,6 @@ export function createSetupServer(...interceptors: Interceptor[]) {
body: parseBody(req.body, requestHeaders),
headers: requestHeaders,
cookies: {},
params: {},
redirect: 'manual',
referrer: '',
keepalive: false,
Expand Down Expand Up @@ -176,11 +174,11 @@ export function createSetupServer(...interceptors: Interceptor[]) {

printHandlers() {
currentHandlers.forEach((handler) => {
const meta = handler.getMetaInfo()
const { header, callFrame } = handler.info

console.log(`\
${bold(meta.header)}
Declaration: ${meta.callFrame}
${bold(header)}
Declaration: ${callFrame}
`)
})
},
Expand Down
6 changes: 3 additions & 3 deletions src/node/glossary.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { MockedResponse as MockedInterceptedResponse } from 'node-request-interceptor'
import { SharedOptions } from '../sharedOptions'
import { RequestHandlersList } from '../setupWorker/glossary'
import { RequestApplicator } from '../setupWorker/glossary'
import { MockedRequest } from '../utils/handlers/requestHandler'

export interface ServerLifecycleEventsMap {
Expand Down Expand Up @@ -29,7 +29,7 @@ export interface SetupServerApi {
* Prepends given request handlers to the list of existing handlers.
* @see {@link https://mswjs.io/docs/api/setup-server/use `server.use()`}
*/
use(...handlers: RequestHandlersList): void
use(...handlers: RequestApplicator[]): void

/**
* Marks all request handlers that respond using `res.once()` as unused.
Expand All @@ -41,7 +41,7 @@ export interface SetupServerApi {
* Resets request handlers to the initial list given to the `setupServer` call, or to the explicit next request handlers list, if given.
* @see {@link https://mswjs.io/docs/api/setup-server/reset-handlers `server.reset-handlers()`}
*/
resetHandlers(...nextHandlers: RequestHandlersList): void
resetHandlers(...nextHandlers: RequestApplicator[]): void

/**
* Lists all active request handlers.
Expand Down
14 changes: 3 additions & 11 deletions src/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,12 @@ const createRestHandler = (method: RESTMethods) => {
>(
mask: Mask,
resolver: ResponseResolver<
MockedRequest<RequestBodyType, RequestParamsType>,
MockedRequest<RequestBodyType>,
typeof restContext,
ResponseBodyType
>,
): RequestHandler<
MockedRequest<RequestBodyType, RequestParamsType>,
MockedRequest<RequestBodyType>,
typeof restContext,
ParsedRestRequest,
MockedRequest<RequestBodyType>,
Expand Down Expand Up @@ -112,6 +112,7 @@ const createRestHandler = (method: RESTMethods) => {
params,
}
},

resolver,

defineContext() {
Expand Down Expand Up @@ -165,15 +166,6 @@ ${queryParams
console.log('Response', loggedResponse)
console.groupEnd()
},

getMetaInfo() {
return {
type: 'rest',
header: `[rest] ${method} ${mask.toString()}`,
mask,
callFrame,
}
},
}
}
}
Expand Down
8 changes: 5 additions & 3 deletions src/setupWorker/glossary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { SharedOptions } from '../sharedOptions'
import { ServiceWorkerMessage } from '../utils/createBroadcastChannel'
import { createStart } from './start/createStart'
import { createStop } from './stop/createStop'
import { RequestHandler as RequestHandlerClass } from '../utils/handlers/2.0/RequestHandler'

export type Mask = RegExp | string
export type ResolvedMask = Mask | URL
Expand Down Expand Up @@ -92,7 +93,7 @@ export interface SetupWorkerInternalContext {
startOptions: StartOptions | undefined
worker: ServiceWorker | null
registration: ServiceWorkerRegistration | null
requestHandlers: RequestHandler<any, any>[]
requestHandlers: RequestApplicator[]
emitter: StrictEventEmitter<WorkerLifecycleEventsMap>
keepAliveInterval?: number
workerChannel: {
Expand Down Expand Up @@ -176,6 +177,7 @@ export type StartOptions = SharedOptions & {
findWorker?: FindWorker
}

export type RequestApplicator = RequestHandlerClass
export type RequestHandlersList = RequestHandler<any, any, any, any, any>[]

export type ResponseWithSerializedHeaders<BodyType = any> = Omit<
Expand Down Expand Up @@ -203,7 +205,7 @@ export interface SetupWorkerApi {
* @param {RequestHandler[]} handlers List of runtime request handlers.
* @see {@link https://mswjs.io/docs/api/setup-worker/use `worker.use()`}
*/
use: (...handlers: RequestHandlersList) => void
use: (...handlers: RequestApplicator[]) => void

/**
* Marks all request handlers that respond using `res.once()` as unused.
Expand All @@ -216,7 +218,7 @@ export interface SetupWorkerApi {
* @param {RequestHandler[]} nextHandlers List of the new initial request handlers.
* @see {@link https://mswjs.io/docs/api/setup-worker/reset-handlers `worker.resetHandlers()`}
*/
resetHandlers: (...nextHandlers: RequestHandlersList) => void
resetHandlers: (...nextHandlers: RequestApplicator[]) => void

/**
* Lists all active request handlers.
Expand Down
27 changes: 19 additions & 8 deletions src/setupWorker/setupWorker.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { StrictEventEmitter } from 'strict-event-emitter'
import {
SetupWorkerInternalContext,
RequestHandlersList,
SetupWorkerApi,
ServiceWorkerIncomingEventsMap,
RequestApplicator,
} from './glossary'
import { createStart } from './start/createStart'
import { createStop } from './stop/createStop'
import * as requestHandlerUtils from '../utils/handlers/requestHandlerUtils'
import { isNodeProcess } from '../utils/internal/isNodeProcess'
import { ServiceWorkerMessage } from '../utils/createBroadcastChannel'
import { jsonParse } from '../utils/internal/jsonParse'
import { RestHandler } from '../utils/handlers/2.0/RestHandler'

interface Listener {
target: EventTarget
Expand All @@ -29,7 +30,7 @@ let listeners: Listener[] = []
* @see {@link https://mswjs.io/docs/api/setup-worker `setupWorker`}
*/
export function setupWorker(
...requestHandlers: RequestHandlersList
...requestHandlers: RequestApplicator[]
): SetupWorkerApi {
requestHandlers.forEach((handler) => {
if (Array.isArray(handler))
Expand Down Expand Up @@ -143,6 +144,7 @@ export function setupWorker(
stop: createStop(context),

use(...handlers) {
console.log('adding new handlers', handlers)
requestHandlerUtils.use(context.requestHandlers, ...handlers)
},

Expand All @@ -159,14 +161,23 @@ export function setupWorker(

printHandlers() {
context.requestHandlers.forEach((handler) => {
const meta = handler.getMetaInfo()
const { header, callFrame } = handler.info

console.groupCollapsed(meta.header)
console.log(`Declaration: ${meta.callFrame}`)
console.log('Resolver: %s', handler.resolver)
if (['rest'].includes(meta.type)) {
console.log('Match:', `https://mswjs.io/repl?path=${meta.mask}`)
console.groupCollapsed(header)

if (callFrame) {
console.log(`Declaration: ${callFrame}`)
}

console.log('Handler:', handler)

if (handler instanceof RestHandler) {
console.log(
'Match:',
`https://mswjs.io/repl?path=${handler.info.mask}`,
)
}

console.groupEnd()
})
},
Expand Down
Loading

0 comments on commit 663d96c

Please sign in to comment.