Skip to content

Commit

Permalink
feat(js): read config from file (#1250)
Browse files Browse the repository at this point in the history
  • Loading branch information
subzero10 authored Nov 17, 2023
1 parent 866bb8d commit 936374c
Show file tree
Hide file tree
Showing 3 changed files with 163 additions and 8 deletions.
16 changes: 11 additions & 5 deletions packages/js/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import { CheckinsConfig } from './server/checkins-manager/types'
import { CheckinsClient } from './server/checkins-manager/client';

const { endpoint } = Util
const DEFAULT_PLUGINS = [
uncaughtException(),
unhandledRejection()
]

type HoneybadgerServerConfig = (Types.Config | Types.ServerlessConfig) & CheckinsConfig

Expand Down Expand Up @@ -61,8 +65,13 @@ class Honeybadger extends Client {
}

factory(opts?: Partial<HoneybadgerServerConfig>): this {
const clone = new Honeybadger({
// fixme: this can create unwanted side-effects, needs to be tested thoroughly before enabling
// __plugins: DEFAULT_PLUGINS,
...(readConfigFromFileSystem() ?? {}),
...opts,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const clone = new Honeybadger(opts) as any
}) as any
clone.setNotifier(this.getNotifier())

return clone
Expand Down Expand Up @@ -160,10 +169,7 @@ class Honeybadger extends Client {
}

const singleton = new Honeybadger({
__plugins: [
uncaughtException(),
unhandledRejection()
],
__plugins: DEFAULT_PLUGINS,
...(readConfigFromFileSystem() ?? {})
})

Expand Down
12 changes: 9 additions & 3 deletions packages/js/src/server/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,14 @@ export function readConfigFromFileSystem(): Record<string, unknown> {
}

function readConfigForModule(moduleName: string): Record<string, unknown> {
const fileExplorer = cosmiconfigSync(moduleName)
const result = fileExplorer.search()
try {
const fileExplorer = cosmiconfigSync(moduleName)
const result = fileExplorer.search()

return result?.config ?? null
return result?.config ?? null
}
catch (e) {
console.debug(`[Honeybadger] Could not read config for module ${moduleName}: ${e.message}`)
return null
}
}
143 changes: 143 additions & 0 deletions packages/js/test/unit/server.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,32 @@
import { Client as BaseClient } from '@honeybadger-io/core'
import os from 'os';
import path from 'path';
import nock from 'nock'
import Singleton from '../../src/server'
import { nullLogger } from './helpers'
import { CheckinDto, CheckinResponsePayload } from '../../src/server/checkins-manager/types';
import { Checkin } from '../../src/server/checkins-manager/checkin';
import { cosmiconfigSync } from 'cosmiconfig'

const configPath = path.resolve(__dirname, '../../', 'honeybadger.config.js')
jest.mock('cosmiconfig', () => ({
cosmiconfigSync: jest.fn().mockImplementation((_moduleName, _options) => {
return {
load: jest.fn(),
clearCaches: jest.fn(),
clearLoadCache: jest.fn(),
clearSearchCache: jest.fn(),
search: () => {
return {
isEmpty: true,
config: {},
filepath: null
}
}
}
})
}))
const mockCosmiconfig = cosmiconfigSync as jest.MockedFunction<typeof cosmiconfigSync>

describe('server client', function () {
let client: typeof Singleton
Expand All @@ -15,6 +38,126 @@ describe('server client', function () {
})
})

afterEach(() => {
jest.resetAllMocks()
})

describe('configuration', function () {
it('creates a client with default configuration', function () {
const client = Singleton.factory()
expect(client.config).toMatchObject({
apiKey: null,
endpoint: 'https://api.honeybadger.io',
environment: null,
projectRoot: process.cwd(),
hostname: os.hostname(),
component: null,
action: null,
revision: null,
reportData: null,
breadcrumbsEnabled: true,
maxBreadcrumbs: 40,
maxObjectDepth: 8,
logger: console,
developmentEnvironments: ['dev', 'development', 'test'],
debug: false,
tags: null,
enableUncaught: true,
enableUnhandledRejection: true,
reportTimeoutWarning: true,
timeoutWarningThresholdMs: 50,
filters: ['creditcard', 'password'],
__plugins: [],
})
})

it('creates a client with constructor arguments', function () {
const opts = {
apiKey: 'testing',
environment: 'staging',
developmentEnvironments: ['staging', 'dev', 'local'],
tags: ['tag-1', 'tag-2']
}
const client = Singleton.factory(opts)
expect(client.config).toMatchObject(opts)
})

it('creates a client from a configuration file', function () {
const configFromFile = {
apiKey: 'testing',
personalAuthToken: 'p123',
environment: 'staging',
developmentEnvironments: ['staging', 'dev', 'local'],
tags: ['tag-1', 'tag-2'],
checkins: [
{
projectId: '11111',
name: 'a check-in',
scheduleType: 'simple',
reportPeriod: '1 week',
gracePeriod: '5 minutes'
}
]
}
mockCosmiconfig.mockImplementation((_moduleName, _options) => {
return {
load: jest.fn(),
clearCaches: jest.fn(),
clearLoadCache: jest.fn(),
clearSearchCache: jest.fn(),
search: () => {
return {
config: configFromFile,
filepath: configPath
}
}
}
})
const client = Singleton.factory()
expect(client.config).toMatchObject(configFromFile)
})

it('creates a client from both a configuration file and constructor arguments', function () {
const configFromFile = {
apiKey: 'testing',
personalAuthToken: 'p123',
environment: 'staging',
developmentEnvironments: ['staging', 'dev', 'local'],
tags: ['tag-1', 'tag-2'],
checkins: [
{
projectId: '11111',
name: 'a check-in',
scheduleType: 'simple',
reportPeriod: '1 week',
gracePeriod: '5 minutes'
}
]
}
mockCosmiconfig.mockImplementation((_moduleName, _options) => {
return {
load: jest.fn(),
clearCaches: jest.fn(),
clearLoadCache: jest.fn(),
clearSearchCache: jest.fn(),
search: () => {
return {
config: configFromFile,
filepath: configPath
}
}
}
})
const client = Singleton.factory({
apiKey: 'not-testing'
})
expect(client.config).toMatchObject({
...configFromFile,
apiKey: 'not-testing'
})
})
})

it('inherits from base client', function () {
expect(client).toEqual(expect.any(BaseClient))
})
Expand Down

0 comments on commit 936374c

Please sign in to comment.