File size: 1,263 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import { AsyncLocalStorage } from 'node:async_hooks'
export interface TestReqInfo {
url: string
proxyPort: number
testData: string
}
export interface TestRequestReader<R> {
url(req: R): string
header(req: R, name: string): string | null
}
const testStorage = new AsyncLocalStorage<TestReqInfo>()
function extractTestInfoFromRequest<R>(
req: R,
reader: TestRequestReader<R>
): TestReqInfo | undefined {
const proxyPortHeader = reader.header(req, 'next-test-proxy-port')
if (!proxyPortHeader) {
return undefined
}
const url = reader.url(req)
const proxyPort = Number(proxyPortHeader)
const testData = reader.header(req, 'next-test-data') || ''
return { url, proxyPort, testData }
}
export function withRequest<R, T>(
req: R,
reader: TestRequestReader<R>,
fn: () => T
): T {
const testReqInfo = extractTestInfoFromRequest(req, reader)
if (!testReqInfo) {
return fn()
}
return testStorage.run(testReqInfo, fn)
}
export function getTestReqInfo<R>(
req?: R,
reader?: TestRequestReader<R>
): TestReqInfo | undefined {
const testReqInfo = testStorage.getStore()
if (testReqInfo) {
return testReqInfo
}
if (req && reader) {
return extractTestInfoFromRequest(req, reader)
}
return undefined
}
|