general fixes

This commit is contained in:
goenning 2023-09-01 15:49:04 +01:00
parent c407842754
commit f6de1cd18b
4 changed files with 33 additions and 44 deletions

View file

@ -22,8 +22,8 @@ export async function trackEvent(
function getHeaders(req?: NextIncomingMessage): Headers | undefined {
if (req) {
// we only need the user-agent header
return new Headers({
'accept-language': req.headers['accept-language'] ?? '',
'user-agent': req.headers['user-agent'] ?? '',
});
}

View file

@ -2,6 +2,8 @@ import { AptabaseOptions } from './types';
export { AptabaseOptions };
const isDebug = process.env.NODE_ENV === 'development';
export function init(appKey: string, options?: AptabaseOptions) {
globalThis.__APTABASE__ = { appKey, options };
}
@ -15,18 +17,15 @@ export async function trackEvent(
props?: Record<string, string | number | boolean>,
): Promise<void> {
const { appKey } = globalThis.__APTABASE__ || {};
if (!appKey) return Promise.resolve();
const userAgent = req.headers.get('user-agent') ?? '';
const body = JSON.stringify({
timestamp: new Date().toISOString(),
sessionId: 'CHANGE-THIS',
eventName: eventName,
systemProps: {
isDebug: true,
locale: 'en',
isDebug,
locale: extractLocale(req.headers.get('accept-language')),
appVersion: '',
sdkVersion: globalThis.__APTABASE_SDK_VERSION__ ?? `aptabase-node@${process.env.PKG_VERSION}`,
},
@ -37,7 +36,7 @@ export async function trackEvent(
const response = await fetch('http://localhost:3000/api/v0/event', {
method: 'POST',
headers: {
'User-Agent': userAgent,
'User-Agent': req.headers.get('user-agent') ?? '',
'Content-Type': 'application/json',
'App-Key': appKey,
},
@ -53,3 +52,17 @@ export async function trackEvent(
console.warn(`Failed to send event "${eventName}": ${e}`);
}
}
function extractLocale(locale: string | null): string | null {
if (!locale) {
return null;
}
const languageLocales = locale.split(',');
const firstLanguageLocale = languageLocales[0];
if (!firstLanguageLocale) {
return null;
}
const [language] = firstLanguageLocale.split(';');
return language || null;
}

View file

@ -1,13 +1,13 @@
export type AptabaseOptions = {
host?: string;
appVersion?: string;
__sdkVersion?: string;
};
const locale = navigator?.languages && navigator?.languages.length ? navigator?.languages[0] : navigator?.language;
const isDebug = location?.hostname === 'localhost';
let _appKey = '';
let _apiUrl = '';
let _locale = '';
let _isDebug = false;
let _options: AptabaseOptions | undefined;
const _hosts: { [region: string]: string } = {
@ -41,26 +41,25 @@ export function init(appKey: string, options?: AptabaseOptions) {
const baseUrl = getBaseUrl(parts[1], options);
_apiUrl = `${baseUrl}/api/v0/event`;
if (typeof location !== 'undefined') {
_isDebug = location.hostname === 'localhost';
}
if (typeof navigator !== 'undefined') {
_locale = navigator.languages && navigator.languages.length ? navigator.languages[0] : navigator.language;
}
}
export function trackEvent(eventName: string, props?: Record<string, string | number | boolean>) {
if (!_appKey || typeof window === 'undefined' || !window.fetch) return;
if (!_appKey) return;
if (typeof window === 'undefined' || !window.fetch) {
console.warn(
`Aptabase: this call to "trackEvent" requires a browser environment. Did you import from the wrong package?`,
);
return;
}
const body = JSON.stringify({
timestamp: new Date().toISOString(),
sessionId: 'CHANGE-THIS',
eventName: eventName,
systemProps: {
isDebug: _isDebug,
locale: _locale,
isDebug,
locale,
appVersion: _options?.appVersion ?? '',
sdkVersion: globalThis.__APTABASE_SDK_VERSION__ ?? `aptabase-web@${process.env.PKG_VERSION}`,
},

View file

@ -1,23 +0,0 @@
export function newSessionId() {
if (typeof crypto !== "undefined" && crypto && crypto.randomUUID) {
return crypto.randomUUID();
}
return [
randomStr(8),
randomStr(4),
randomStr(4),
randomStr(4),
randomStr(12),
].join("-");
}
const characters = "abcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
function randomStr(len: number) {
let result = "";
for (let i = 0; i < len; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}