-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRESTful.js
More file actions
103 lines (85 loc) · 2.51 KB
/
Copy pathRESTful.js
File metadata and controls
103 lines (85 loc) · 2.51 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
var mime = require('mime');
//the config object for the RESTful module
var RESTconfig = require('./RESTconfig');
var config = RESTconfig.config;
//return boolean if the url contain an api dir
exports.isRESTcall = function(url){
for (i in config.api){
if (url.search(config.api[i].dir) != -1 ){
return true;
}
}
return false;
}
exports.parseCall = function(response, url, postData){
var dir = '';
var callTemplate = '';
var methodTemplate = '';
var defaultMethod = '';
var objectHome = '';
//determine which api dir is the one to use
for (i in config.api){
if (url.search(config.api[i].dir) != -1 ){
dir = config.api[i].dir;
callTemplate = config.api[i].callTemplate;
methodTemplate = config.api[i].methodTemplate;
defaultMethod = config.api[i].defaultMethod;
objectHome = config.api[i].objectHome;
}
}
//split up the url
var callPath = url.split('/');
//get the file type so we know what to return
var filetype = callPath[callPath.length-1].split('.')[1];
//remove the file type from the call so we can call the function
var uri = url.slice(0,url.length - filetype.length - 1);
//the object we will create out of the template and uri
var object = {}
var fn = '';
//remove the everything before the api path
var callPath = uri.split(dir)[1];
callPath = callPath.split('/');
callPath.shift();
//remove the first (empty) item from the call array
var callOrder = callTemplate.split('/?');
callOrder.shift();
for(index in callOrder){
object[callOrder[index]] = callPath[index];
}
writeHeaderType(response,filetype);
if (typeof(object.method) == 'undefined'){
object.method = defaultMethod;
}
//build the function
fn = 'call.' + object.object + '.' + object.method + '(';
typeof(object.id) != 'undefined' ? fn += object.id: fn += '';
//send any post data through if there is any
if (typeof(postData) != 'undefined' && typeof(object.id) != 'undefined' ) {
fn += ',' + postData;
}
else if (typeof(postData) != 'undefined' && typeof(object.id) == 'undefined' ){
fn += postData;
}
fn += ')';
var call = require(objectHome + object.object + '.js');
obj = eval( fn );
response.write( serializeObject(filetype,obj) );
response.end();
}
function writeHeaderType(response,type){
if (typeof(type) == 'undefined'){
type = 'txt';
}
response.writeHead(200, {'Content-Type': mime.lookup(type)});
}
function serializeObject(type,object){
switch(type.toLowerCase()){
case 'url':
break;
case 'xml':
break;
case 'json':
default:
return JSON.stringify(object);
}
}