-
Notifications
You must be signed in to change notification settings - Fork 76
/
APICloud-rest.js
237 lines (227 loc) · 8.63 KB
/
APICloud-rest.js
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
'use strict';
function copy(obj) {
if (obj == null || typeof (obj) != 'object')
return obj;
var temp = obj.constructor();
// changed
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
temp[key] = copy(obj[key]);
}
}
return temp;
}
function isType(type) {
return function (obj) {
return {}.toString.call(obj) == "[object " + type + "]"
}
}
var isFunction = isType("Function");
function Resource(appId, appKey, baseurl) {
var now = Date.now();
this.appId = appId;
this.baseurl = baseurl || "https://d.apicloud.com/mcm/api";
this.appCode = SHA1(appId + "UZ" + appKey + "UZ" + now) + "." + now;
this.defaultactions = {
'get': {method: 'GET',params: ["_id", "_relation"]}, //_relationid 后续支持
'save': {method: 'POST',params: ["_id", "_relation"]}, //_relationid 后续支持
'query': {method: 'GET',params: ["filter"]},
'delete': {method: 'DELETE',params: ["_id", "_relation"]}, //_relationid 后续支持
'login': {method: "POST",params: ["username", "passwordd"]},
'logout': {method: "POST"},
'count': {method: "GET",params: ["_id", "_relation","filter"]},
'exists': {method: "GET",params: ["_id"]},
'findOne': {method: 'GET',params: ["filter"]},
'verify': {method: "POST",params: ["email", "language", "username"],alias: "verifyEmail"},
'reset': {method: "POST",params: ["email", "language", "username"],alias: "resetRequest"}
};
this.headers={};
this.setHeaders("X-APICloud-AppId",this.appId);
this.setHeaders("X-APICloud-AppKey",this.appCode);
this.setHeaders("Content-Type","application/json;");
}
Resource.prototype.setHeaders=function(key,value){
this.headers[key]=value;
}
Resource.prototype.upload = function (modelName,isFilter, filepath, params, callback) {
if (typeof params == "function") {
callback = params;
params = {};
}
var url=params["_id"]&¶ms["_relation"]?("/"+modelName+"/"+params["_id"]+"/"+params["_relation"]):"/file";
var isPut=(!params["_relation"])&¶ms["_id"];
var fileUrl = this.baseurl + url + ( isPut ? ("/" + params["_id"]) : "");
var filename = filepath.substr(filepath.lastIndexOf("/") + 1, filepath.length);
var ajaxConfig={
url: fileUrl,
method: isPut ? "PUT" : "POST",
data: {
values: {
filename: filename
},
files: {
file: filepath
}
}
}
ajaxConfig["headers"] = {};
for(var header in this.headers){
ajaxConfig["headers"][header]=this.headers[header];
}
api.ajax(ajaxConfig, function (ret, err) {
if (ret && ret.id && !err) {
var newobj = {};
if (isFilter) {
newobj["id"] = ret["id"];
newobj["name"] = ret["name"];
newobj["url"] = ret["url"];
callback(null, newobj)
} else {
callback(null, ret);
}
} else {
callback(ret || err, null)
}
});
}
Resource.prototype.Factory = function (modelName) {
var self = this;
var route = new Route(modelName, self.baseurl);
var actions = copy(this.defaultactions);
var resourceFactory = new Object();
Object.keys(actions).forEach(function (name) {
if (modelName != "user" && ["login", "logout", "verify", "reset"].indexOf(name) != -1){ return;}
resourceFactory[name] = function (a1, a2, a3) {
var action = copy(actions[name]);
var params = {}, data, callback;
var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);
switch (arguments.length) {
case 3:
params = a1;
data = a2;
callback = a3;
break;
case 2:
if (hasBody)
data = a1;
else
params = a1;
callback = a2;
break;
case 1:
if (isFunction(a1))
callback = a1;
else if (hasBody)
data = a1;
else
params = a1;
break;
case 0:
break;
default:
throw new Error("参数最多为3个");
}
if (hasBody&&name != "logout") {
var fileCount = 0;
Object.keys(data).forEach(function (key) {
var item = data[key];
if (item && item.isFile) {
var isFilter = true;
if (modelName == "file"||item.isFileClass) {
isFilter = false;
}
fileCount++;
self.upload(modelName,isFilter, item.path, params, function (err, returnData) {
if (err) {
return callback(null, err);
} else {
if (!isFilter)
return callback(returnData, null);
data[key] = returnData;
fileCount--;
if (fileCount == 0) {
next();
}
}
})
}
});
if (fileCount == 0) {
next();
}
} else {
next();
}
function next() {
var httpConfig = {};
httpConfig["headers"] = {};
for(var header in self.headers){
httpConfig["headers"][header]=self.headers[header];
}
if (name === "logout"&&!httpConfig["headers"]["authorization"]) {
return callback({status:0,msg:"未设置authorization参数,无法注销!"}, null);
}
if (hasBody) {
httpConfig.data = {
body: JSON.stringify(data)
};
}
if (params && (name == "save") && params["_id"] && (!params["_relation"]) && (!params["_relationid"])) {
action.method = "PUT";
}
if (params && (name == "save") && params["_id"] && params["_relation"] && params["_relationid"]) {
action.method = "PUT";
}
for (var key in action) {
if (key != 'params' && key != "alias") {
httpConfig[key] = copy(action[key]);
}
}
var curparams = {};
action.params = action.params || [];
for (var k = 0, len = action.params.length; k < len; k++) {
var tempkey = action.params[k];
if (params[tempkey]) {
curparams[tempkey] = copy(params[tempkey]);
}
}
if (["login", "logout", "count", "exists", "verify", "reset", "findOne"].indexOf(name) != -1) {
curparams["_custom"] = action.alias || name;
}
route.setUrlParams(httpConfig, curparams);
console.log(httpConfig.method + "\t" + httpConfig.url);
api.ajax(httpConfig, function (ret, err) {
return callback(ret, err);
})
}
};
});
return resourceFactory;
};
function Route(template, baseurl) {
this.template = template;
this.baseurl = baseurl;
}
Route.prototype = {
setUrlParams: function (config, params) {
var url = "/:_class/:_id/:_relation/:_custom/:_relationid";
url = url.replace(":_class", this.template);
var parArr = [];
Object.keys(params).forEach(function (ckey) {
if (ckey.charAt(0) == '_') {
url = url.replace(":" + ckey, params[ckey]);
delete params[ckey];
} else {
if (ckey == "filter") {
parArr.push(ckey + "=" + JSON.stringify(params[ckey]));
}
}
});
url = url.replace(/:[^/]+/ig, '/');
if (parArr.length > 0) {
url += ("?" + parArr.join("&"));
}
url = url.replace(/\/+/g, '/');
config.url = this.baseurl + url;
}
};