Skip to content

Commit

Permalink
Types: Add types to analytics module, fix module syntax (#1883)
Browse files Browse the repository at this point in the history
The analytics module has been using a commonJS format and has been working "by accident"
because `webpack` properly translates the import/export syntax.

```js
// moduleA.js
const stuff = {
	thing: 5;
}

module.exports = stuff;

// moduleB.js
import { thing } from 'moduleA'
```

^^^ that shouldn't work but it has been. This has been resolved in this commit.
  • Loading branch information
dmsnell authored Feb 25, 2020
1 parent dafff35 commit 81a221e
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 105 deletions.
34 changes: 26 additions & 8 deletions lib/analytics/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,23 @@ const debug = require('debug')('analytics');
/**
* Internal dependencies
*/
var user;
require('./tracks');
import './tracks';
import { TKQItem } from './tracks';
let user: string;

import * as T from '../types';

declare global {
interface Window {
analyticsEnabled: boolean;
_tkq: TKQItem[];
}
}

declare const config: { version: string };

const analytics = {
initialize: function(initUser) {
initialize: function(initUser: string) {
analytics.setUser(initUser);
analytics.identifyUser();
},
Expand All @@ -28,12 +40,15 @@ const analytics = {
return null;
},

setUser: function(newUser) {
setUser: function(newUser: string) {
user = newUser;
},

tracks: {
recordEvent: function(eventName, eventProperties) {
recordEvent: function(
eventName: string,
eventProperties: T.JSONSerializable = {}
) {
const prefix = analytics.getPlatformPrefix();

const fullEventName = `${prefix}_${eventName}`;
Expand All @@ -53,7 +68,10 @@ const analytics = {
window._tkq.push(['recordEvent', fullEventName, fullEventProperties]);
}
},
validateEvent: function(fullEventName, fullEventProperties) {
validateEvent: function(
fullEventName: string,
fullEventProperties: T.JSONSerializable
) {
if (process.env.NODE_ENV !== 'development') {
return;
}
Expand All @@ -76,7 +94,7 @@ const analytics = {

identifyUser: function() {
// Don't identify the user if we don't have one
if (user) {
if (undefined !== user) {
window._tkq.push(['identifyUser', user, user]);
}
},
Expand All @@ -89,4 +107,4 @@ const analytics = {
// Load tracking script
window._tkq = window._tkq || [];

module.exports = analytics;
export default analytics;
Loading

0 comments on commit 81a221e

Please sign in to comment.