import { ISequencedDocumentMessage , MessageType } from "@fluidframework/protocol-definitions" ; import { IFluidDataStoreRuntime , IChannelStorageService , IChannelFactory , } from "@fluidframework/datastore-definitions" ; import { readAndParse } from "@fluidframework/driver-utils" ; import { ISummaryTreeWithStats } from "@fluidframework/runtime-definitions" ; import { createSingleBlobSummary , IFluidSerializer , SharedObject } from "@fluidframework/shared-object-base" ; import { CounterFactory } from "./counterFactory" ; import { ISharedCounter , ISharedCounterEvents } from "./interfaces" ; /**
 * Describes the op format for incrementing the counter
 */ interface IIncrementOperation { type : "increment" ; incrementAmount : number ; } /**
 * Used in snapshotting.
 */ interface ICounterSnapshotFormat { value : number ; } const snapshotFileName = "header" ; public remarks export class SharedCounter extends SharedObject < ISharedCounterEvents > implements ISharedCounter { param runtime param id returns public static create ( runtime , id ? ) { return runtime . createChannel ( id , CounterFactory . Type ) as SharedCounter ; } returns public static getFactory ( ) { return new CounterFactory ( ) ; } private _value : number = 0 ; /**
     * {@inheritDoc ISharedCounter.value}
     */ public get value ( ) { return this . _value ; } /**
     * {@inheritDoc ISharedCounter.increment}
     */ public increment ( incrementAmount ) { if ( incrementAmount % 1 !== 0 ) { throw new Error ( "Must increment by a whole number" ) ; } const op = { type : "increment" , incrementAmount } ; this . incrementCore ( incrementAmount ) ; this . submitLocalMessage ( op ) ; } private incrementCore ( incrementAmount ) { this . _value += incrementAmount ; this . emit ( "incremented" , incrementAmount , this . _value ) ; } returns internal protected summarizeCore ( serializer ) { const content = { value : this . value } ; return createSingleBlobSummary ( snapshotFileName , JSON . stringify ( content ) ) ; } internal protected async loadCore ( storage ) { const content = await readAndParse < ICounterSnapshotFormat > ( storage , snapshotFileName ) ; this . _value = content . value ; } internal protected registerCore ( ) { } internal protected onDisconnect ( ) { } param message param local param localOpMetadata internal protected processCore ( message , local , localOpMetadata ) { if ( message . type === MessageType . Operation && ! local ) { const op = message . contents as IIncrementOperation ; switch ( op . type ) { case "increment" : this . incrementCore ( op . incrementAmount ) ; break ; default : throw new Error ( "Unknown operation" ) ; } } } internal protected applyStashedOp ( ) { throw new Error ( "not implemented" ) ; } }