( timestamp: FastifyRequest['timestamp'], payload: ITrackHandlerPayload['payload'] )
| 97 | } |
| 98 | |
| 99 | export function getTimestamp( |
| 100 | timestamp: FastifyRequest['timestamp'], |
| 101 | payload: ITrackHandlerPayload['payload'] |
| 102 | ) { |
| 103 | const safeTimestamp = timestamp || Date.now(); |
| 104 | const userDefinedTimestamp = |
| 105 | 'properties' in payload |
| 106 | ? (payload?.properties?.__timestamp as string | undefined) |
| 107 | : undefined; |
| 108 | |
| 109 | if (!userDefinedTimestamp) { |
| 110 | return { timestamp: safeTimestamp, isTimestampFromThePast: false }; |
| 111 | } |
| 112 | |
| 113 | const clientTimestamp = new Date(userDefinedTimestamp); |
| 114 | const clientTimestampNumber = clientTimestamp.getTime(); |
| 115 | |
| 116 | // Constants for time validation |
| 117 | const ONE_MINUTE_MS = 60 * 1000; |
| 118 | const FIFTEEN_MINUTES_MS = 15 * ONE_MINUTE_MS; |
| 119 | |
| 120 | // Use safeTimestamp if invalid or more than 1 minute in the future |
| 121 | if ( |
| 122 | Number.isNaN(clientTimestampNumber) || |
| 123 | clientTimestampNumber > safeTimestamp + ONE_MINUTE_MS |
| 124 | ) { |
| 125 | return { timestamp: safeTimestamp, isTimestampFromThePast: false }; |
| 126 | } |
| 127 | |
| 128 | // isTimestampFromThePast is true only if timestamp is older than 15 minutes |
| 129 | const isTimestampFromThePast = |
| 130 | clientTimestampNumber < safeTimestamp - FIFTEEN_MINUTES_MS; |
| 131 | |
| 132 | return { |
| 133 | timestamp: clientTimestampNumber, |
| 134 | isTimestampFromThePast, |
| 135 | }; |
| 136 | } |
| 137 | |
| 138 | interface TrackContext { |
| 139 | projectId: string; |
no outgoing calls
no test coverage detected