Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Last active September 25, 2020 02:19
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 DavidWells/4afc410e452b2c97429c38cce4fcba68 to your computer and use it in GitHub Desktop.
Save DavidWells/4afc410e452b2c97429c38cce4fcba68 to your computer and use it in GitHub Desktop.
Adding segment group functionality to analytics npm package. See the docs https://getanalytics.io/plugins/segment/#adding-group-functionality
import Analytics from 'analytics'
import segmentPlugin from '@analytics/segment'
const originalSegmentInstance = segmentPlugin({
writeKey: '123-xyz'
})
// Extend originalSegmentInstance with custom methods
const enchancedSegmentInstance = Object.assign({}, originalSegmentInstance, {
methods: {
// add analytics.group method https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#group
group(groupId, traits = {}, options = {}, callback) {
const analyticsInstance = this.instance
// If no segment, return early
if (typeof window.analytics === 'undefined') {
return
}
// Make group call to segment
window.analytics.group(groupId, traits, options, callback)
},
}
}
// Initialize analytics instance with plugins
const analytics = Analytics({
app: 'your-app-name',
plugins: [
enchancedSegmentInstance,
]
})
// Usage:
// Now you can call segment.group in your app like so
analytics.plugins.segment.group('one', 'two', 'three')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment