1
0
mirror of https://github.com/oceanprotocol-archive/squid-js.git synced 2024-02-02 15:31:51 +01:00
squid-js/src/Instantiable.abstract.ts

94 lines
2.5 KiB
TypeScript
Raw Normal View History

2019-06-20 00:20:09 +02:00
import * as Web3 from 'web3'
import Config from './models/Config'
import { Logger, LoggerInstance, LogLevel } from './utils'
import Web3Provider from './keeper/Web3Provider'
import { Ocean } from './ocean/Ocean'
export interface InstantiableConfig {
ocean: Ocean
config?: Config
web3?: Web3
logger?: Logger
}
2019-06-20 00:20:09 +02:00
export function generateIntantiableConfigFromConfig(
config: Config
): Partial<InstantiableConfig> {
const logLevel =
typeof config.verbose !== 'number'
? config.verbose
? LogLevel.Log
: LogLevel.None
: (config.verbose as LogLevel)
return {
config,
web3: Web3Provider.getWeb3(config),
2019-06-20 00:20:09 +02:00
logger: new Logger(logLevel)
}
}
export abstract class Instantiable {
protected get ocean() {
if (!this._ocean) {
2019-06-20 00:20:09 +02:00
this.logger.error('Ocean instance is not defined.')
}
return this._ocean
}
protected get web3() {
if (!this._web3) {
2019-06-20 00:20:09 +02:00
this.logger.error('Web3 instance is not defined.')
this.logger.error('Using default instance.')
return Web3Provider.getWeb3()
}
return this._web3
}
protected get config() {
if (!this._config) {
2019-06-20 00:20:09 +02:00
this.logger.error('Config instance is not defined.')
}
return this._config
}
protected get logger() {
if (!this._logger) {
2019-06-20 00:20:09 +02:00
LoggerInstance.error('Logger instance is not defined.')
LoggerInstance.error('Using default instance.')
return LoggerInstance
}
return this._logger
}
protected get instanceConfig(): InstantiableConfig {
2019-06-20 00:20:09 +02:00
const { ocean, web3, config, logger } = this
return { ocean, web3, config, logger }
}
2019-03-21 03:17:36 +01:00
public static async getInstance(...args: any[]): Promise<any>
public static async getInstance(config: InstantiableConfig): Promise<any> {
2019-06-20 00:20:09 +02:00
LoggerInstance.warn(
'getInstance() methods has needs to be added to child class.'
)
2019-03-21 03:17:36 +01:00
}
2019-06-20 00:20:09 +02:00
protected static setInstanceConfig<T extends Instantiable>(
instance: T,
{ ocean, config, web3, logger }: InstantiableConfig
) {
instance._ocean = ocean
instance._config = config
instance._web3 = web3
instance._logger = logger
}
2019-03-21 03:17:36 +01:00
private _ocean: Ocean
private _web3: Web3
private _config: Config
private _logger: Logger
protected setInstanceConfig(config: InstantiableConfig) {
Instantiable.setInstanceConfig(this, config)
}
}