Skip to content

Commit

Permalink
First cut at esm and commonjs
Browse files Browse the repository at this point in the history
  • Loading branch information
seekayel committed Aug 9, 2022
1 parent 564ba24 commit 9914dc9
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 1 deletion.
57 changes: 57 additions & 0 deletions index.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const axios = require('axios')
const { v4: uuid } = require('uuid');
const md5 = require('md5')

const LIBRARY_VERSION = process.env.npm_package_version || 'unknown'
const LIBRARY_NAME = process.env.npm_package_name || 'analytics-async'

export async function track(msg) {
return call('track', msg)
}

export async function identify(msg) {
return call('identify', msg)
}

async function call(type, message) {

message = Object.assign({}, message)
message.context = Object.assign({
library: {
name: LIBRARY_NAME,
version: LIBRARY_VERSION
}
}, message.context)

message._metadata = Object.assign({
nodeVersion: process.versions.node
}, message._metadata)

if (!message.timestamp) {
message.timestamp = new Date()
}

if (!message.messageId) {
// We md5 the messaage to add more randomness. This is primarily meant
// for use in the browser where the uuid package falls back to Math.random()
// which is not a great source of randomness.
// Borrowed from analytics.js (https://github.com/segment-integrations/analytics.js-integration-segmentio/blob/a20d2a2d222aeb3ab2a8c7e72280f1df2618440e/lib/index.js#L255-L256).
message.messageId = `node-${md5(JSON.stringify(message))}-${uuid()}`
}

const headers = {
'content-type': 'application/json',
'user-agent': `${LIBRARY_NAME}/${LIBRARY_VERSION}`
}

const req = {
auth: {
username: process.env.SEGMENT_WRITE_KEY || 'Unset process.env.SEGMENT_WRITE_KEY'
},
headers
}

let p = axios.post(`https://api.segment.io/v1/${type}`, message, req)
console.log(`${type} => ${message.userId}`)
return p
}
File renamed without changes.
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
"name": "analytics-async",
"version": "0.0.4",
"description": "The hassle-free way to integrate analytics into any node application w/o dropping API calls.",
"main": "index.mjs",
"main": "index.js",
"type": "module",
"exports": {
"import": "./main.js",
"require": "./main.cjs"
},
"scripts": {
"start": "node index.mjs",
"test": "echo \"Error: no test specified\" && exit 1"
Expand Down

0 comments on commit 9914dc9

Please sign in to comment.