import { Injectable } from '@angular/core' ; import { GrowthBook , Experiment } from '@growthbook/growthbook' ; import { ConfigsService } from '../../common/services/configs.service' ; import { AnalyticsService } from '../../services/analytics' ; import { Session } from '../../services/session' ; import { CookieService } from '../../common/services/cookie.service' ; export { Experiment } from '@growthbook/growthbook' ; @ Injectable ( { providedIn : 'root' } ) export class ExperimentsService { growthbook : GrowthBook ; experiments : Experiment < unknown > [ ] = [ ] ; constructor ( private session , private configs , private analytics , private cookieService ) { } /**
     * Initialize Growthbook, only want to do this once
     */ initGrowthbook ( ) { if ( ! this . growthbook ) { const userId = this . getUserId ( ) ; this . growthbook = new GrowthBook ( { user : { id : userId } , trackingCallback : ( experiment , result ) => { /**
                     * Tracking is only called if force is not used.
                     */ this . addToAnalytics ( experiment . key , result . variationId ) ; } , } ) ; } const experiments = this . configs . get ( 'experiments' ) ; if ( experiments && experiments . length > 0 ) { for ( let experiment of experiments ) { const originExperiment = Object . assign ( experiment ) ; experiment = { key : experiment . experimentId , variations : experiment . variations , } ; if ( this . session . isLoggedIn ( ) ) { experiment . force = originExperiment . variationId ; } this . experiments . push ( experiment ) ; this . growthbook . run ( experiment ) ; if ( experiment . force != undefined ) { this . addToAnalytics ( experiment . key , experiment . force ) ; } } } } param { string } key throws returns { string } public run ( key ) { for ( let experiment of this . experiments ) { if ( experiment . key === key ) { const { value } = this . growthbook . run ( experiment ) ; return String ( value ) ; } } throw 'Could not find experiment with key ' + key ; } private addToAnalytics ( experimentId , variationId ) { this . analytics . contexts . push ( { schema : 'iglu:com.minds/growthbook_context/jsonschema/1-0-1' , data : { experiment_id : experimentId , variation_id : variationId , } , } ) ; } param { string } experimentId param { string } variation returns { boolean } public hasVariation ( experimentId , variation = 'on' ) { try { return this . run ( experimentId ) === variation ; } catch ( e ) { return false ; } } returns protected getUserId ( ) { if ( this . session . isLoggedIn ( ) ) { return this . session . getLoggedInUser ( ) ?. guid ; } const cookieName = 'experiments_id' ; let cookieValue = this . cookieService . get ( cookieName ) ; if ( ! cookieValue ) { cookieValue = 'exp-' + Math . random ( ) . toString ( 36 ) . substr ( 2 , 16 ) ; this . cookieService . put ( cookieName , cookieValue ) ; } return cookieValue ; } }