feat: 3.2.1 release

This commit is contained in:
Shinwoo PARK 2025-03-21 09:40:32 +09:00
parent 3ac9b1d38d
commit 59cd199287
37 changed files with 673 additions and 566 deletions

6
dist/lib/index.d.ts vendored
View File

@ -1,4 +1,4 @@
export { LoggedRoute, LoggedFunction, LoggedController, LoggedInjectable, LoggedGuard, LoggedInterceptor, } from "./logged";
export { ScopedLogger } from "./logger";
export { InjectLogger, LoggedParam, LoggedHeaders, LoggedBody, LoggedQuery, Logged, Returns } from "./reflected";
export { LoggedRoute, LoggedFunction, LoggedController, LoggedInjectable, LoggedGuard, LoggedInterceptor, } from './logged';
export { ScopedLogger } from './logger';
export { InjectLogger, LoggedParam, LoggedHeaders, LoggedBody, LoggedQuery, Logged, Returns, } from './reflected';
export { getRequestLogger } from './utils';

6
dist/lib/internals/nest.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum';
import { ParamData, PipeTransform, Type } from '@nestjs/common';
import { ROUTE_ARGS_METADATA } from '@nestjs/common/constants';
export { RouteParamtypes, PipeTransform, Type, ROUTE_ARGS_METADATA };
export declare function createRouteParamDecorator(paramtype: RouteParamtypes): (data?: ParamData) => ParameterDecorator;
export declare const createPipesRouteParamDecorator: (paramtype: RouteParamtypes) => (data?: any, ...pipes: (Type<PipeTransform> | PipeTransform)[]) => ParameterDecorator;

24
dist/lib/internals/nest.js vendored Normal file
View File

@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPipesRouteParamDecorator = exports.createRouteParamDecorator = exports.ROUTE_ARGS_METADATA = exports.RouteParamtypes = void 0;
const route_paramtypes_enum_1 = require("@nestjs/common/enums/route-paramtypes.enum");
Object.defineProperty(exports, "RouteParamtypes", { enumerable: true, get: function () { return route_paramtypes_enum_1.RouteParamtypes; } });
const common_1 = require("@nestjs/common");
const constants_1 = require("@nestjs/common/constants");
Object.defineProperty(exports, "ROUTE_ARGS_METADATA", { enumerable: true, get: function () { return constants_1.ROUTE_ARGS_METADATA; } });
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
function createRouteParamDecorator(paramtype) {
return (data) => (target, key, index) => {
const args = Reflect.getMetadata(constants_1.ROUTE_ARGS_METADATA, target.constructor, key) || {};
Reflect.defineMetadata(constants_1.ROUTE_ARGS_METADATA, (0, common_1.assignMetadata)(args, paramtype, index, data), target.constructor, key);
};
}
exports.createRouteParamDecorator = createRouteParamDecorator;
const createPipesRouteParamDecorator = (paramtype) => (data, ...pipes) => (target, key, index) => {
const args = Reflect.getMetadata(constants_1.ROUTE_ARGS_METADATA, target.constructor, key) || {};
const hasParamData = (0, shared_utils_1.isNil)(data) || (0, shared_utils_1.isString)(data);
const paramData = hasParamData ? data : undefined;
const paramPipes = hasParamData ? pipes : [data, ...pipes];
Reflect.defineMetadata(constants_1.ROUTE_ARGS_METADATA, (0, common_1.assignMetadata)(args, paramtype, index, paramData, ...paramPipes), target.constructor, key);
};
exports.createPipesRouteParamDecorator = createPipesRouteParamDecorator;

View File

@ -5,12 +5,7 @@ export declare function includeObjectSync(ocv: any, opt: {
export declare function excludeObjectSync(ocv: any, opt: {
paths: string[];
}): any;
export declare function includeOrExcludeObjectSync(ocv: any, paths: string[], currentPath: string[], include: boolean): any;
export declare function objectContainedLoggedSync(ocv: any, options?: {
include?: string[];
exclude: string[];
}): string;
export declare function imObjectContainedLogSync(ocv: any, options?: {
export declare function objectContainedLogSync(ocv: any, options?: {
include?: string[];
exclude?: string[];
}): string;

View File

@ -1,7 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getItemByPathSync = exports.imObjectContainedLogSync = exports.objectContainedLoggedSync = exports.includeOrExcludeObjectSync = exports.excludeObjectSync = exports.includeObjectSync = exports.notIncludedSymbol = void 0;
exports.notIncludedSymbol = Symbol("notIncluded");
exports.getItemByPathSync = exports.objectContainedLogSync = exports.excludeObjectSync = exports.includeObjectSync = exports.notIncludedSymbol = void 0;
exports.notIncludedSymbol = Symbol('notIncluded');
function includeObjectSync(ocv, opt) {
let current = Array.isArray(ocv) ? [] : typeof ocv === 'object' ? {} : ocv;
opt.paths.forEach((dotpath) => {
@ -31,7 +31,11 @@ function includeObjectSync(ocv, opt) {
}
exports.includeObjectSync = includeObjectSync;
function excludeObjectSync(ocv, opt) {
const copied = typeof ocv === 'object' ? Array.isArray(ocv) ? [...ocv] : { ...ocv } : ocv;
const copied = typeof ocv === 'object'
? Array.isArray(ocv)
? [...ocv]
: { ...ocv }
: ocv;
opt.paths.forEach((dotpath) => {
let objRef = copied;
const path = dotpath.split('.');
@ -50,45 +54,7 @@ function excludeObjectSync(ocv, opt) {
return copied;
}
exports.excludeObjectSync = excludeObjectSync;
function includeOrExcludeObjectSync(ocv, paths, currentPath = [], include // or exclude
) {
if (Array.isArray(ocv)) {
return (ocv.map((v, i) => includeOrExcludeObjectSync(v, paths, [...currentPath, i.toString()], include))).filter((e) => e !== exports.notIncludedSymbol);
}
if (typeof ocv === "object") {
return Object.fromEntries(Object.entries(ocv).map(([key, value]) => [
key,
includeOrExcludeObjectSync(value, paths, [...currentPath, key], include),
]).filter((e) => e[1] !== exports.notIncludedSymbol));
}
const isIncluded = paths.includes(currentPath.join("."));
return include
? isIncluded // include mode, path is in list
? ocv
: exports.notIncludedSymbol
: isIncluded // exclude mode, path is in list
? exports.notIncludedSymbol
: ocv;
}
exports.includeOrExcludeObjectSync = includeOrExcludeObjectSync;
function objectContainedLoggedSync(ocv, options) {
if (options && typeof ocv === "object") {
if (options.include && options.include.length > 0) {
return JSON.stringify(includeOrExcludeObjectSync(ocv, options.include, [], true));
}
if (options.exclude && options.exclude.length > 0) {
return JSON.stringify(includeOrExcludeObjectSync(ocv, options.exclude, [], false));
}
}
if (typeof ocv === "object") {
return JSON.stringify(ocv);
}
else {
return `${ocv}`;
}
}
exports.objectContainedLoggedSync = objectContainedLoggedSync;
function imObjectContainedLogSync(ocv, options) {
function objectContainedLogSync(ocv, options) {
if (options && typeof ocv === 'object' && ocv !== null) {
if (options.include && options.include.length > 0) {
return JSON.stringify(includeObjectSync(ocv, { paths: options.include }));
@ -97,18 +63,18 @@ function imObjectContainedLogSync(ocv, options) {
return JSON.stringify(excludeObjectSync(ocv, { paths: options.exclude }));
}
}
if (typeof ocv === "object" && ocv !== null) {
if (typeof ocv === 'object' && ocv !== null) {
return JSON.stringify(ocv);
}
else {
return `${ocv}`;
}
}
exports.imObjectContainedLogSync = imObjectContainedLogSync;
exports.objectContainedLogSync = objectContainedLogSync;
function getItemByPathSync(obj, path) {
const paths = Array.isArray(path) ? path : path.split(".");
const paths = Array.isArray(path) ? path : path.split('.');
return Object.keys(obj).includes(paths[0])
? typeof obj[paths[0]] === "object"
? typeof obj[paths[0]] === 'object'
? getItemByPathSync(obj[paths[0]], paths.slice(1))
: obj[paths[0]]
: undefined;

27
dist/lib/logged.d.ts vendored
View File

@ -1,27 +0,0 @@
import { LogLevel, ControllerOptions, ScopeOptions, ExecutionContext } from "@nestjs/common";
export declare function LoggedInjectable(options?: ScopeOptions & {
verbose?: boolean;
}): (target: any) => void;
export declare function LoggedController(): (target: any) => void;
export declare function LoggedController(prefix: string | string[]): (target: any) => void;
export declare function LoggedController(options: ControllerOptions & {
verbose?: boolean;
}): (target: any) => void;
interface OverrideBuildOptions {
callLogLevel: LogLevel | 'skip';
returnLogLevel: LogLevel | 'skip';
errorLogLevel: LogLevel | 'skip';
/** @deprecated use `callLogLevel: 'skip'` instead */
skipCallLog: boolean;
/** @deprecated use `returnLogLevel: 'skip'` instead */
skipReturnLog: boolean;
/** @deprecated use `errorLogLevel: 'skip'` instead */
skipErrorLog: boolean;
}
export declare const REQUEST_LOG_ID = "__nestlogged_request_log_id__";
export declare function LoggedFunction<F extends Array<any>, R>(options?: Partial<OverrideBuildOptions>): (_target: any, key: string, descriptor: TypedPropertyDescriptor<(...args: F) => R | Promise<R>>) => void;
export declare function LoggedRoute<F extends Array<any>, R>(route?: string, options?: Partial<OverrideBuildOptions>): (_target: any, key: string, descriptor: TypedPropertyDescriptor<(...args: F) => R>) => void;
export declare function LoggedGuard<F extends Array<any>, R>(options?: Partial<OverrideBuildOptions>): (_target: any, key: string, descriptor: TypedPropertyDescriptor<(context: ExecutionContext, ...args: F) => R>) => void;
export declare function LoggedInterceptor<F extends Array<any>, R>(options?: Partial<OverrideBuildOptions>): (_target: any, key: string, descriptor: TypedPropertyDescriptor<(context: ExecutionContext, ...args: F) => R>) => void;
export declare function LoggedMiddleware<F extends Array<any>, R>(options?: Partial<OverrideBuildOptions>): (_target: any, key: string, descriptor: TypedPropertyDescriptor<(context: ExecutionContext, ...args: F) => R>) => void;
export {};

436
dist/lib/logged.js vendored
View File

@ -1,436 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggedMiddleware = exports.LoggedInterceptor = exports.LoggedGuard = exports.LoggedRoute = exports.LoggedFunction = exports.REQUEST_LOG_ID = exports.LoggedController = exports.LoggedInjectable = void 0;
const common_1 = require("@nestjs/common");
const logger_1 = require("./logger");
const reflected_1 = require("./reflected");
const functions_1 = require("./functions");
const RevRequestMethod = [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
"ALL",
"OPTIONS",
"HEAD",
"SEARCH",
];
function loggerInit(_target) {
if (!Object.getOwnPropertyNames(_target).includes("logger")) {
const newTargetLogger = new common_1.Logger(_target.constructor.name);
newTargetLogger.log("Logger Initialized.");
Object.defineProperty(_target, "logger", {
writable: false,
enumerable: false,
configurable: false,
value: newTargetLogger,
});
}
}
function LoggedInjectable(options) {
return (target) => {
loggerInit(target.prototype);
const logger = target.prototype.logger;
const methods = Object.getOwnPropertyNames(target.prototype);
methods.forEach((method) => {
if (method !== "constructor" &&
typeof target.prototype[method] === "function") {
if (options && options.verbose)
logger.log(`LoggedFunction applied to ${method}`);
LoggedFunction()(target.prototype, method, {
value: target.prototype[method],
});
}
});
(0, common_1.Injectable)(options)(target);
};
}
exports.LoggedInjectable = LoggedInjectable;
function LoggedController(param) {
return (target) => {
loggerInit(target.prototype);
const logger = target.prototype.logger;
const methods = Object.getOwnPropertyNames(target.prototype);
let verbose = typeof param === "object" && Object.keys(param).includes("verbose")
? param.verbose
: false;
methods.forEach((method) => {
if (method !== "constructor" &&
typeof target.prototype[method] === "function") {
if (verbose) {
const path = Reflect.getMetadata("path", target.prototype[method]);
const httpMethod = Reflect.getMetadata("method", target.prototype[method]);
logger.log(`LoggedRoute applied to ${method} (${RevRequestMethod[httpMethod]} ${path})`);
}
LoggedRoute()(target.prototype, method, {
value: target.prototype[method],
});
}
});
(0, common_1.Controller)(param)(target);
};
}
exports.LoggedController = LoggedController;
const defaultOverrideBuildOptions = {
callLogLevel: 'log',
returnLogLevel: 'log',
errorLogLevel: 'error',
skipCallLog: false,
skipReturnLog: false,
skipErrorLog: false,
};
class LoggedMetadata {
constructor(options) {
this.options = {
...defaultOverrideBuildOptions,
...(options ?? {}),
};
}
updateOption(options) {
this.options = {
...this.options,
...options
};
}
}
const callLogIdentifyMessageDictionary = {
route: 'ENDPOINT',
function: 'FUNCTION',
guard: 'GUARD',
interceptor: 'INTERCEPTOR',
middleware: 'MIDDLEWARE',
};
function createCallLogIdentifyMessage(message, type, key, route) {
if (message === 'ERROR')
return `ERROR WHILE ${callLogIdentifyMessageDictionary[type]} ${key} (${route}): `;
if (type === 'guard' || type === 'interceptor' || type === 'middleware' || type === 'route')
return `${message} ${callLogIdentifyMessageDictionary[type]} ${key} (${route})`;
if (type === 'function')
return `${message} ${callLogIdentifyMessageDictionary[type]} ${key}`;
return `${message} ${callLogIdentifyMessageDictionary[type]}`;
}
exports.REQUEST_LOG_ID = '__nestlogged_request_log_id__';
function overrideBuild(type, originalFunction, baseLogger, metadatas, key, returnsData, logged, route) {
return function (...args) {
// Creating ScopedLogger
let injectedLogger = baseLogger;
if (typeof metadatas.scopedLoggerInjectableParam !== "undefined") {
if (type === 'function') {
if (args.length <= metadatas.scopedLoggerInjectableParam ||
!(args[metadatas.scopedLoggerInjectableParam] instanceof logger_1.ScopedLogger)) {
args[metadatas.scopedLoggerInjectableParam] = logger_1.ScopedLogger.fromRoot(baseLogger, key);
}
else {
args[metadatas.scopedLoggerInjectableParam] = logger_1.ScopedLogger.fromSuper(baseLogger, args[metadatas.scopedLoggerInjectableParam], key);
}
}
else {
// special, can access to request object
if (type === 'guard' || type === 'interceptor') {
// args[0] == ExecutionContext
const ctx = args[0];
if (ctx.getType() !== 'http') {
injectedLogger.error('Cannot inject logger: Request type is not http');
}
else {
let req = ctx.switchToHttp().getRequest();
if (req[exports.REQUEST_LOG_ID] === undefined) {
req[exports.REQUEST_LOG_ID] = logger_1.ScopedLogger.createScopeId();
}
args[metadatas.scopedLoggerInjectableParam] = logger_1.ScopedLogger.fromRoot(baseLogger, key, req[exports.REQUEST_LOG_ID]);
}
}
else if (type === 'middleware') {
let req = args[0];
if (req[exports.REQUEST_LOG_ID] === undefined) {
req[exports.REQUEST_LOG_ID] = logger_1.ScopedLogger.createScopeId();
}
args[metadatas.scopedLoggerInjectableParam] = logger_1.ScopedLogger.fromRoot(baseLogger, key, req[exports.REQUEST_LOG_ID]);
}
else if (type === 'route') {
// args[metadatas.scopedLoggerInjectableParam] is now Request object, thanks to code in @LoggedRoute!!!!
let req = args[metadatas.scopedLoggerInjectableParam];
if (req[exports.REQUEST_LOG_ID] === undefined) {
req[exports.REQUEST_LOG_ID] = logger_1.ScopedLogger.createScopeId();
}
args[metadatas.scopedLoggerInjectableParam] = logger_1.ScopedLogger.fromRoot(baseLogger, key, req[exports.REQUEST_LOG_ID]);
}
}
injectedLogger = args[metadatas.scopedLoggerInjectableParam];
}
// If this is ExecutionContext based function (e.g. Guard, Interceptor) get Request from Context
if (type === 'guard' || type === 'interceptor') {
const context = args[0];
if (context.getType() === 'http') {
const req = context.switchToHttp().getRequest();
route = /* supporting FastifyRequest */ req.raw ? req.raw.url : req.url;
}
}
// Start Log
if (logged.options.callLogLevel !== 'skip') {
const callLogIdentifyMessage = type === 'middleware' || type === 'guard' || type === 'interceptor' || type === 'route'
? createCallLogIdentifyMessage('HIT', type, key, route)
: createCallLogIdentifyMessage('HIT', type, key);
injectedLogger[logged.options.callLogLevel](`${callLogIdentifyMessage} ${metadatas.loggedParams && metadatas.loggedParams.length > 0
? "WITH " +
metadatas.loggedParams.map(({ name, index, include, exclude }) => name +
"=" +
(0, functions_1.imObjectContainedLogSync)(args[index], {
include,
exclude,
})).join(", ")
: ""}`);
}
try {
const r = originalFunction.call(this, ...args); // Try to call original function
// Return Log
if (logged.options.returnLogLevel !== 'skip') {
if (originalFunction.constructor.name === 'AsyncFunction' ||
(r && typeof r === 'object' && typeof r['then'] === 'function')) {
return r['then']((r) => {
const resultLogged = Array.isArray(returnsData)
? typeof r === "object" && r !== null
? "WITH " +
returnsData.map(({ name, path }) => {
const value = (0, functions_1.getItemByPathSync)(r, path);
return value !== undefined ? `${name}=${value}` : "";
})
.filter((v) => v.length > 0)
.join(", ")
: ""
: typeof returnsData === 'string'
? "WITH " + returnsData + "=" + typeof r === "object" ? JSON.stringify(r) : r
: returnsData
? typeof r === "object"
? "WITH " + JSON.stringify(r)
: "WITH " + r
: "";
injectedLogger[logged.options.returnLogLevel](`${createCallLogIdentifyMessage('RETURNED', type, key, route)} ${resultLogged}`);
return r;
});
}
else {
const resultLogged = Array.isArray(returnsData)
? typeof r === "object" && r !== null
? "WITH " +
returnsData.map(({ name, path }) => {
const value = (0, functions_1.getItemByPathSync)(r, path);
return value !== undefined ? `${name}=${value}` : "";
})
.filter((v) => v.length > 0)
.join(", ")
: ""
: typeof returnsData === 'string'
? "WITH " + returnsData + "=" + typeof r === "object" ? JSON.stringify(r) : r
: returnsData
? typeof r === "object"
? "WITH " + JSON.stringify(r)
: "WITH " + r
: "";
injectedLogger[logged.options.returnLogLevel](`${createCallLogIdentifyMessage('RETURNED', type, key, route)} ${resultLogged}`);
return r;
}
}
else {
return r;
}
}
catch (e) {
// Error Log
if (logged.options.errorLogLevel !== 'skip') {
injectedLogger[logged.options.errorLogLevel](`${createCallLogIdentifyMessage('ERROR', type, key, route)} ${e}`);
}
throw e;
}
};
}
function LoggedFunction(options) {
return (_target, key, descriptor) => {
loggerInit(_target);
const logger = _target.logger;
const fn = descriptor.value;
if (!fn || typeof fn !== "function") {
logger.warn(`LoggedFunction decorator applied to non-function property: ${key}`);
return;
}
const logMetadata = Reflect.getOwnMetadata(reflected_1.nestLoggedMetadata, _target, key);
if (logMetadata) {
// already applied, override instead
logMetadata.updateOption(options);
return;
}
const newMetadata = new LoggedMetadata(options);
const all = Reflect.getMetadataKeys(fn).map((k) => [
k,
Reflect.getMetadata(k, fn),
]);
const scopedLoggerInjectableParam = Reflect.getOwnMetadata(reflected_1.scopedLogger, _target, key);
const loggedParams = Reflect.getOwnMetadata(reflected_1.loggedParam, _target, key);
const returnsData = Reflect.getOwnMetadata(reflected_1.returns, fn);
const overrideFunction = overrideBuild('function', fn, logger, {
scopedLoggerInjectableParam,
loggedParams,
}, key, returnsData, newMetadata);
_target[key] = overrideFunction;
descriptor.value = overrideFunction;
Reflect.defineMetadata(reflected_1.nestLoggedMetadata, newMetadata, _target, key);
all.forEach(([k, v]) => {
Reflect.defineMetadata(k, v, _target[key]);
Reflect.defineMetadata(k, v, descriptor.value);
});
};
}
exports.LoggedFunction = LoggedFunction;
function LoggedRoute(route, options) {
return (_target, key, descriptor) => {
loggerInit(_target);
const logger = _target.logger;
const fn = descriptor.value;
if (!fn || typeof fn !== "function") {
logger.warn(`LoggedRoute decorator applied to non-function property: ${key}`);
return;
}
const logMetadata = Reflect.getOwnMetadata(reflected_1.nestLoggedMetadata, _target, key);
if (logMetadata) {
// already applied, override instead
logMetadata.updateOption(options);
return;
}
const newMetadata = new LoggedMetadata(options);
const all = Reflect.getMetadataKeys(fn).map((k) => [
k,
Reflect.getMetadata(k, fn),
]);
const httpPath = Reflect.getMetadata("path", fn);
const httpMethod = Reflect.getMetadata("method", fn);
const fullRoute = `${_target.constructor.name}::${route ?? httpPath}[${RevRequestMethod[httpMethod]}]`;
const scopedLoggerInjectableParam = Reflect.getOwnMetadata(reflected_1.scopedLogger, _target, key);
// if @InjectLogger exists, fake nestjs as it is @Req()
if (scopedLoggerInjectableParam !== undefined) {
(0, reflected_1.createRouteParamDecorator)(0)()(_target, key, scopedLoggerInjectableParam);
}
const loggedParams = Reflect.getOwnMetadata(reflected_1.loggedParam, _target, key);
const returnsData = Reflect.getOwnMetadata(reflected_1.returns, fn);
const overrideFunction = overrideBuild('route', fn, logger, {
scopedLoggerInjectableParam,
loggedParams,
}, key, returnsData, newMetadata, fullRoute);
_target[key] = overrideFunction;
descriptor.value = overrideFunction;
Reflect.defineMetadata(reflected_1.nestLoggedMetadata, newMetadata, _target, key);
all.forEach(([k, v]) => {
Reflect.defineMetadata(k, v, _target[key]);
Reflect.defineMetadata(k, v, descriptor.value);
});
};
}
exports.LoggedRoute = LoggedRoute;
function LoggedGuard(options) {
return (_target, key, descriptor) => {
loggerInit(_target);
const logger = _target.logger;
const fn = descriptor.value;
if (!fn || typeof fn !== "function") {
logger.warn(`LoggedGuard decorator applied to non-function property: ${key}`);
return;
}
const logMetadata = Reflect.getOwnMetadata(reflected_1.nestLoggedMetadata, _target, key);
if (logMetadata) {
// already applied, override instead
logMetadata.updateOption(options);
return;
}
const newMetadata = new LoggedMetadata(options);
const all = Reflect.getMetadataKeys(fn).map((k) => [
k,
Reflect.getMetadata(k, fn),
]);
const scopedLoggerInjectableParam = Reflect.getOwnMetadata(reflected_1.scopedLogger, _target, key);
const returnsData = Reflect.getOwnMetadata(reflected_1.returns, fn);
const overrideFunction = overrideBuild('guard', fn, logger, {
scopedLoggerInjectableParam,
loggedParams: [],
}, _target.constructor.name, returnsData, newMetadata);
_target[key] = overrideFunction;
descriptor.value = overrideFunction;
Reflect.defineMetadata(reflected_1.nestLoggedMetadata, newMetadata, _target, key);
all.forEach(([k, v]) => {
Reflect.defineMetadata(k, v, _target[key]);
Reflect.defineMetadata(k, v, descriptor.value);
});
};
}
exports.LoggedGuard = LoggedGuard;
function LoggedInterceptor(options) {
return (_target, key, descriptor) => {
loggerInit(_target);
const logger = _target.logger;
const fn = descriptor.value;
if (!fn || typeof fn !== "function") {
logger.warn(`LoggedInterceptor decorator applied to non-function property: ${key}`);
return;
}
const logMetadata = Reflect.getOwnMetadata(reflected_1.nestLoggedMetadata, _target, key);
if (logMetadata) {
// already applied, override instead
logMetadata.updateOption(options);
return;
}
const newMetadata = new LoggedMetadata(options);
const all = Reflect.getMetadataKeys(fn).map((k) => [
k,
Reflect.getMetadata(k, fn),
]);
const scopedLoggerInjectableParam = Reflect.getOwnMetadata(reflected_1.scopedLogger, _target, key);
const returnsData = Reflect.getOwnMetadata(reflected_1.returns, fn);
const overrideFunction = overrideBuild('interceptor', fn, logger, {
scopedLoggerInjectableParam,
loggedParams: [],
}, _target.constructor.name, returnsData, newMetadata);
_target[key] = overrideFunction;
descriptor.value = overrideFunction;
Reflect.defineMetadata(reflected_1.nestLoggedMetadata, newMetadata, _target, key);
all.forEach(([k, v]) => {
Reflect.defineMetadata(k, v, _target[key]);
Reflect.defineMetadata(k, v, descriptor.value);
});
};
}
exports.LoggedInterceptor = LoggedInterceptor;
function LoggedMiddleware(options) {
return (_target, key, descriptor) => {
loggerInit(_target);
const logger = _target.logger;
const fn = descriptor.value;
if (!fn || typeof fn !== "function") {
logger.warn(`LoggedMiddleware decorator applied to non-function property: ${key}`);
return;
}
const logMetadata = Reflect.getOwnMetadata(reflected_1.nestLoggedMetadata, _target, key);
if (logMetadata) {
// already applied, override instead
logMetadata.updateOption(options);
return;
}
const newMetadata = new LoggedMetadata(options);
const all = Reflect.getMetadataKeys(fn).map((k) => [
k,
Reflect.getMetadata(k, fn),
]);
const scopedLoggerInjectableParam = Reflect.getOwnMetadata(reflected_1.scopedLogger, _target, key);
const returnsData = Reflect.getOwnMetadata(reflected_1.returns, fn);
const overrideFunction = overrideBuild('middleware', fn, logger, {
scopedLoggerInjectableParam,
loggedParams: [],
}, _target.constructor.name, returnsData, newMetadata);
_target[key] = overrideFunction;
descriptor.value = overrideFunction;
Reflect.defineMetadata(reflected_1.nestLoggedMetadata, newMetadata, _target, key);
all.forEach(([k, v]) => {
Reflect.defineMetadata(k, v, _target[key]);
Reflect.defineMetadata(k, v, descriptor.value);
});
};
}
exports.LoggedMiddleware = LoggedMiddleware;

9
dist/lib/logged/class.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
import { ControllerOptions, ScopeOptions } from '@nestjs/common';
export declare function LoggedInjectable(options?: ScopeOptions & {
verbose?: boolean;
}): (target: any) => void;
export declare function LoggedController(): (target: any) => void;
export declare function LoggedController(prefix: string | string[]): (target: any) => void;
export declare function LoggedController(options: ControllerOptions & {
verbose?: boolean;
}): (target: any) => void;

50
dist/lib/logged/class.js vendored Normal file
View File

@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggedController = exports.LoggedInjectable = void 0;
const common_1 = require("@nestjs/common");
const utils_1 = require("./utils");
const methods_1 = require("./methods");
function LoggedInjectable(options) {
return (target) => {
(0, utils_1.loggerInit)(target.prototype);
const logger = target.prototype.logger;
const methods = Object.getOwnPropertyNames(target.prototype);
methods.forEach((method) => {
if (method !== 'constructor' &&
typeof target.prototype[method] === 'function') {
if (options && options.verbose)
logger.log(`LoggedFunction applied to ${method}`);
(0, methods_1.LoggedFunction)()(target.prototype, method, {
value: target.prototype[method],
});
}
});
(0, common_1.Injectable)(options)(target);
};
}
exports.LoggedInjectable = LoggedInjectable;
function LoggedController(param) {
return (target) => {
(0, utils_1.loggerInit)(target.prototype);
const logger = target.prototype.logger;
const methods = Object.getOwnPropertyNames(target.prototype);
let verbose = typeof param === 'object' && Object.keys(param).includes('verbose')
? param.verbose
: false;
methods.forEach((method) => {
if (method !== 'constructor' &&
typeof target.prototype[method] === 'function') {
if (verbose) {
const path = Reflect.getMetadata('path', target.prototype[method]);
const httpMethod = Reflect.getMetadata('method', target.prototype[method]);
logger.log(`LoggedRoute applied to ${method} (${utils_1.RevRequestMethod[httpMethod]} ${path})`);
}
(0, methods_1.LoggedRoute)()(target.prototype, method, {
value: target.prototype[method],
});
}
});
(0, common_1.Controller)(param)(target);
};
}
exports.LoggedController = LoggedController;

2
dist/lib/logged/index.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
export * from './methods';
export { LoggedController, LoggedInjectable } from './class';

21
dist/lib/logged/index.js vendored Normal file
View File

@ -0,0 +1,21 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggedInjectable = exports.LoggedController = void 0;
__exportStar(require("./methods"), exports);
var class_1 = require("./class");
Object.defineProperty(exports, "LoggedController", { enumerable: true, get: function () { return class_1.LoggedController; } });
Object.defineProperty(exports, "LoggedInjectable", { enumerable: true, get: function () { return class_1.LoggedInjectable; } });

7
dist/lib/logged/metadata.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
import { OverrideBuildOptions } from './utils';
export declare const nestLoggedMetadata: unique symbol;
export declare class LoggedMetadata {
options: OverrideBuildOptions;
constructor(options?: Partial<OverrideBuildOptions>);
updateOption(options: Partial<OverrideBuildOptions>): void;
}

20
dist/lib/logged/metadata.js vendored Normal file
View File

@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggedMetadata = exports.nestLoggedMetadata = void 0;
const utils_1 = require("./utils");
exports.nestLoggedMetadata = Symbol('nlogdec-metadata');
class LoggedMetadata {
constructor(options) {
this.options = {
...utils_1.defaultOverrideBuildOptions,
...(options ?? {}),
};
}
updateOption(options) {
this.options = {
...this.options,
...options,
};
}
}
exports.LoggedMetadata = LoggedMetadata;

2
dist/lib/logged/methods/function.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
import { OverrideBuildOptions } from '../utils';
export declare function LoggedFunction<F extends Array<any>, R>(options?: Partial<OverrideBuildOptions>): (_target: any, key: string, descriptor: TypedPropertyDescriptor<(...args: F) => R | Promise<R>>) => void;

44
dist/lib/logged/methods/function.js vendored Normal file
View File

@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggedFunction = void 0;
const utils_1 = require("../utils");
const metadata_1 = require("../metadata");
const reflected_1 = require("../../reflected");
const override_1 = require("../override");
function LoggedFunction(options) {
return (_target, key, descriptor) => {
(0, utils_1.loggerInit)(_target);
const logger = _target.logger;
const fn = descriptor.value;
if (!fn || typeof fn !== 'function') {
logger.warn(`LoggedFunction decorator applied to non-function property: ${key}`);
return;
}
const logMetadata = Reflect.getOwnMetadata(metadata_1.nestLoggedMetadata, _target, key);
if (logMetadata) {
// already applied, override instead
logMetadata.updateOption(options);
return;
}
const newMetadata = new metadata_1.LoggedMetadata(options);
const all = Reflect.getMetadataKeys(fn).map((k) => [
k,
Reflect.getMetadata(k, fn),
]);
const scopedLoggerInjectableParam = Reflect.getOwnMetadata(reflected_1.scopedLogger, _target, key);
const loggedParams = Reflect.getOwnMetadata(reflected_1.loggedParam, _target, key);
const returnsData = Reflect.getOwnMetadata(reflected_1.returns, fn);
const overrideFunction = (0, override_1.overrideBuild)('function', fn, logger, {
scopedLoggerInjectableParam,
loggedParams,
}, key, returnsData, newMetadata);
_target[key] = overrideFunction;
descriptor.value = overrideFunction;
Reflect.defineMetadata(metadata_1.nestLoggedMetadata, newMetadata, _target, key);
all.forEach(([k, v]) => {
Reflect.defineMetadata(k, v, _target[key]);
Reflect.defineMetadata(k, v, descriptor.value);
});
};
}
exports.LoggedFunction = LoggedFunction;

3
dist/lib/logged/methods/guard.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
import { ExecutionContext } from '@nestjs/common';
import { OverrideBuildOptions } from '../utils';
export declare function LoggedGuard<F extends Array<any>, R>(options?: Partial<OverrideBuildOptions>): (_target: any, key: string, descriptor: TypedPropertyDescriptor<(context: ExecutionContext, ...args: F) => R>) => void;

43
dist/lib/logged/methods/guard.js vendored Normal file
View File

@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggedGuard = void 0;
const utils_1 = require("../utils");
const metadata_1 = require("../metadata");
const reflected_1 = require("../../reflected");
const override_1 = require("../override");
function LoggedGuard(options) {
return (_target, key, descriptor) => {
(0, utils_1.loggerInit)(_target);
const logger = _target.logger;
const fn = descriptor.value;
if (!fn || typeof fn !== 'function') {
logger.warn(`LoggedGuard decorator applied to non-function property: ${key}`);
return;
}
const logMetadata = Reflect.getOwnMetadata(metadata_1.nestLoggedMetadata, _target, key);
if (logMetadata) {
// already applied, override instead
logMetadata.updateOption(options);
return;
}
const newMetadata = new metadata_1.LoggedMetadata(options);
const all = Reflect.getMetadataKeys(fn).map((k) => [
k,
Reflect.getMetadata(k, fn),
]);
const scopedLoggerInjectableParam = Reflect.getOwnMetadata(reflected_1.scopedLogger, _target, key);
const returnsData = Reflect.getOwnMetadata(reflected_1.returns, fn);
const overrideFunction = (0, override_1.overrideBuild)('guard', fn, logger, {
scopedLoggerInjectableParam,
loggedParams: [],
}, _target.constructor.name, returnsData, newMetadata);
_target[key] = overrideFunction;
descriptor.value = overrideFunction;
Reflect.defineMetadata(metadata_1.nestLoggedMetadata, newMetadata, _target, key);
all.forEach(([k, v]) => {
Reflect.defineMetadata(k, v, _target[key]);
Reflect.defineMetadata(k, v, descriptor.value);
});
};
}
exports.LoggedGuard = LoggedGuard;

5
dist/lib/logged/methods/index.d.ts vendored Normal file
View File

@ -0,0 +1,5 @@
export { LoggedFunction } from './function';
export { LoggedRoute } from './route';
export { LoggedGuard } from './guard';
export { LoggedInterceptor } from './interceptor';
export { LoggedMiddleware } from './middleware';

13
dist/lib/logged/methods/index.js vendored Normal file
View File

@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggedMiddleware = exports.LoggedInterceptor = exports.LoggedGuard = exports.LoggedRoute = exports.LoggedFunction = void 0;
var function_1 = require("./function");
Object.defineProperty(exports, "LoggedFunction", { enumerable: true, get: function () { return function_1.LoggedFunction; } });
var route_1 = require("./route");
Object.defineProperty(exports, "LoggedRoute", { enumerable: true, get: function () { return route_1.LoggedRoute; } });
var guard_1 = require("./guard");
Object.defineProperty(exports, "LoggedGuard", { enumerable: true, get: function () { return guard_1.LoggedGuard; } });
var interceptor_1 = require("./interceptor");
Object.defineProperty(exports, "LoggedInterceptor", { enumerable: true, get: function () { return interceptor_1.LoggedInterceptor; } });
var middleware_1 = require("./middleware");
Object.defineProperty(exports, "LoggedMiddleware", { enumerable: true, get: function () { return middleware_1.LoggedMiddleware; } });

View File

@ -0,0 +1,3 @@
import { OverrideBuildOptions } from '../utils';
import { ExecutionContext } from '@nestjs/common';
export declare function LoggedInterceptor<F extends Array<any>, R>(options?: Partial<OverrideBuildOptions>): (_target: any, key: string, descriptor: TypedPropertyDescriptor<(context: ExecutionContext, ...args: F) => R>) => void;

43
dist/lib/logged/methods/interceptor.js vendored Normal file
View File

@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggedInterceptor = void 0;
const utils_1 = require("../utils");
const metadata_1 = require("../metadata");
const reflected_1 = require("../../reflected");
const override_1 = require("../override");
function LoggedInterceptor(options) {
return (_target, key, descriptor) => {
(0, utils_1.loggerInit)(_target);
const logger = _target.logger;
const fn = descriptor.value;
if (!fn || typeof fn !== 'function') {
logger.warn(`LoggedInterceptor decorator applied to non-function property: ${key}`);
return;
}
const logMetadata = Reflect.getOwnMetadata(metadata_1.nestLoggedMetadata, _target, key);
if (logMetadata) {
// already applied, override instead
logMetadata.updateOption(options);
return;
}
const newMetadata = new metadata_1.LoggedMetadata(options);
const all = Reflect.getMetadataKeys(fn).map((k) => [
k,
Reflect.getMetadata(k, fn),
]);
const scopedLoggerInjectableParam = Reflect.getOwnMetadata(reflected_1.scopedLogger, _target, key);
const returnsData = Reflect.getOwnMetadata(reflected_1.returns, fn);
const overrideFunction = (0, override_1.overrideBuild)('interceptor', fn, logger, {
scopedLoggerInjectableParam,
loggedParams: [],
}, _target.constructor.name, returnsData, newMetadata);
_target[key] = overrideFunction;
descriptor.value = overrideFunction;
Reflect.defineMetadata(metadata_1.nestLoggedMetadata, newMetadata, _target, key);
all.forEach(([k, v]) => {
Reflect.defineMetadata(k, v, _target[key]);
Reflect.defineMetadata(k, v, descriptor.value);
});
};
}
exports.LoggedInterceptor = LoggedInterceptor;

View File

@ -0,0 +1,3 @@
import { OverrideBuildOptions } from '../utils';
import { ExecutionContext } from '@nestjs/common';
export declare function LoggedMiddleware<F extends Array<any>, R>(options?: Partial<OverrideBuildOptions>): (_target: any, key: string, descriptor: TypedPropertyDescriptor<(context: ExecutionContext, ...args: F) => R>) => void;

43
dist/lib/logged/methods/middleware.js vendored Normal file
View File

@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggedMiddleware = void 0;
const utils_1 = require("../utils");
const metadata_1 = require("../metadata");
const reflected_1 = require("../../reflected");
const override_1 = require("../override");
function LoggedMiddleware(options) {
return (_target, key, descriptor) => {
(0, utils_1.loggerInit)(_target);
const logger = _target.logger;
const fn = descriptor.value;
if (!fn || typeof fn !== 'function') {
logger.warn(`LoggedMiddleware decorator applied to non-function property: ${key}`);
return;
}
const logMetadata = Reflect.getOwnMetadata(metadata_1.nestLoggedMetadata, _target, key);
if (logMetadata) {
// already applied, override instead
logMetadata.updateOption(options);
return;
}
const newMetadata = new metadata_1.LoggedMetadata(options);
const all = Reflect.getMetadataKeys(fn).map((k) => [
k,
Reflect.getMetadata(k, fn),
]);
const scopedLoggerInjectableParam = Reflect.getOwnMetadata(reflected_1.scopedLogger, _target, key);
const returnsData = Reflect.getOwnMetadata(reflected_1.returns, fn);
const overrideFunction = (0, override_1.overrideBuild)('middleware', fn, logger, {
scopedLoggerInjectableParam,
loggedParams: [],
}, _target.constructor.name, returnsData, newMetadata);
_target[key] = overrideFunction;
descriptor.value = overrideFunction;
Reflect.defineMetadata(metadata_1.nestLoggedMetadata, newMetadata, _target, key);
all.forEach(([k, v]) => {
Reflect.defineMetadata(k, v, _target[key]);
Reflect.defineMetadata(k, v, descriptor.value);
});
};
}
exports.LoggedMiddleware = LoggedMiddleware;

2
dist/lib/logged/methods/route.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
import { OverrideBuildOptions } from '../utils';
export declare function LoggedRoute<F extends Array<any>, R>(route?: string, options?: Partial<OverrideBuildOptions>): (_target: any, key: string, descriptor: TypedPropertyDescriptor<(...args: F) => R>) => void;

52
dist/lib/logged/methods/route.js vendored Normal file
View File

@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggedRoute = void 0;
const utils_1 = require("../utils");
const metadata_1 = require("../metadata");
const reflected_1 = require("../../reflected");
const override_1 = require("../override");
const nest_1 = require("../../internals/nest");
function LoggedRoute(route, options) {
return (_target, key, descriptor) => {
(0, utils_1.loggerInit)(_target);
const logger = _target.logger;
const fn = descriptor.value;
if (!fn || typeof fn !== 'function') {
logger.warn(`LoggedRoute decorator applied to non-function property: ${key}`);
return;
}
const logMetadata = Reflect.getOwnMetadata(metadata_1.nestLoggedMetadata, _target, key);
if (logMetadata) {
// already applied, override instead
logMetadata.updateOption(options);
return;
}
const newMetadata = new metadata_1.LoggedMetadata(options);
const all = Reflect.getMetadataKeys(fn).map((k) => [
k,
Reflect.getMetadata(k, fn),
]);
const httpPath = Reflect.getMetadata('path', fn);
const httpMethod = Reflect.getMetadata('method', fn);
const fullRoute = `${_target.constructor.name}::${route ?? httpPath}[${utils_1.RevRequestMethod[httpMethod]}]`;
const scopedLoggerInjectableParam = Reflect.getOwnMetadata(reflected_1.scopedLogger, _target, key);
// if @InjectLogger exists, fake nestjs as it is @Req()
if (scopedLoggerInjectableParam !== undefined) {
(0, nest_1.createRouteParamDecorator)(0)()(_target, key, scopedLoggerInjectableParam);
}
const loggedParams = Reflect.getOwnMetadata(reflected_1.loggedParam, _target, key);
const returnsData = Reflect.getOwnMetadata(reflected_1.returns, fn);
const overrideFunction = (0, override_1.overrideBuild)('route', fn, logger, {
scopedLoggerInjectableParam,
loggedParams,
}, key, returnsData, newMetadata, fullRoute);
_target[key] = overrideFunction;
descriptor.value = overrideFunction;
Reflect.defineMetadata(metadata_1.nestLoggedMetadata, newMetadata, _target, key);
all.forEach(([k, v]) => {
Reflect.defineMetadata(k, v, _target[key]);
Reflect.defineMetadata(k, v, descriptor.value);
});
};
}
exports.LoggedRoute = LoggedRoute;

10
dist/lib/logged/override.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
import { Logger } from '@nestjs/common';
import { LoggedParamReflectData, ReturnsReflectData } from '../reflected';
import { LoggedMetadata } from './metadata';
interface FunctionMetadata {
scopedLoggerInjectableParam?: number;
loggedParams?: LoggedParamReflectData[];
}
export declare function overrideBuild<F extends Array<any>, R>(type: 'route', originalFunction: (...args: F) => R, baseLogger: Logger, metadatas: FunctionMetadata, key: string, returnsData: ReturnsReflectData[] | string | true, logged: LoggedMetadata, route: string): (...args: F) => R;
export declare function overrideBuild<F extends Array<any>, R>(type: 'function' | 'guard' | 'interceptor' | 'middleware', originalFunction: (...args: F) => R, baseLogger: Logger, metadatas: FunctionMetadata, key: string, returnsData: ReturnsReflectData[] | string | true, logged: LoggedMetadata): (...args: F) => R;
export {};

152
dist/lib/logged/override.js vendored Normal file
View File

@ -0,0 +1,152 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.overrideBuild = void 0;
const utils_1 = require("./utils");
const utils_2 = require("../internals/utils");
const logger_1 = require("../logger");
function overrideBuild(type, originalFunction, baseLogger, metadatas, key, returnsData, logged, route) {
return function (...args) {
// Creating ScopedLogger
let injectedLogger = baseLogger;
if (typeof metadatas.scopedLoggerInjectableParam !== 'undefined') {
if (type === 'function') {
if (args.length <= metadatas.scopedLoggerInjectableParam ||
!(args[metadatas.scopedLoggerInjectableParam] instanceof logger_1.ScopedLogger)) {
args[metadatas.scopedLoggerInjectableParam] = logger_1.ScopedLogger.fromRoot(baseLogger, key);
}
else {
args[metadatas.scopedLoggerInjectableParam] = logger_1.ScopedLogger.fromSuper(baseLogger, args[metadatas.scopedLoggerInjectableParam], key);
}
}
else {
// special, can access to request object
if (type === 'guard' || type === 'interceptor') {
// args[0] == ExecutionContext
const ctx = args[0];
if (ctx.getType() !== 'http') {
injectedLogger.error('Cannot inject logger: Request type is not http');
}
else {
let req = ctx.switchToHttp().getRequest();
if (req[utils_1.REQUEST_LOG_ID] === undefined) {
req[utils_1.REQUEST_LOG_ID] = logger_1.ScopedLogger.createScopeId();
}
args[metadatas.scopedLoggerInjectableParam] = logger_1.ScopedLogger.fromRoot(baseLogger, key, req[utils_1.REQUEST_LOG_ID]);
}
}
else if (type === 'middleware') {
let req = args[0];
if (req[utils_1.REQUEST_LOG_ID] === undefined) {
req[utils_1.REQUEST_LOG_ID] = logger_1.ScopedLogger.createScopeId();
}
args[metadatas.scopedLoggerInjectableParam] = logger_1.ScopedLogger.fromRoot(baseLogger, key, req[utils_1.REQUEST_LOG_ID]);
}
else if (type === 'route') {
// args[metadatas.scopedLoggerInjectableParam] is now Request object, thanks to code in @LoggedRoute!!!!
let req = args[metadatas.scopedLoggerInjectableParam];
if (req[utils_1.REQUEST_LOG_ID] === undefined) {
req[utils_1.REQUEST_LOG_ID] = logger_1.ScopedLogger.createScopeId();
}
args[metadatas.scopedLoggerInjectableParam] = logger_1.ScopedLogger.fromRoot(baseLogger, key, req[utils_1.REQUEST_LOG_ID]);
}
}
injectedLogger = args[metadatas.scopedLoggerInjectableParam];
}
// If this is ExecutionContext based function (e.g. Guard, Interceptor) get Request from Context
if (type === 'guard' || type === 'interceptor') {
const context = args[0];
if (context.getType() === 'http') {
const req = context.switchToHttp().getRequest();
route = /* supporting FastifyRequest */ req.raw ? req.raw.url : req.url;
}
}
// Start Log
if (logged.options.callLogLevel !== 'skip') {
const callLogIdentifyMessage = type === 'middleware' ||
type === 'guard' ||
type === 'interceptor' ||
type === 'route'
? (0, utils_1.createCallLogIdentifyMessage)('HIT', type, key, route)
: (0, utils_1.createCallLogIdentifyMessage)('HIT', type, key);
injectedLogger[logged.options.callLogLevel](`${callLogIdentifyMessage} ${metadatas.loggedParams && metadatas.loggedParams.length > 0
? 'WITH ' +
metadatas.loggedParams
.map(({ name, index, include, exclude }) => name +
'=' +
(0, utils_2.objectContainedLogSync)(args[index], {
include,
exclude,
}))
.join(', ')
: ''}`);
}
try {
const r = originalFunction.call(this, ...args); // Try to call original function
// Return Log
if (logged.options.returnLogLevel !== 'skip') {
if (originalFunction.constructor.name === 'AsyncFunction' ||
(r && typeof r === 'object' && typeof r['then'] === 'function')) {
return r['then']((r) => {
const resultLogged = Array.isArray(returnsData)
? typeof r === 'object' && r !== null
? 'WITH ' +
returnsData
.map(({ name, path }) => {
const value = (0, utils_2.getItemByPathSync)(r, path);
return value !== undefined ? `${name}=${value}` : '';
})
.filter((v) => v.length > 0)
.join(', ')
: ''
: typeof returnsData === 'string'
? 'WITH ' + returnsData + '=' + typeof r === 'object'
? JSON.stringify(r)
: r
: returnsData
? typeof r === 'object'
? 'WITH ' + JSON.stringify(r)
: 'WITH ' + r
: '';
injectedLogger[logged.options.returnLogLevel](`${(0, utils_1.createCallLogIdentifyMessage)('RETURNED', type, key, route)} ${resultLogged}`);
return r;
});
}
else {
const resultLogged = Array.isArray(returnsData)
? typeof r === 'object' && r !== null
? 'WITH ' +
returnsData
.map(({ name, path }) => {
const value = (0, utils_2.getItemByPathSync)(r, path);
return value !== undefined ? `${name}=${value}` : '';
})
.filter((v) => v.length > 0)
.join(', ')
: ''
: typeof returnsData === 'string'
? 'WITH ' + returnsData + '=' + typeof r === 'object'
? JSON.stringify(r)
: r
: returnsData
? typeof r === 'object'
? 'WITH ' + JSON.stringify(r)
: 'WITH ' + r
: '';
injectedLogger[logged.options.returnLogLevel](`${(0, utils_1.createCallLogIdentifyMessage)('RETURNED', type, key, route)} ${resultLogged}`);
return r;
}
}
else {
return r;
}
}
catch (e) {
// Error Log
if (logged.options.errorLogLevel !== 'skip') {
injectedLogger[logged.options.errorLogLevel](`${(0, utils_1.createCallLogIdentifyMessage)('ERROR', type, key, route)} ${e}`);
}
throw e;
}
};
}
exports.overrideBuild = overrideBuild;

18
dist/lib/logged/utils.d.ts vendored Normal file
View File

@ -0,0 +1,18 @@
import { LogLevel } from '@nestjs/common';
export declare const RevRequestMethod: string[];
export declare function loggerInit(_target: any): void;
export type BuildType = 'route' | 'function' | 'guard' | 'interceptor' | 'middleware';
export declare function createCallLogIdentifyMessage(message: 'HIT' | 'RETURNED' | 'ERROR', type: BuildType, key?: string, route?: string): string;
export declare const REQUEST_LOG_ID = "__nestlogged_request_log_id__";
export interface OverrideBuildOptions {
callLogLevel: LogLevel | 'skip';
returnLogLevel: LogLevel | 'skip';
errorLogLevel: LogLevel | 'skip';
/** @deprecated use `callLogLevel: 'skip'` instead */
skipCallLog: boolean;
/** @deprecated use `returnLogLevel: 'skip'` instead */
skipReturnLog: boolean;
/** @deprecated use `errorLogLevel: 'skip'` instead */
skipErrorLog: boolean;
}
export declare const defaultOverrideBuildOptions: OverrideBuildOptions;

57
dist/lib/logged/utils.js vendored Normal file
View File

@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultOverrideBuildOptions = exports.REQUEST_LOG_ID = exports.createCallLogIdentifyMessage = exports.loggerInit = exports.RevRequestMethod = void 0;
const common_1 = require("@nestjs/common");
exports.RevRequestMethod = [
'GET',
'POST',
'PUT',
'DELETE',
'PATCH',
'ALL',
'OPTIONS',
'HEAD',
'SEARCH',
];
function loggerInit(_target) {
if (!Object.getOwnPropertyNames(_target).includes('logger')) {
const newTargetLogger = new common_1.Logger(_target.constructor.name);
newTargetLogger.log('Logger Initialized.');
Object.defineProperty(_target, 'logger', {
writable: false,
enumerable: false,
configurable: false,
value: newTargetLogger,
});
}
}
exports.loggerInit = loggerInit;
const callLogIdentifyMessageDictionary = {
route: 'ENDPOINT',
function: 'FUNCTION',
guard: 'GUARD',
interceptor: 'INTERCEPTOR',
middleware: 'MIDDLEWARE',
};
function createCallLogIdentifyMessage(message, type, key, route) {
if (message === 'ERROR')
return `ERROR WHILE ${callLogIdentifyMessageDictionary[type]} ${key} (${route}): `;
if (type === 'guard' ||
type === 'interceptor' ||
type === 'middleware' ||
type === 'route')
return `${message} ${callLogIdentifyMessageDictionary[type]} ${key} (${route})`;
if (type === 'function')
return `${message} ${callLogIdentifyMessageDictionary[type]} ${key}`;
return `${message} ${callLogIdentifyMessageDictionary[type]}`;
}
exports.createCallLogIdentifyMessage = createCallLogIdentifyMessage;
exports.REQUEST_LOG_ID = '__nestlogged_request_log_id__';
exports.defaultOverrideBuildOptions = {
callLogLevel: 'log',
returnLogLevel: 'log',
errorLogLevel: 'error',
skipCallLog: false,
skipReturnLog: false,
skipErrorLog: false,
};

View File

@ -1,4 +1,4 @@
import { Logger } from "@nestjs/common";
import { Logger } from '@nestjs/common';
export declare class ScopedLogger extends Logger {
private logger;
private scope;

16
dist/lib/logger.js vendored
View File

@ -10,26 +10,24 @@ class ScopedLogger extends common_1.Logger {
this.logger = logger;
this.scope = scope;
this.scopeId = scopeId;
this.debug = this.scopedLog("debug");
this.log = this.scopedLog("log");
this.warn = this.scopedLog("warn");
this.verbose = this.scopedLog("verbose");
this.error = this.scopedLog("error");
this.fatal = this.scopedLog("fatal");
this.debug = this.scopedLog('debug');
this.log = this.scopedLog('log');
this.warn = this.scopedLog('warn');
this.verbose = this.scopedLog('verbose');
this.error = this.scopedLog('error');
this.fatal = this.scopedLog('fatal');
}
scopedLog(method) {
return (message) => {
this.logger[method](`${this.scopeId ? `(ID ${this.scopeId}) | ` : ""}${this.scope.join(" -> ")}: ${message}`);
this.logger[method](`${this.scopeId ? `(ID ${this.scopeId}) | ` : ''}${this.scope.join(' -> ')}: ${message}`);
};
}
static fromSuper(baseLogger, logger, scope) {
return new ScopedLogger(baseLogger, [...logger.scope, scope], logger.scopeId);
}
;
static fromRoot(logger, scope, scopeId) {
return new ScopedLogger(logger, [scope], scopeId);
}
;
static createScopeId() {
return createId();
}

View File

@ -1,6 +1,4 @@
import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum';
import { ParamData, PipeTransform, Type } from "@nestjs/common";
export declare function createRouteParamDecorator(paramtype: RouteParamtypes): (data?: ParamData) => ParameterDecorator;
import { Type, PipeTransform } from './internals/nest';
export type Path = string | string[];
export type Paths = Path[];
export interface IncludeExcludePath {
@ -26,7 +24,6 @@ export interface ReturnsReflectData {
export declare const scopedLogger: unique symbol;
export declare const loggedParam: unique symbol;
export declare const returns: unique symbol;
export declare const nestLoggedMetadata: unique symbol;
export declare function InjectLogger(target: any, propertyKey: string | symbol, parameterIndex: number): void;
type ParameterDecoratorType = (target: any, propertyKey: string | symbol, parameterIndex: number) => void;
type LoggedParamReturns = (name: string, options?: IncludeExcludePath) => ParameterDecoratorType;

40
dist/lib/reflected.js vendored
View File

@ -1,28 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Returns = exports.LoggedHeaders = exports.LoggedBody = exports.LoggedQuery = exports.LoggedParam = exports.Logged = exports.InjectLogger = exports.nestLoggedMetadata = exports.returns = exports.loggedParam = exports.scopedLogger = exports.createRouteParamDecorator = void 0;
const route_paramtypes_enum_1 = require("@nestjs/common/enums/route-paramtypes.enum");
const common_1 = require("@nestjs/common");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const ROUTE_ARGS_METADATA = '__routeArguments__';
function createRouteParamDecorator(paramtype) {
return (data) => (target, key, index) => {
const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, target.constructor, key) || {};
Reflect.defineMetadata(ROUTE_ARGS_METADATA, (0, common_1.assignMetadata)(args, paramtype, index, data), target.constructor, key);
};
}
exports.createRouteParamDecorator = createRouteParamDecorator;
const createPipesRouteParamDecorator = (paramtype) => (data, ...pipes) => (target, key, index) => {
const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, target.constructor, key) || {};
const hasParamData = (0, shared_utils_1.isNil)(data) || (0, shared_utils_1.isString)(data);
const paramData = hasParamData ? data : undefined;
const paramPipes = hasParamData ? pipes : [data, ...pipes];
Reflect.defineMetadata(ROUTE_ARGS_METADATA, (0, common_1.assignMetadata)(args, paramtype, index, paramData, ...paramPipes), target.constructor, key);
};
exports.scopedLogger = Symbol("nlogdec-scopedLogger");
exports.loggedParam = Symbol("nlogdec-loggedParam");
exports.returns = Symbol("nlogdec-returns");
exports.nestLoggedMetadata = Symbol("nlogdec-metadata");
exports.Returns = exports.LoggedHeaders = exports.LoggedBody = exports.LoggedQuery = exports.LoggedParam = exports.Logged = exports.InjectLogger = exports.returns = exports.loggedParam = exports.scopedLogger = void 0;
const nest_1 = require("./internals/nest");
exports.scopedLogger = Symbol('nlogdec-scopedLogger');
exports.loggedParam = Symbol('nlogdec-loggedParam');
exports.returns = Symbol('nlogdec-returns');
function InjectLogger(target, propertyKey, parameterIndex) {
Reflect.defineMetadata(exports.scopedLogger, parameterIndex, target, propertyKey);
}
@ -36,10 +18,10 @@ function createLoggedFunctionParam(name, options) {
// If path is provided in string[] type, convert it to string path because it is used in string type
include: options &&
options.includePath &&
options.includePath.map((v) => (Array.isArray(v) ? v.join(".") : v)),
options.includePath.map((v) => (Array.isArray(v) ? v.join('.') : v)),
exclude: options &&
options.excludePath &&
options.excludePath.map((v) => (Array.isArray(v) ? v.join(".") : v)),
options.excludePath.map((v) => (Array.isArray(v) ? v.join('.') : v)),
});
Reflect.defineMetadata(exports.loggedParam, existingLoggedParams, target, propertyKey);
};
@ -49,7 +31,7 @@ exports.Logged = Logged;
function LoggedParam(property, ...pipes) {
return (name, options) => {
return (target, propertyKey, parameterIndex) => {
createPipesRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.PARAM)(property, ...pipes)(target, propertyKey, parameterIndex);
(0, nest_1.createPipesRouteParamDecorator)(nest_1.RouteParamtypes.PARAM)(property, ...pipes)(target, propertyKey, parameterIndex);
createLoggedFunctionParam(name, options)(target, propertyKey, parameterIndex);
};
};
@ -58,7 +40,7 @@ exports.LoggedParam = LoggedParam;
function LoggedQuery(property, ...pipes) {
return (name, options) => {
return (target, propertyKey, parameterIndex) => {
createPipesRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.QUERY)(property, ...pipes)(target, propertyKey, parameterIndex);
(0, nest_1.createPipesRouteParamDecorator)(nest_1.RouteParamtypes.QUERY)(property, ...pipes)(target, propertyKey, parameterIndex);
createLoggedFunctionParam(name, options)(target, propertyKey, parameterIndex);
};
};
@ -67,7 +49,7 @@ exports.LoggedQuery = LoggedQuery;
function LoggedBody(property, ...pipes) {
return (name, options) => {
return (target, propertyKey, parameterIndex) => {
createPipesRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.BODY)(property, ...pipes)(target, propertyKey, parameterIndex);
(0, nest_1.createPipesRouteParamDecorator)(nest_1.RouteParamtypes.BODY)(property, ...pipes)(target, propertyKey, parameterIndex);
createLoggedFunctionParam(name, options)(target, propertyKey, parameterIndex);
};
};
@ -76,7 +58,7 @@ exports.LoggedBody = LoggedBody;
function LoggedHeaders(property) {
return (name, options) => {
return (target, propertyKey, parameterIndex) => {
createRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.HEADERS)(property)(target, propertyKey, parameterIndex);
(0, nest_1.createRouteParamDecorator)(nest_1.RouteParamtypes.HEADERS)(property)(target, propertyKey, parameterIndex);
createLoggedFunctionParam(name, options)(target, propertyKey, parameterIndex);
};
};

2
dist/lib/utils.d.ts vendored
View File

@ -1,2 +1,2 @@
import { ScopedLogger } from "./logger";
import { ScopedLogger } from './logger';
export declare function getRequestLogger(functionName: string, req: any): ScopedLogger;

4
dist/lib/utils.js vendored
View File

@ -3,9 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
exports.getRequestLogger = void 0;
const common_1 = require("@nestjs/common");
const logger_1 = require("./logger");
const logged_1 = require("./logged");
const utils_1 = require("./logged/utils");
const logger = new common_1.Logger();
function getRequestLogger(functionName, req) {
return new logger_1.ScopedLogger(logger, [functionName], req[logged_1.REQUEST_LOG_ID]);
return new logger_1.ScopedLogger(logger, [functionName], req[utils_1.REQUEST_LOG_ID]);
}
exports.getRequestLogger = getRequestLogger;

2
dist/package.json vendored
View File

@ -1,6 +1,6 @@
{
"name": "nestlogged",
"version": "3.2.0",
"version": "3.2.1",
"description": "A NestJS Logger Decorator Library",
"main": "lib/index.js",
"repository": "https://git.psw.kr/p-sw/nestlogged",

View File

@ -1,6 +1,6 @@
{
"name": "nestlogged",
"version": "3.2.0",
"version": "3.2.1",
"description": "A NestJS Logger Decorator Library",
"main": "./dist/lib/index.js",
"repository": "https://git.psw.kr/p-sw/nestlogged",