initial for v1

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-07-28 00:05:32 +02:00
committed by Carl-Gerhard Lindesvärd
parent c770634e73
commit 15e997129a
23 changed files with 1019 additions and 528 deletions

View File

@@ -1,8 +1,8 @@
import type { NextFunction, Request, Response } from 'express';
import { getClientIp } from 'request-ip';
import type { OpenpanelSdkOptions } from '@openpanel/sdk';
import { OpenpanelSdk } from '@openpanel/sdk';
import type { OpenPanelOptions } from '@openpanel/sdk';
import { OpenPanel } from '@openpanel/sdk';
export * from '@openpanel/sdk';
@@ -10,33 +10,35 @@ declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Express {
export interface Request {
op: OpenpanelSdk;
op: OpenPanel;
}
}
}
export type OpenpanelOptions = OpenpanelSdkOptions & {
export type OpenpanelOptions = OpenPanelOptions & {
trackRequest?: (url: string) => boolean;
getProfileId?: (req: Request) => string;
};
export default function createMiddleware(options: OpenpanelOptions) {
return function middleware(req: Request, res: Response, next: NextFunction) {
const sdk = new OpenpanelSdk(options);
const sdk = new OpenPanel(options);
const ip = getClientIp(req);
if (ip) {
sdk.api.headers['x-client-ip'] = ip;
sdk.api.addHeader('x-client-ip', ip);
}
if (options.getProfileId) {
const profileId = options.getProfileId(req);
if (profileId) {
sdk.setProfileId(profileId);
sdk.identify({
profileId,
});
}
}
if (options.trackRequest?.(req.url)) {
sdk.event('request', {
sdk.track('request', {
url: req.url,
method: req.method,
query: req.query,