erest
Version:
Easy to build api server depend on @leizm/web and express.
96 lines (95 loc) • 3.24 kB
JavaScript
"use strict";
/**
* @file API Test
* @author Yourtion Guo <yourtion@gmail.com>
*/
Object.defineProperty(exports, "__esModule", { value: true });
const node_assert_1 = require("node:assert");
const agent_1 = require("../agent");
const debug_1 = require("../debug");
const utils_1 = require("../utils");
class IAPITest {
erest;
info;
app;
testPath;
supertest;
constructor(erestIns, path) {
this.erest = erestIns;
const { info, app } = this.erest.privateInfo;
this.info = info;
this.app = app;
this.testPath = path;
this.supertest = require("supertest");
}
get get() {
return this.buildTest("get");
}
get post() {
return this.buildTest("post");
}
get put() {
return this.buildTest("put");
}
get delete() {
return this.buildTest("delete");
}
get patch() {
return this.buildTest("patch");
}
/** 创建测试会话 */
session() {
(0, node_assert_1.strict)(this.app, "请先调用 setApp() 设置 app 实例");
(0, node_assert_1.strict)(this.supertest, "请先安装 supertest");
const agent = this.supertest.agent(this.app);
const buildSession = (method) => {
return (path) => {
const s = this.findApi(method, path);
if (!s || !s.key)
throw new Error(`尝试请求未注册的API:${method} ${path}`);
const a = new agent_1.TestAgent(method, path, s.key, s.options.sourceFile, this.erest);
a.setAgent(agent[method](path));
return a.agent();
};
};
return {
$agent: agent,
get: buildSession("get"),
post: buildSession("post"),
put: buildSession("put"),
delete: buildSession("delete"),
patch: buildSession("patch"),
};
}
/** 根据请求方法和请求路径查找对应的API */
findApi(method, path) {
// 如果定义了 API 的 basePath,需要在测试时替换掉
const routerPath = this.info.basePath ? path.replace(this.info.basePath, "") : path;
const key = (0, utils_1.getSchemaKey)(method, routerPath);
(0, debug_1.test)(method, path, key);
// 检查path无变量情况
if (this.erest.api.$apis.get(key)) {
return this.erest.api.$apis.get(key);
}
// 检查path有变量情况
for (const s of this.erest.api.$apis.values()) {
if (s.pathTest(method, routerPath))
return s;
}
return;
}
/** 生成测试方法 */
buildTest(method) {
return (path) => {
const s = this.findApi(method, path);
if (!s || !s.key) {
throw new Error(`尝试请求未注册的API:${method} ${path}`);
}
const a = new agent_1.TestAgent(method, path, s.key, (0, utils_1.getCallerSourceLine)(this.testPath), this.erest);
(0, node_assert_1.strict)(this.app, "请先调用 setApp() 设置 app 实例");
a.initAgent(this.app);
return a.agent();
};
}
}
exports.default = IAPITest;