-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
118 lines (107 loc) · 2.8 KB
/
client.ts
File metadata and controls
118 lines (107 loc) · 2.8 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import { Method, Route } from "./types";
const API_URL = (port: number | string = 8000) => `http://localhost:${port}`;
const ADMIN_PATH = "/_routes";
global.fetch = require("node-fetch");
export default class Api {
baseUrl: string;
adminPath: string;
addedRoutes: Route[];
current: Route;
constructor(port?: number | string) {
this.baseUrl = API_URL(port);
this.adminPath = ADMIN_PATH;
this.addedRoutes = [];
this.current = {};
}
nock(path: string) {
this.current.path = path;
return this;
}
method(method: Method) {
this.current.method = method;
return this;
}
status(status: number) {
if (this.current?.response) {
this.current.response.status = status;
} else {
this.current.response = { status };
}
return this;
}
async send(response: any) {
if (response) {
if (this.current?.response) {
this.current.response.body = response;
} else {
this.current.response = { body: response, status: 200 };
}
}
const res = await this._addRoute(this.current);
const { method, path } = this.current;
this.current = {};
if (!res.error) {
const getStats = () => this._getStats(method!, path!);
return {
getStats,
getCount: async () => {
const stats = await getStats();
return stats.count;
},
getStubRequests: async () => {
const stats = await getStats();
return stats.stubRequests;
},
deleteRoute: () => {
return this._handleRoutes({ method, path }, "delete");
},
};
}
return res;
}
async _getStats(method: Method, path: string) {
const response = await fetch(
`${this.baseUrl + this.adminPath}?method=${method}&path=${path}`,
{
method: "GET",
}
);
return response.json();
}
async _handleRoutes(data: any, method: Method) {
const response = await fetch(this.baseUrl + this.adminPath, {
method: method.toLowerCase(),
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
return response.json();
}
async _addRoute(routeData: any) {
if (!routeData) {
return { error: "Data not provided" };
}
try {
const { method, path } = routeData;
const response = await this._handleRoutes(routeData, "post");
this.addedRoutes.push({ method, path });
return response;
} catch (e) {
return { error: e.message };
}
}
async finishTest() {
try {
const response = await fetch(`${this.baseUrl + this.adminPath}/all`, {
method: "DELETE",
});
return await response.json();
} catch (e) {
return { error: e.message };
}
}
_removeQuery(route: string) {
return route.split("?")[0];
}
}