import { getCredentials } from "../credentials/channel" ; import Credentials from "../credentials/Credentials" ; import TextDatasource from "./TextDatasource" ; const __datasources = { } ; const __datasourceFlags = { } ; const __postHandlers = [ ] ; param credentials throws throws throws private export function credentialsToDatasource ( credentials ) { const { datasource } = getCredentials ( credentials . id ) . data ; if ( ! datasource ) { throw new Error ( "No datasource configuration in credentials" ) ; } const { type } = datasource ; if ( ! type ) { throw new Error ( "No datasource type specified in datasource configuration" ) ; } const DSClass = __datasources [ type ] ; if ( ! DSClass ) { throw new Error ( `No datasource found for type: ${ type }` ) ; } return new DSClass ( prepareDatasourceCredentials ( credentials ) ) ; } param type param datasource private export function fireInstantiationHandlers ( type , datasource ) { __postHandlers . forEach ( handler => { try { handler ( type , datasource ) ; } catch ( err ) { console . error ( "Failed executing a datasource instantiation handler for a datasource" ) ; console . error ( err ) ; } } ) ; } param credentials private export function prepareDatasourceCredentials ( credentials , typeOverride = null ) { const { data : { datasource } , masterPassword } = getCredentials ( credentials . id ) ; const datasourceType = typeOverride || datasource . type || "" ; const { open = false } = __datasourceFlags [ datasourceType ] || { } ; if ( ! open ) { return credentials ; } const newCreds = Credentials . fromCredentials ( credentials , masterPassword ) ; const newCredPayload = getCredentials ( newCreds . id ) ; newCredPayload . open = true ; return newCreds ; } param datasourceType param DSClass memberof export function registerDatasource ( datasourceType , DSClass , flags = { } ) { if ( __datasources [ datasourceType ] ) { throw new Error ( `Datasource already registered for type: ${ datasourceType }` ) ; } __datasources [ datasourceType ] = DSClass ; __datasourceFlags [ datasourceType ] = flags ; } interface DatasourcePostProcessorHandler { remove : ( ) => void ; } param { Function } callback returns private export function registerDatasourcePostProcessor ( callback ) { __postHandlers . push ( callback ) ; return { remove : ( ) => { const ind = __postHandlers . indexOf ( callback ) ; if ( ind >= 0 ) { __postHandlers . splice ( ind , 1 ) ; } } } ; }