-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (60 loc) · 1.85 KB
/
index.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
/**
* XadillaX created at 2016-05-13 16:33:09 With ♥
*
* Copyright (c) 2016 Souche.com, all rights
* reserved.
*/
"use strict";
var changeCase = require("change-case");
var _util = require("config.util");
var DEFAULT_OPTIONS = {
output: "underscore"
};
var CUOutputer = function(akyuu, options) {
this.position = akyuu.PLUGIN_POS.BEFORE_CONNECTION;
this.akyuu = akyuu;
this.options = _util.extendDeep({}, DEFAULT_OPTIONS, options);
};
CUOutputer.prototype._transformKey = function(key) {
if(typeof key !== "string") return key;
switch(this.options.output) {
case "underscore": return changeCase.snakeCase(key);
case "lower_camelize": return changeCase.camelCase(key);
case "upper_camelize": return changeCase.pascalCase(key);
case "hyphen": return changeCase.paramCase(key);
default: return changeCase.snakeCase(key);
}
};
CUOutputer.prototype._transform = function(obj) {
if(!obj || typeof obj !== "object") return obj;
if(Array.isArray(obj)) {
var res = [];
for(var i = 0; i < obj.length; i++) {
res.push(this._transform(obj[i]));
}
return res;
}
var res = {};
for(var key in obj) {
if(!obj.hasOwnProperty(key)) continue;
res[this._transformKey(key)] = this._transform(obj[key]);
}
return res;
};
CUOutputer.prototype.plug = function() {
var self = this;
this.akyuu.use(function(req, resp, next) {
// hack resp
var rawSend = resp.send;
resp.send = function() {
if(arguments[0] && typeof arguments[0] === "object") {
arguments[0] = self._transform(arguments[0]);
}
rawSend.apply(resp, arguments);
};
next();
});
};
exports.create = function(akyuu, options) {
return new CUOutputer(akyuu, options);
};