lin-mizar
Version:
The core library of Lin CMS
42 lines (41 loc) • 1.12 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.json = void 0;
const utils_1 = require("../utils");
const exception_1 = require("../exception");
const lodash_1 = require("lodash");
/**
* json序列化扩展
*
* ```js
* ctx.json({ message: "hello from lin!" })
* ```
*
* @param app app实例
*/
exports.json = (app) => {
/**
* hide 表示想要隐藏的属性
*/
app.context.json = function (obj, hide = []) {
this.type = 'application/json';
utils_1.unsets(obj, hide);
let data = Object.create(null);
if (obj instanceof exception_1.HttpException) {
transform(obj, data);
lodash_1.set(data, 'request', `${this.method} ${this.req.url}`);
this.status = obj.status;
}
else {
data = obj;
}
this.body = JSON.stringify(data);
};
};
// 驼峰转换下划线
function transform(obj, data) {
const fields = lodash_1.get(obj, 'fields', []);
fields.forEach(field => {
data[utils_1.toLine(field)] = lodash_1.get(obj, field);
});
}