load-api-facade.mjs 1.29 KB
/**
 * @file 在 Node 测试中注入 request spy,加载小程序 API facade;不执行真实网络请求。
 */
import { readFile } from 'node:fs/promises'
import path from 'node:path'

const projectRoot = path.resolve(process.cwd())

/**
 * 加载 API facade,并以 spy 替代 `~/utils/request/request.js`。
 * @param {string} relativePath 仓库内 API 文件路径
 * @param {{post: Function}} requestSpy request facade spy
 * @returns {Promise<object>} API facade
 */
export async function loadApiFacade(relativePath, requestSpy) {
	const absolutePath = path.resolve(projectRoot, relativePath)
	const relativeToRoot = path.relative(projectRoot, absolutePath)
	if (
		relativeToRoot === '..' ||
		relativeToRoot.startsWith(`..${path.sep}`) ||
		path.isAbsolute(relativeToRoot)
	) {
		throw new Error(`API facade must stay inside project: ${relativePath}`)
	}
	const source = await readFile(absolutePath, 'utf8')
	const executable = source
		.replace(/^\s*import\s+api\s+from\s+['"][^'"]+['"];?\s*$/m, '')
		.replace(/export\s+default\s+/, 'const __facade = ')
		.replace(/module\.exports\s*=\s*/, 'const __facade = ')
	if (!executable.includes('const __facade = ')) {
		throw new Error(`Unsupported API facade export: ${relativePath}`)
	}
	return new Function('api', `${executable}\nreturn __facade;`)(requestSpy)
}