-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathrequest-code.js
More file actions
79 lines (59 loc) · 2.09 KB
/
request-code.js
File metadata and controls
79 lines (59 loc) · 2.09 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
const { joinStrings } = require("../../lib/join-strings");
const { printObject, objectToArray } = require("../../lib/print-object");
function templateRequestCode(props) {
const name = props.name;
const params = templateParams(props);
const body = templateBody(props);
return `export function ${name}(${params}) {${body}}`;
}
function templateParams(props) {
const { isExistParams } = props;
return isExistParams ? "params" : "";
}
function templateBody(props) {
const wariningDeprecated = templateWariningDeprecated(props);
const request = templateRequest(props);
const joinConfig = { before: " ", separator: "\n" };
const body = joinStrings([wariningDeprecated, request], joinConfig);
return lineBreak(body, { before: true, after: true });
}
function templateWariningDeprecated(props) {
const { isWarningDeprecated, name } = props;
if (isWarningDeprecated) {
return `console.warn("Api method '${name}' is deprecated");`;
}
}
function templateRequest(props) {
const args = templateRequestArgs(props);
const params = templateParams(props);
return `return request(${args})(${params});`;
}
function templateRequestArgs(props) {
const method = `"${props.method}"`;
const url = `\`${templateUrl(props)}\``;
const defaultParams = templateDefaultParams(props);
const joinConfig = { separator: ", " };
const args = joinStrings([method, url, defaultParams], joinConfig);
return args;
}
function templateUrl(props) {
if (props.isExistParams) {
return props.url.replace(/\{(.*)\}/g, "${params.path.$1}");
}
return props.url;
}
function templateDefaultParams(props) {
const { defaultParams } = props;
if (defaultParams && typeof defaultParams === "object" && Object.keys(defaultParams).length) {
return printObject(objectToArray(defaultParams), (propValue) =>
printObject(objectToArray(propValue)),
);
}
return "";
}
function lineBreak(value, options = {}) {
const before = options.before ? "\n" : "";
const after = options.before ? "\n" : "";
return value.length ? `${before}${value}${after}` : "";
}
module.exports = { templateRequestCode };