-
Notifications
You must be signed in to change notification settings - Fork 67
/
Curl.service.ts
59 lines (50 loc) 路 1.62 KB
/
Curl.service.ts
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
import {CURLParser} from 'parse-curl-js';
import {ICurlValues, ITriggerService} from 'types/Test.types';
import Validator from 'utils/Validator';
import {HTTP_METHOD} from 'constants/Common.constants';
import HttpRequest from 'models/HttpRequest.model';
interface ICurlTriggerService extends ITriggerService {
getRequestFromCommand(command: string): ICurlValues;
getIsValidCommand(command: string): boolean;
}
const CurlTriggerService = (): ICurlTriggerService => ({
async getRequest(draft) {
const {url, method, auth, headers, body} = draft as ICurlValues;
return HttpRequest({url, method, auth, headers, body});
},
async validateDraft(draft) {
const {url, method} = draft as ICurlValues;
return Validator.required(url) && Validator.required(method);
},
getRequestFromCommand(command) {
const parser = new CURLParser(command);
const {
url = '',
method,
headers = [],
body: {data: body = {}},
} = parser.parse();
return {
url: url.split('')[0] === "'" ? url.slice(1, -1) : url,
auth: undefined,
command,
method: method as HTTP_METHOD,
headers: Object.entries(headers).map(([key, value]) => ({key, value})),
body: body === 'data' ? '' : JSON.stringify(body),
};
},
getIsValidCommand(command) {
try {
const parser = new CURLParser(command);
const {
url = '',
method,
body: {data: body = {}},
} = parser.parse();
return Boolean((method.toUpperCase() === HTTP_METHOD.POST && body) || (url && method));
} catch (e) {
return false;
}
},
});
export default CurlTriggerService();