@liqd-js/mongodb-model
Version:
Mongo model class
91 lines (90 loc) • 3.05 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.GET_PARENT = exports.REGISTER_MODEL = void 0;
exports.flowStart = flowStart;
exports.flowGet = flowGet;
exports.flowSet = flowSet;
exports.flowExecute = flowExecute;
exports.map = map;
exports.LOG = LOG;
exports.hasPublicMethod = hasPublicMethod;
exports.DUMP = DUMP;
exports.LOG_FILE = LOG_FILE;
const mongodb_1 = require("mongodb");
const log_1 = require("./log");
exports.REGISTER_MODEL = Symbol('REGISTER_MODEL');
exports.GET_PARENT = Symbol('GET_PARENT');
const fs = require('fs');
const Flow = require('@liqd-js/flow');
function flowStart(callback, scope) {
Flow.start(callback, scope);
}
function flowGet(key, fallback) {
return Flow.get(key, fallback);
}
function flowSet(key, value) {
Flow.set(key, value);
}
function flowExecute(callback, scope, freeze = true) {
return Flow.execute(callback, scope, freeze);
}
function map(ids, entries, getID) {
const index = new Map(entries.map(e => [idToIndexKey(getID(e)), e]));
return ids.map(id => index.get(idToIndexKey(id)) ?? null);
}
function idToIndexKey(id) {
return id instanceof mongodb_1.ObjectId ? id.toString() : id;
}
const { inspect } = require('util');
function LOG(...args) {
console.log(...args.map(a => typeof a === 'string' ? a : inspect(a, { colors: true, depth: Infinity })));
}
function stringify(value, indentation = '') {
if (typeof value === 'undefined') {
return 'undefined';
}
if (value === null) {
return 'null';
}
if (typeof value === 'number' || typeof value === 'boolean') {
return value.toString();
}
if (typeof value === 'string') {
return JSON.stringify(value);
}
if (Array.isArray(value)) {
const elements = value.map((element) => stringify(element, indentation));
return '[' + elements.join(',') + ']';
}
if (typeof value === 'object') {
if (value instanceof Date) {
return 'ISODate("' + value.toISOString() + '")';
}
if (value instanceof RegExp) {
return value.toString();
}
if (value instanceof mongodb_1.ObjectId) {
return 'ObjectId("' + value.toHexString() + '")';
}
const properties = Object.keys(value).map((key) => {
const val = stringify(value[key], indentation + ' ');
return indentation + '"' + key + '": ' + val;
});
return '{\n' + properties.join(',\n') + '\n' + indentation + '}';
}
return '';
}
function hasPublicMethod(obj, method) {
return obj && method in obj && typeof obj[method] === 'function';
}
function DUMP(obj) {
console.log(stringify(obj));
}
function LOG_FILE(query, separator = false) {
const path = flowGet('experimentalFlags')?.['logQueries'];
const traceID = flowGet('traceID');
if (!path || !traceID) {
return;
}
log_1.Log.append(path + '/' + traceID + '.txt', stringify(query) + (separator ? '\n===============================\n\n' : '\n'));
}
;