rest-chronicle
Version:
autodocumentate rest api
85 lines (84 loc) • 3.19 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(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
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;