* Segment serverside analytics plugin * @link https://getanalytics.io/plugins/segment/ * @link https://segment.com/docs/sources/website/analytics.js/ * @param {object} pluginConfig - Plugin settings * @param {string} pluginConfig.writeKey - Your segment writeKey * @param {boolean} [pluginConf
(userConfig = {})
| 32 | * }) |
| 33 | */ |
| 34 | function segmentPlugin(userConfig = {}) { |
| 35 | const config = { |
| 36 | ...defaultConfig, |
| 37 | ...userConfig |
| 38 | } |
| 39 | const client = new Analytics(config.writeKey, { |
| 40 | ...config |
| 41 | }) |
| 42 | |
| 43 | return { |
| 44 | name: 'segment', |
| 45 | config: config, |
| 46 | // Custom segment methods |
| 47 | methods: { |
| 48 | // Segment group call https://segment.com/docs/connections/sources/catalog/libraries/server/node/#group |
| 49 | group(groupId, traits = {}, options = {}, callback) { |
| 50 | const analyticsInstance = this.instance |
| 51 | const user = analyticsInstance.user() |
| 52 | const userId = options.userId || user.userId |
| 53 | const anonymousId = options.anonymousId || user.anonymousId |
| 54 | client.group({ |
| 55 | ...(anonymousId ? { anonymousId } : {}), |
| 56 | ...(userId ? { userId } : {}), |
| 57 | groupId: groupId, |
| 58 | traits: traits, |
| 59 | }, callback) |
| 60 | }, |
| 61 | // Function for using analytics-node client in other methods |
| 62 | getClient: () => client, |
| 63 | }, |
| 64 | /* page view */ |
| 65 | page: ({ payload, config }) => { |
| 66 | const { userId, anonymousId } = payload |
| 67 | if (!userId && !anonymousId) { |
| 68 | throw new Error('Missing userId and anonymousId. You must include one to make segment call') |
| 69 | } |
| 70 | |
| 71 | const data = { |
| 72 | properties: payload.properties, |
| 73 | anonymousId, |
| 74 | userId |
| 75 | } |
| 76 | |
| 77 | client.page(data) |
| 78 | }, |
| 79 | /* track event */ |
| 80 | track: ({ payload, config }) => { |
| 81 | const { userId, anonymousId } = payload |
| 82 | if (!userId && !anonymousId) { |
| 83 | throw new Error('Missing userId and anonymousId. You must include one to make segment call') |
| 84 | } |
| 85 | |
| 86 | const data = { |
| 87 | event: payload.event, |
| 88 | properties: payload.properties |
| 89 | } |
| 90 | |
| 91 | if (userId) { |
no outgoing calls
no test coverage detected