forked from lgwebdream/fe-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-templates.js
More file actions
82 lines (79 loc) · 2.33 KB
/
code-templates.js
File metadata and controls
82 lines (79 loc) · 2.33 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
/**
* define all the CRUD code templates, the generator name schema is:
* [language]_[requestLib]_[codeStyle], for example, JavaScript_JQuery_CodeSnippet
* the signature of all the generators :
* @param {*} apiInfo
* @param {*} serviceName
* @returns void
* the generated code will be mounted to apiInfo.code which will be assembled later
*/
const { JS, TS, CodeSnippet, Axios, GET } = require('../../constants/concept');
module.exports = {
// JavaScript_Axios_CodeSnippet
[`${JS}_${Axios}_${CodeSnippet}`]: apiInfo => {
const { path, method, name } = apiInfo;
let code;
if (method.toUpperCase() === GET) {
// GET method
code = `function ${name}(params={}){
return axios.request({
url:'${path}',
method:'${method}',
params
}).catch(err=>{
throw new Error(err ? err.message :'服务端错误');
})
}`;
} else {
code = `function ${name}(data={}){
return axios.request({
url:'${path}',
method:'${method}',
data
}).catch(err=>{
throw new Error(err ? err.message :'服务端错误');
})
}`;
}
return {
...apiInfo,
code,
};
},
// TypeScript_Axios_CodeSnippet
[`${TS}_${Axios}_${CodeSnippet}`]: (apiInfo, serviceName) => {
const { path, name, method } = apiInfo;
const apiName = `${serviceName}${name[0].toUpperCase()}${name.slice(1)}API`;
let code;
if (method.toUpperCase() === GET) {
// GET method
code = `
import * as ${apiName} from '@typings/api.${serviceName}.${name}';
function ${name}(params:${apiName}.Request):Promise<${apiName}.Response>{
return axios.request({
url:'${path}',
method:'${method}',
params:params || {}
}).catch(err=>{
throw new Error(err ? err.message :'服务端错误');
})
}`;
} else {
code = `
import * as ${apiName} from '@typings/api.${serviceName}.${name}';
function ${name}(data:${apiName}.Request):Promise<${apiName}.Response>{
axios.request({
url:'${path}',
method:'${method}',
data:data || {}
}).catch(err=>{
throw new Error(err ? err.message :'服务端错误');
})
}`;
}
return {
...apiInfo,
code,
};
},
};