UNPKG

lin-cms-test

Version:

The core library of Lin CMS, this package is just for test!

114 lines (113 loc) 3.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const exception_1 = require("./exception"); const consola_1 = tslib_1.__importDefault(require("consola")); const util_1 = require("./util"); const mixin_1 = require("./mixin"); const lodash_1 = require("lodash"); /** * 将返回的结果json序列化 * @param app app实例 */ exports.json = (app) => { /** * hide 表示想要隐藏的属性 */ app.context.json = function (obj, hide = []) { this.type = "application/json"; util_1.unsets(obj, hide); let data = Object.create(null); if (obj instanceof exception_1.HttpException) { transform1(obj, data); lodash_1.set(data, "url", this.request.url); this.status = obj.code; } else { // data = jsonUnmarshal(obj); // data = transform2(obj); data = obj; } this.body = JSON.stringify(data); }; }; function jsonUnmarshal(obj) { let data = Object.create(null); if (lodash_1.isObject(obj)) { if (obj instanceof mixin_1.JsonMixin) { transform1(obj, data); } else if (lodash_1.isMap(obj)) { obj.forEach((v, k) => { if (lodash_1.isObject(v)) { data[util_1.toLine(k)] = jsonUnmarshal(v); } else { data[util_1.toLine(k)] = v; } }); } else if (lodash_1.isArray(obj)) { obj.forEach(v => { if (lodash_1.isObject(v)) { v = jsonUnmarshal(v); } }); } else { Object.keys(obj).forEach(key => { if (lodash_1.isObject(obj[key])) { data[util_1.toLine(key)] = jsonUnmarshal(obj[key]); } else { data[util_1.toLine(key)] = obj[key]; } }); } } else { data = obj; } return data; } function transform2(obj) { let data; if (lodash_1.isArray(obj)) { data = []; obj.forEach((it, index) => { data[index] = transform2(it); }); } else { data = Object.create(null); const fields = Object.keys(obj); fields.forEach(field => { data[util_1.toLine(field)] = lodash_1.get(obj, field); }); } return data; } function transform1(obj, data) { const fields = lodash_1.get(obj, "fields", []); fields.forEach(field => { data[util_1.toLine(field)] = lodash_1.get(obj, field); }); } function transform(obj, hide, data) { const fields = lodash_1.get(obj, "fields", []); if (lodash_1.isArray(hide) && hide.length > 0) { lodash_1.remove(fields, item => { return lodash_1.findIndex(hide, item) !== -1; }); } fields.forEach(field => { data[util_1.toLine(field)] = lodash_1.get(obj, field); }); } /** * logging扩展 * @param app app实例 */ exports.logging = (app) => { app.context.logger = consola_1.default; };