Skip to content
This repository has been archived by the owner on Sep 8, 2023. It is now read-only.

Fix: Optimize client creation #42

Merged
merged 1 commit into from
Jul 9, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,33 +32,39 @@ const create = function (servicename, overrides = {}) {
throw new Error('A service name is required')
}

// Were no overrides passed?
const noOverrides = !Object.keys(overrides).length

// Look for an existing client w/ the specified service name
let client = GlobalConfig.clientInstances[servicename]

// If no overrides are passed and a client already exists, return it
if (noOverrides && client) {
return client
}

// Come up with the new client's configuration
const base = Hoek.applyToDefaults(GlobalConfig.base, GlobalConfig.overrides[servicename] || {}, { shallow: ['agent'] })
const merged = Hoek.applyToDefaults(base, overrides, { shallow: ['agent'] })

const config = Schema.validateCreate(servicename, merged)

// If an agent was not included in the overrides, create one and add it to the config
// istanbul ignore else */
if (!config.agent) {
config.agent = Agent.create(config.protocol, config)
}

// If overrides are passed do not cache the client
if (Object.keys(overrides).length) {
const client = new Client(servicename, config)
// Create a new client
client = new Client(servicename, config)
debug('create(): created client id %s for service %s', client.id, servicename)

debug('create(): created client id %s for service %s', client.id, servicename)

return client
// If no overrides are passed, cache the new client
if (noOverrides) {
GlobalConfig.clientInstances[servicename] = client
}

// If the client is not already cached create an instance and cache
if (typeof GlobalConfig.clientInstances[servicename] === 'undefined') {
GlobalConfig.clientInstances[servicename] = new Client(servicename, config)
}

debug('create(): created client id %s for service %s', GlobalConfig.clientInstances[servicename].id, servicename)

return GlobalConfig.clientInstances[servicename]
// Return the new client
return client
}

const remove = function (servicename) {
Expand Down