rest-chronicle
Version:
autodocumentate rest api
85 lines (84 loc) • 3.05 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _path = _interopRequireDefault(require("path"));
var _fsExtra = _interopRequireDefault(require("fs-extra"));
var _clsHooked = _interopRequireDefault(require("cls-hooked"));
var _uuid = require("uuid");
var _reporters = _interopRequireDefault(require("../reporters"));
var _constants = require("../constants");
var _Action = _interopRequireDefault(require("./Action"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
class Chronicle {
constructor(config = {}) {
_defineProperty(this, "contextBuilder", c => c);
this._actions = [];
this.setConfig(config);
this.id = config.id || (0, _uuid.v4)();
}
useCLS(namespace, contextKey = _constants.DEFAULT_CLS_CONTEXT_KEY) {
this.clsEnabled = true;
this._cls = {
namespace,
contextKey
};
}
getCLSContext() {
const namespace = _clsHooked.default.getNamespace(this._cls.namespace);
return namespace.get(this._cls.contextKey);
}
setContextBuilder(fn) {
this.contextBuilder = fn;
}
setConfig(config) {
this.config = config;
}
action(context) {
return new _Action.default({
context,
chronicle: this
});
}
clear() {
this._actions = [];
this.contextBuilder = c => c;
this.setConfig({});
}
async save(filePath, opts = {}) {
const {
reporter: reporterType = 'json',
...reporterOptions
} = opts;
const Reporter = _reporters.default[reporterType];
await _fsExtra.default.ensureDir(_path.default.dirname(filePath));
const reporter = new Reporter(filePath, reporterOptions);
await reporter.write(this._actions.map(a => a.data));
}
split(splitfn) {
const splitted = new Map();
for (const item of this._actions) {
const chrID = splitfn(item);
const curr = splitted.get(chrID) || [];
curr.push(item);
splitted.set(chrID, curr);
}
return [...splitted.keys()].map(groupId => {
const actions = splitted.get(groupId);
const chronicle = new Chronicle({
...this.config,
id: groupId
});
chronicle.clsEnabled = this.clsEnabled;
chronicle._cls = this._cls;
chronicle.contextBuilder = this.contextBuilder;
for (const action of actions) action.copy(chronicle);
return chronicle;
});
}
}
exports.default = Chronicle;