Skip to content

Commit

Permalink
fix(logger): remove chalk from proxy api to reduce bundle size (#208)
Browse files Browse the repository at this point in the history
perf(logger): remove package chalk from client side
  • Loading branch information
neo-reply-lukas authored Apr 11, 2024
1 parent e51cdb2 commit 5e84078
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 37 deletions.
5 changes: 3 additions & 2 deletions src/integrations/endpointIntegrationWrapper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { HttpError } from '../exceptions'
import { FSXARemoteApi, Logger } from '../modules'
import { FSXARemoteApi } from '../modules'
import {
FetchByFilterBody,
FetchElementRouteBody,
Expand All @@ -19,6 +19,7 @@ import {
NormalizedProjectPropertyResponse,
ProjectProperties,
} from '../types'
import { LoggerChalked } from '../modules/LoggerChalked'

export type FetchWrapperResult<T = any> =
| FetchWrapperSuccess<T>
Expand Down Expand Up @@ -64,7 +65,7 @@ export const useEndpointIntegrationWrapper = (
api: FSXARemoteApi,
loggerName = 'Endpoint-Utils'
) => {
const logger = new Logger(api.logLevel, loggerName)
const logger = new LoggerChalked(api.logLevel, loggerName)

/**
* Fetches an Element by Id via {@link FSXARemoteApi}
Expand Down
3 changes: 2 additions & 1 deletion src/integrations/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
FetchWrapperResult,
useEndpointIntegrationWrapper,
} from './endpointIntegrationWrapper'
import { LoggerChalked } from '../modules/LoggerChalked'

export interface GetExpressRouterContext {
api: FSXARemoteApi
Expand Down Expand Up @@ -69,7 +70,7 @@ const sendUnexpectedError = (

function getExpressRouter({ api }: GetExpressRouterContext) {
const router = express.Router()
const logger = new Logger(api.logLevel, 'Express-Server')
const logger = new LoggerChalked(api.logLevel, 'Express-Server')
const wrappers = useEndpointIntegrationWrapper(api, 'Express-Server')

router.use(express.json())
Expand Down
32 changes: 25 additions & 7 deletions src/modules/CaaSEventStream.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { Channel, createChannel, createSession } from 'better-sse'
import { FSXARemoteApi, Logger } from './'
import ReconnectingWebSocket, { Options, ErrorEvent } from 'reconnecting-websocket'
import ReconnectingWebSocket, {
Options,
ErrorEvent,
} from 'reconnecting-websocket'
import WebSocket from 'ws'
import { Request, Response } from 'express'
import { LoggerChalked } from './LoggerChalked'

type SocketUrl = () => Promise<string>

Expand All @@ -16,7 +20,11 @@ class CaaSEventStream {
channel: Channel
socket: ReconnectingWebSocket

constructor(logger: Logger, createSocketUrl: SocketUrl, options: Options = {}) {
constructor(
logger: Logger,
createSocketUrl: SocketUrl,
options: Options = {}
) {
this.logger = logger
this.createSocketUrl = createSocketUrl

Expand Down Expand Up @@ -45,7 +53,11 @@ class CaaSEventStream {
this.socket.readyState === ReconnectingWebSocket.OPEN ||
this.socket.readyState === ReconnectingWebSocket.CONNECTING

this.logger.info('onCheckState', 'activeSessions', this.channel.activeSessions.length)
this.logger.info(
'onCheckState',
'activeSessions',
this.channel.activeSessions.length
)

if (hasSessions && !isSocketOpenOrConnecting) {
this.socket.reconnect()
Expand All @@ -63,16 +75,19 @@ class CaaSEventStream {

// add a new event-stream (session)
addSession(req: Request, res: Response) {
const serializer = (data: any) => (typeof data === 'string' ? data : JSON.stringify(data))
createSession(req, res, { serializer }).then((session) => this.channel.register(session))
const serializer = (data: any) =>
typeof data === 'string' ? data : JSON.stringify(data)
createSession(req, res, { serializer }).then((session) =>
this.channel.register(session)
)
}
}

const streams: Record<string, CaaSEventStream> = {}

export const eventStreamHandler = (api: FSXARemoteApi) => {
return async (req: Request, res: Response) => {
const logger = new Logger(api.logLevel, 'CaaSEventStream')
const logger = new LoggerChalked(api.logLevel, 'CaaSEventStream')
logger.info('requesting route: ', req.url, req.query)

let remoteProject
Expand All @@ -85,7 +100,10 @@ export const eventStreamHandler = (api: FSXARemoteApi) => {
if (!(caasUrl in streams)) {
const createSocketUrl = async () => {
const token = await api.fetchSecureToken()
const socketUrl = `${caasUrl.replace(/^http/, 'ws')}/_streams/crud?securetoken=${token}`
const socketUrl = `${caasUrl.replace(
/^http/,
'ws'
)}/_streams/crud?securetoken=${token}`
logger.info('createSocketUrl', 'socketUrl', socketUrl)
return socketUrl
}
Expand Down
6 changes: 3 additions & 3 deletions src/modules/CaaSMapper.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import faker from 'faker'
import { CaaSMapper, CaaSMapperErrors } from './CaaSMapper'
import { FSXARemoteApi } from './FSXARemoteApi'
import { Logger, LogLevel } from './Logger'
import { LogLevel } from './Logger'
import { FSXAContentMode } from '../enums'
import {
CaaSApi_Body,
Expand Down Expand Up @@ -57,14 +57,14 @@ import {
Reference,
} from '..'
import { createFetchResponse } from '../testutils/createFetchResponse'
import { createPageRefBody } from '../testutils'
import { LoggerChalked } from './LoggerChalked'

jest.mock('./FSXARemoteApi')
jest.mock('date-fns')

describe('CaaSMapper', () => {
const createPath = () => [faker.random.word(), faker.random.word()]
const createLogger = () => new Logger(LogLevel.NONE, 'Querybuilder')
const createLogger = () => new LoggerChalked(LogLevel.NONE, 'Querybuilder')
const createApi = () =>
jest.mocked<FSXARemoteApi>(new (FSXARemoteApi as any)())
const createMapper = () =>
Expand Down
3 changes: 2 additions & 1 deletion src/modules/FSXARemoteApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { LogLevel } from './Logger'
import { denormalizeResolvedReferences } from './MappingUtils'
import { ComparisonQueryOperatorEnum, QueryBuilder } from './QueryBuilder'
import { HttpError } from '../exceptions'
import { LoggerChalked } from './LoggerChalked'

type buildNavigationServiceURLParams = {
locale?: string
Expand Down Expand Up @@ -113,7 +114,7 @@ export class FSXARemoteApi implements FSXAApi {
this._maxReferenceDepth = maxReferenceDepth
this._customMapper = customMapper
this._logLevel = logLevel
this._logger = new Logger(logLevel, 'FSXARemoteApi')
this._logger = new LoggerChalked(logLevel, 'FSXARemoteApi')
this._queryBuilder = new QueryBuilder(this._logger)
this._navigationItemFilter = filterOptions?.navigationItemFilter
this._caasItemFilter = filterOptions?.caasItemFilter
Expand Down
41 changes: 23 additions & 18 deletions src/modules/Logger.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import chalk from 'chalk'
import type { Chalk } from 'chalk'
import { inspect } from 'util'

export enum LogLevel {
Expand Down Expand Up @@ -42,13 +42,18 @@ const formatOutput = (...args: any[]) => {
breakLength: Infinity,
}).replace(/\'/g, '')
}

const identity = (text: string) => text

export class Logger {
private _logLevel: LogLevel
private _name: string
private chalk: Chalk | undefined

constructor(logLevel: LogLevel, name: string) {
constructor(logLevel: LogLevel, name: string, chalk?: Chalk) {
this._logLevel = logLevel
this._name = name
this.chalk = chalk
}

get logLevel() {
Expand All @@ -58,10 +63,10 @@ export class Logger {
debug(...args: any[]) {
if (this._logLevel <= LogLevel.DEBUG) {
console.info(
chalk.gray(
`${chalk.bgWhite.black(' DEBUG ')} ${this._name} | ${formatOutput(
...args
)}`
(this.chalk?.gray || identity)(
`${(this.chalk?.bgWhite.black || identity)(' DEBUG ')} ${
this._name
} | ${formatOutput(...args)}`
)
)
}
Expand All @@ -74,10 +79,10 @@ export class Logger {
info(...args: any[]) {
if (this._logLevel <= LogLevel.INFO) {
console.info(
chalk.blue(
`${chalk.bgBlue.white(' INFO ')} ${this._name} | ${formatOutput(
...args
)}`
(this.chalk?.blue || identity)(
`${(this.chalk?.bgBlue.white || identity)(' INFO ')} ${
this._name
} | ${formatOutput(...args)}`
)
)
}
Expand All @@ -86,10 +91,10 @@ export class Logger {
warn(...args: any[]) {
if (this._logLevel <= LogLevel.WARNING) {
console.warn(
chalk.yellow(
`${chalk.bgYellow.black(' WARN ')} ${this._name} | ${formatOutput(
...args
)}`
(this.chalk?.yellow || identity)(
`${(this.chalk?.bgYellow.black || identity)(' WARN ')} ${
this._name
} | ${formatOutput(...args)}`
)
)
}
Expand All @@ -98,10 +103,10 @@ export class Logger {
error(...args: any[]) {
if (this._logLevel <= LogLevel.ERROR) {
console.error(
chalk.red(
`${chalk.bgRed.black(' ERROR ')} ${this._name} | ${formatOutput(
...args
)}`
(this.chalk?.red || identity)(
`${(this.chalk?.bgRed.black || identity)(' ERROR ')} ${
this._name
} | ${formatOutput(...args)}`
)
)
}
Expand Down
13 changes: 13 additions & 0 deletions src/modules/LoggerChalked.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import chalk from 'chalk'
import { LogLevel, Logger } from './Logger'

/**
* Provides Coloring of Logs via Chalk package.
* split from Logger because of Bundle Optimization.
* Usage on client side increases Bundle Size by ~20KB
*/
export class LoggerChalked extends Logger {
constructor(logLevel: LogLevel, name: string) {
super(logLevel, name, chalk)
}
}
6 changes: 4 additions & 2 deletions src/modules/QueryBuilder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import {
LogicalQueryOperatorEnum,
EvaluationQueryOperatorEnum,
QueryBuilderErrors,
Logger,
LogLevel,
} from '.'
import { MappedFilter } from '../types'
import { LoggerChalked } from './LoggerChalked'

const builder = new QueryBuilder(new Logger(LogLevel.NONE, 'Querybuilder'))
const builder = new QueryBuilder(
new LoggerChalked(LogLevel.NONE, 'Querybuilder')
)
const foobar = 'foobar'

describe('QueryBuilder', () => {
Expand Down
1 change: 0 additions & 1 deletion src/modules/QueryBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { MappedFilter, QueryBuilderQuery } from '../types'
import { Logger } from './Logger'
import { isValidRegex } from '../utils'
import { isGeneratorFunction } from 'util/types'

export enum ComparisonQueryOperatorEnum {
GREATER_THAN_EQUALS = '$gte',
Expand Down
5 changes: 3 additions & 2 deletions src/modules/XMLParser.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Logger, LogLevel } from './'
import { LogLevel } from './'
import { LoggerChalked } from './LoggerChalked'
import XMLParser from './XMLParser'

describe('XMLParser', () => {
const logger = new Logger(LogLevel.ERROR, 'XMLParserTest')
const logger = new LoggerChalked(LogLevel.ERROR, 'XMLParserTest')
const xmlParser = new XMLParser(logger)

it('should log an error on incorrect XML', async () => {
Expand Down

0 comments on commit 5e84078

Please sign in to comment.