All files / src/services time-service.ts

100% Statements 6/6
100% Branches 0/0
100% Functions 3/3
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                                                              2x 6x 6x   6x     6x 6x        
import { Logger } from '../utils/logger';
 
/**
 * Service interface for managing server time synchronization.
 * Provides methods to get and set the current server time, accounting for
 * the time difference between client and server.
 */
export interface TimeService {
    /**
     * Gets the current server time, adjusted for the client-server time delta.
     *
     * @returns Current server time in milliseconds
     */
    get serverTime(): number;
 
    /**
     * Sets the server time and calculates the delta with the local time.
     * This delta is then used to adjust future time calculations.
     *
     * @param value - The server time to synchronize with
     */
    set serverTime(value: number);
}
 
/**
 * Factory function that creates and returns an implementation of the TimeService interface.
 * Maintains the time difference between client and server for time synchronization.
 *
 * @param logger - Logger instance for debugging information
 * @returns An implementation of the TimeService interface
 */
export function getTimeService(logger: Logger): TimeService {
    let serverTimeDelta = 0;
    return {
        get serverTime(): number {
            return Date.now() + serverTimeDelta;
        },
        set serverTime(value: number) {
            serverTimeDelta = value - Date.now();
            logger.debug(`[time-service] Server time delta has been set to: ${serverTimeDelta}ms`);
        },
    };
}