Skip to content

Commit bd5a285

Browse files
committed
feat: SessionDuration integration
1 parent de9b23a commit bd5a285

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

packages/integrations/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ export { Ember } from './ember';
66
export { ExtraErrorData } from './extraerrordata';
77
export { ReportingObserver } from './reportingobserver';
88
export { RewriteFrames } from './rewriteframes';
9+
export { SessionDuration } from './sessionduration';
910
export { Tracing } from './tracing';
1011
export { Transaction } from './transaction';
1112
export { Vue } from './vue';
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { Event, EventProcessor, Hub, Integration } from '@sentry/types';
2+
3+
/** This function adds duration since Sentry was initialized till the time event was sent */
4+
export class SessionDuration implements Integration {
5+
/**
6+
* @inheritDoc
7+
*/
8+
public name: string = SessionDuration.id;
9+
/**
10+
* @inheritDoc
11+
*/
12+
public static id: string = 'SessionDuration';
13+
14+
/** Exact time Client was initialized expressed in milliseconds since Unix Epoch. */
15+
protected readonly _startTime: number = Date.now();
16+
17+
/**
18+
* @inheritDoc
19+
*/
20+
public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {
21+
addGlobalEventProcessor(event => {
22+
const self = getCurrentHub().getIntegration(SessionDuration);
23+
if (self) {
24+
return self.process(event);
25+
}
26+
return event;
27+
});
28+
}
29+
30+
/**
31+
* @inheritDoc
32+
*/
33+
public process(event: Event): Event {
34+
return {
35+
...event,
36+
extra: {
37+
...event.extra,
38+
['session:duration']: Date.now() - this._startTime,
39+
},
40+
};
41+
}
42+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { SessionDuration } from '../src/sessionduration';
2+
3+
describe('SessionDuration', () => {
4+
it('should work as expected', done => {
5+
const sessionDuration: SessionDuration = new SessionDuration();
6+
7+
// Juuust in case so we know that 1ms passes
8+
setTimeout(() => {
9+
const event = sessionDuration.process({
10+
extra: {
11+
some: 'value',
12+
},
13+
});
14+
expect(event.extra!['session:duration']).toBeGreaterThan(0);
15+
expect(typeof event.extra!['session:duration']).toBe('number');
16+
expect(event.extra!.some).toEqual('value');
17+
done();
18+
}, 1);
19+
});
20+
});

0 commit comments

Comments
 (0)