refactor(infra): directory structure (#4615)

This commit is contained in:
Joooye_34
2023-10-18 23:30:08 +08:00
committed by GitHub
parent 814d552be8
commit bed9310519
1150 changed files with 539 additions and 584 deletions

View File

@@ -0,0 +1,34 @@
/**
* @vitest-environment happy-dom
*/
import { describe, expect, test, vi } from 'vitest';
import { DebugLogger } from '..';
describe('debug', () => {
test('disabled', () => {
const logger = new DebugLogger('test');
logger.enabled = false;
for (const level of ['debug', 'info', 'warn', 'error'] as const) {
const fn = vi.fn();
vi.spyOn(globalThis.console, level).mockImplementation(fn);
expect(logger.enabled).toBe(false);
expect(fn).not.toBeCalled();
logger[level]('test');
expect(fn, level).not.toBeCalled();
}
});
test('log', () => {
const logger = new DebugLogger('test');
logger.enabled = true;
for (const level of ['debug', 'info', 'warn', 'error'] as const) {
const fn = vi.fn();
vi.spyOn(globalThis.console, level).mockImplementation(fn);
expect(logger.enabled).toBe(true);
expect(fn).not.toBeCalled();
logger[level]('test');
expect(fn, level).toBeCalled();
}
});
});

View File

@@ -0,0 +1,61 @@
import debug from 'debug';
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
const SESSION_KEY = 'affine:debug';
if (typeof window !== 'undefined') {
// enable debug logs if the URL search string contains `debug`
// e.g. http://localhost:3000/?debug
if (window.location.search.includes('debug')) {
// enable debug logs for the current session
// since the query string may be removed by the browser after navigations,
// we need to store the debug flag in sessionStorage
sessionStorage.setItem(SESSION_KEY, 'true');
}
if (sessionStorage.getItem(SESSION_KEY) === 'true') {
// enable all debug logs by default
debug.enable('*');
console.warn('Debug logs enabled');
}
if (process.env.NODE_ENV === 'development') {
debug.enable('*');
console.warn('Debug logs enabled');
}
}
export class DebugLogger {
private _debug: debug.Debugger;
constructor(namespace: string) {
this._debug = debug(namespace);
}
set enabled(enabled: boolean) {
this._debug.enabled = enabled;
}
get enabled() {
return this._debug.enabled;
}
debug(message: string, ...args: any[]) {
this.log('debug', message, ...args);
}
info(message: string, ...args: any[]) {
this.log('info', message, ...args);
}
warn(message: string, ...args: any[]) {
this.log('warn', message, ...args);
}
error(message: string, ...args: any[]) {
this.log('error', message, ...args);
}
log(level: LogLevel, message: string, ...args: any[]) {
this._debug.log = console[level].bind(console);
this._debug(`[${level.toUpperCase()}] ${message}`, ...args);
}
}