|
| 1 | +import type { ResolvedConfig } from '../../config' |
| 2 | +import type { DevEnvironmentContext } from '../environment' |
| 3 | +import { DevEnvironment } from '../environment' |
| 4 | +import type { Environment } from '../../environment' |
| 5 | + |
| 6 | +export interface FetchableDevEnvironmentContext extends DevEnvironmentContext { |
| 7 | + handleRequest(request: Request): Promise<Response> | Response |
| 8 | +} |
| 9 | + |
| 10 | +export function createFetchableDevEnvironment( |
| 11 | + name: string, |
| 12 | + config: ResolvedConfig, |
| 13 | + context: FetchableDevEnvironmentContext, |
| 14 | +): FetchableDevEnvironment { |
| 15 | + if (typeof Request === 'undefined' || typeof Response === 'undefined') { |
| 16 | + throw new TypeError( |
| 17 | + 'FetchableDevEnvironment requires a global `Request` and `Response` object.', |
| 18 | + ) |
| 19 | + } |
| 20 | + |
| 21 | + if (!context.handleRequest) { |
| 22 | + throw new TypeError( |
| 23 | + 'FetchableDevEnvironment requires a `handleRequest` method during initialisation.', |
| 24 | + ) |
| 25 | + } |
| 26 | + |
| 27 | + return new FetchableDevEnvironment(name, config, context) |
| 28 | +} |
| 29 | + |
| 30 | +export function isFetchableDevEnvironment( |
| 31 | + environment: Environment, |
| 32 | +): environment is FetchableDevEnvironment { |
| 33 | + return environment instanceof FetchableDevEnvironment |
| 34 | +} |
| 35 | + |
| 36 | +class FetchableDevEnvironment extends DevEnvironment { |
| 37 | + private _handleRequest: (request: Request) => Promise<Response> | Response |
| 38 | + |
| 39 | + constructor( |
| 40 | + name: string, |
| 41 | + config: ResolvedConfig, |
| 42 | + context: FetchableDevEnvironmentContext, |
| 43 | + ) { |
| 44 | + super(name, config, context) |
| 45 | + this._handleRequest = context.handleRequest |
| 46 | + } |
| 47 | + |
| 48 | + public async dispatchFetch(request: Request): Promise<Response> { |
| 49 | + if (!(request instanceof Request)) { |
| 50 | + throw new TypeError( |
| 51 | + 'FetchableDevEnvironment `dispatchFetch` must receive a `Request` object.', |
| 52 | + ) |
| 53 | + } |
| 54 | + const response = await this._handleRequest(request) |
| 55 | + if (!(response instanceof Response)) { |
| 56 | + throw new TypeError( |
| 57 | + 'FetchableDevEnvironment `context.handleRequest` must return a `Response` object.', |
| 58 | + ) |
| 59 | + } |
| 60 | + return response |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +export type { FetchableDevEnvironment } |
0 commit comments