Skip to content

Instantly share code, notes, and snippets.

@patrickt010
Last active July 9, 2019 00:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickt010/f3a8a5e2c103ab6f38791ca4314185b5 to your computer and use it in GitHub Desktop.
Save patrickt010/f3a8a5e2c103ab6f38791ca4314185b5 to your computer and use it in GitHub Desktop.
/* tslint:disable */
const GoogleAnalytics = require('universal-analytics');
const Amplitude = require('amplitude');
const Mixpanel = require('mixpanel');
const Segment = require('analytics-node');
const Ajv = require('ajv');
export interface ContextProperties {
/**
* Some context prop.
*/
contextProp: string;
}
export interface IdentifyProperties {
/**
* User's last name.
*/
lastName: string;
/**
* User's first name.
*/
firstName: number;
}
export interface GroupProperties {
/**
* The number of members in the group.
*/
size: number;
/**
* The group's name.
*/
name: string;
}
export interface PageProperties {}
export interface ScreenProperties {}
export interface CommandFailedProperties {
/**
* The name of the command.
*/
name: string;
}
export interface CommandRanProperties {
/**
* The name of the command.
*/
name: string;
}
export interface ItlyOptions {
env?: 'dev' | 'prod';
disabled?: boolean;
destinations?: { ga?: { config?: {} }, amplitude?: { config?: {} }, mixpanel?: { config?: {} }, segment?: { config?: {} } };
context?: ContextProperties | (() => ContextProperties);
logger?: { debug: (message: string) => void; info: (message: string) => void; warn: (message: string) => void; error: (message: string) => void; };
}
class Itly {
private inited = false;
private options: ItlyOptions = {};
private ga: any;
private amplitude: any;
private mixpanel: any;
private segment: any;
private readonly ajv = new Ajv();
private readonly validators = {
'Context': this.ajv.compile({"title":"Context","type":"object","properties":{"contextProp":{"type":"string","description":"Some context prop."}},"additionalProperties":false,"required":["contextProp"]}),
'Identify': this.ajv.compile({"title":"Identify","type":"object","properties":{"lastName":{"type":"string","description":"User's last name."},"firstName":{"type":"integer","description":"User's first name.","minimum":3,"maximum":5,"minLength":2}},"additionalProperties":false,"required":["lastName","firstName"]}),
'Group': this.ajv.compile({"title":"Group","type":"object","properties":{"size":{"type":"integer","description":"The number of members in the group.","minimum":0},"name":{"type":"string","description":"The group's name.","minLength":2}},"additionalProperties":false,"required":["size","name"]}),
'Page': this.ajv.compile({"title":"Page","type":"object","properties":{},"additionalProperties":false,"required":[]}),
'Screen': this.ajv.compile({"title":"Screen","type":"object","properties":{},"additionalProperties":false,"required":[]}),
'CommandFailed': this.ajv.compile({"$id":"http://iterative.ly/company/0f45aaca-d07e-457a-9599-fb4fba3f5e24/event/12f12b2b-dc0c-4ff5-9602-89f21468a752","$schema":"http://json-schema.org/draft-07/schema#","title":"Command Failed","description":"Called when a command fails.","type":"object","properties":{"name":{"description":"The name of the command.","type":"string"}},"additionalProperties":false,"required":["name"]}),
'CommandRan': this.ajv.compile({"$id":"http://iterative.ly/company/0f45aaca-d07e-457a-9599-fb4fba3f5e24/event/e6ac7a63-e73d-4964-ae29-7d8ef989e58c","$schema":"http://json-schema.org/draft-07/schema#","title":"Command Ran","description":"Called when a command runs.","type":"object","properties":{"name":{"description":"The name of the command.","type":"string","minLength":2}},"additionalProperties":false,"required":["name"]}),
};
private throwOrLog(message: string) {
if (this.options.env === 'prod') {
if (this.options.logger) {
this.options.logger.error(message);
}
else {
console.error(message);
}
}
else {
throw new Error(message);
}
}
init(options: ItlyOptions = {}) {
if (this.inited) {
this.throwOrLog('Itly is already initialized.');
}
this.inited = true;
this.options = options;
this.ga = GoogleAnalytics(this.options.env === 'prod' ? 'UA-118251069-2' : 'UA-118251069-2', /* client id */);
this.amplitude = new Amplitude(this.options.env === 'prod' ? '17928187f8f09a3fd719ab59c3009858' : '17928187f8f09a3fd719ab59c3009858');
this.mixpanel = Mixpanel.init(this.options.env === 'prod' ? 'dc84694107ea11a77577422f76a3c150' : 'dc84694107ea11a77577422f76a3c150', this.options.destinations && this.options.destinations.mixpanel && this.options.destinations.mixpanel.config);
this.segment = new Segment(this.options.env === 'prod' ? 'kjOVDepZmpHx5eWteMqZb5J9LZaVbsMa' : 'kjOVDepZmpHx5eWteMqZb5J9LZaVbsMa', this.options.destinations && this.options.destinations.segment && this.options.destinations.segment.config);
}
/**
* Set or update a user's properties.
* @param userId The user's ID.
* @param properties Required and optional user properties.
*/
identify(userId: string, properties?: IdentifyProperties) {
if (properties && !this.validators['Identify'](properties)) {
this.throwOrLog(`Itly validation error: ${this.validators['Identify'].errors!.map((e: any) => `properties${e.dataPath} (${e.message})`).join('')}`);
}
if (this.options.disabled) {
return;
}
this.amplitude.identify({
user_id: userId,
user_properties: properties,
});
this.mixpanel.people.set(userId, {
distinct_id: userId,
...properties,
});
this.segment.identify({
userId,
traits: properties,
});
}
/**
* Called when a command fails.
* @param userId The user's ID.
* @param properties Required and optional event properties.
*/
trackCommandFailed(userId: string, properties: CommandFailedProperties) {
if (this.options.disabled) {
return;
}
if (!this.validators['CommandFailed'](properties)) {
this.throwOrLog(`Itly validation error: ${this.validators['CommandFailed'].errors.map((e: any) => `properties${e.dataPath} (${e.message})`).join('')}`);
}
let context = {};
if (this.options.context) {
context = (typeof this.options.context === 'object') ? this.options.context : this.options.context();
if (!this.validators['Context'](context)) {
this.throwOrLog(`Itly validation error: ${this.validators['Context'].errors.map((e: any) => `context${e.dataPath} (${e.message})..`).join('')}`);
}
}
this.ga.event({ ec: 'All', ea: 'Command Failed', /* cd1: todo */ }).send();
this.amplitude.track({
event_type: 'Command Failed',
user_id: userId,
event_properties: { ...context, ...properties, itly_source: 'cli', itly_version: '1.0', itly_schema: 'http://iterative.ly/company/0f45aaca-d07e-457a-9599-fb4fba3f5e24/event/12f12b2b-dc0c-4ff5-9602-89f21468a752' },
});
this.mixpanel.track(
'Command Failed',
{ distinct_id: userId, ...context, ...properties, itly_source: 'cli', itly_version: '1.0', itly_schema: 'http://iterative.ly/company/0f45aaca-d07e-457a-9599-fb4fba3f5e24/event/12f12b2b-dc0c-4ff5-9602-89f21468a752' },
);
this.segment.track({
userId,
event: 'Command Failed',
properties: { ...context, ...properties, itly_source: 'cli', itly_version: '1.0', itly_schema: 'http://iterative.ly/company/0f45aaca-d07e-457a-9599-fb4fba3f5e24/event/12f12b2b-dc0c-4ff5-9602-89f21468a752' },
});
}
/**
* Called when a command runs.
* @param userId The user's ID.
* @param properties Required and optional event properties.
*/
trackCommandRan(userId: string, properties: CommandRanProperties) {
if (this.options.disabled) {
return;
}
if (!this.validators['CommandRan'](properties)) {
this.throwOrLog(`Itly validation error: ${this.validators['CommandRan'].errors.map((e: any) => `properties${e.dataPath} (${e.message})`).join('')}`);
}
let context = {};
if (this.options.context) {
context = (typeof this.options.context === 'object') ? this.options.context : this.options.context();
if (!this.validators['Context'](context)) {
this.throwOrLog(`Itly validation error: ${this.validators['Context'].errors.map((e: any) => `context${e.dataPath} (${e.message})..`).join('')}`);
}
}
this.ga.event({ ec: 'All', ea: 'Command Ran', /* cd1: todo */ }).send();
this.amplitude.track({
event_type: 'Command Ran',
user_id: userId,
event_properties: { ...context, ...properties, itly_source: 'cli', itly_version: '1.0', itly_schema: 'http://iterative.ly/company/0f45aaca-d07e-457a-9599-fb4fba3f5e24/event/e6ac7a63-e73d-4964-ae29-7d8ef989e58c' },
});
this.mixpanel.track(
'Command Ran',
{ distinct_id: userId, ...context, ...properties, itly_source: 'cli', itly_version: '1.0', itly_schema: 'http://iterative.ly/company/0f45aaca-d07e-457a-9599-fb4fba3f5e24/event/e6ac7a63-e73d-4964-ae29-7d8ef989e58c' },
);
this.segment.track({
userId,
event: 'Command Ran',
properties: { ...context, ...properties, itly_source: 'cli', itly_version: '1.0', itly_schema: 'http://iterative.ly/company/0f45aaca-d07e-457a-9599-fb4fba3f5e24/event/e6ac7a63-e73d-4964-ae29-7d8ef989e58c' },
});
}
}
export default new Itly();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment