Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
Changelog

## [4.14.0](https://github.com/MikeDev75015/mongodb-dynamic-api/compare/v4.13.0...v4.14.0) (2026-05-26)

### typing

* **typing:** 6 upstream improvements — BeforeRegisterContext, TExtra, BodyDTO generics, customRoutes req/interceptors, WS customEvents ([bab7aec](https://github.com/MikeDev75015/mongodb-dynamic-api/commit/bab7aecf5400954c6f21c1e99434174b892cde1d)), closes [#5](https://github.com/MikeDev75015/mongodb-dynamic-api/issues/5) [#2](https://github.com/MikeDev75015/mongodb-dynamic-api/issues/2) [#4](https://github.com/MikeDev75015/mongodb-dynamic-api/issues/4) [#3](https://github.com/MikeDev75015/mongodb-dynamic-api/issues/3) [#6](https://github.com/MikeDev75015/mongodb-dynamic-api/issues/6)

## [4.13.0](https://github.com/MikeDev75015/mongodb-dynamic-api/compare/v4.12.0...v4.13.0) (2026-05-26)

### route-config
Expand Down
135 changes: 135 additions & 0 deletions libs/dynamic-api/src/adapters/socket-adapter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,5 +143,140 @@ describe('SocketAdapter', () => {
expect.any(String),
);
});

describe('customEvents', () => {
it('registers socket.on for each customEvent on connection', () => {
const handler = jest.fn();
const eventSocket = {
id: 'sock-ev',
handshake: { auth: {}, query: {} },
on: jest.fn(),
};

DynamicApiWsConfigStore.customEvents = [
{ name: 'voice-call', handler },
{ name: 'admin-action', handler },
];

connectionHandler(eventSocket);

expect(eventSocket.on).toHaveBeenCalledTimes(2);
expect(eventSocket.on).toHaveBeenCalledWith('voice-call', expect.any(Function));
expect(eventSocket.on).toHaveBeenCalledWith('admin-action', expect.any(Function));
});

it('calls the event handler with payload and user', () => {
const handler = jest.fn();
let capturedListener: ((payload: unknown) => void) | undefined;

const eventSocket = {
id: 'sock-ev2',
handshake: { auth: {}, query: {} },
on: jest.fn((_name: string, listener: (payload: unknown) => void) => {
capturedListener = listener;
}),
};

DynamicApiWsConfigStore.customEvents = [{ name: 'test-event', handler }];

connectionHandler(eventSocket);
capturedListener!({ data: 'hello' });

expect(handler).toHaveBeenCalledWith(eventSocket, { data: 'hello' }, undefined);
});

it('blocks the event handler when predicate returns false', () => {
const handler = jest.fn();
const predicate = jest.fn().mockReturnValue(false);
let capturedListener: ((payload: unknown) => void) | undefined;

const eventSocket = {
id: 'sock-pred',
handshake: { auth: {}, query: {} },
on: jest.fn((_name: string, listener: (payload: unknown) => void) => {
capturedListener = listener;
}),
};

DynamicApiWsConfigStore.customEvents = [{ name: 'restricted', handler, predicate }];

connectionHandler(eventSocket);
capturedListener!({ data: 'blocked' });

expect(predicate).toHaveBeenCalledWith(undefined);
expect(handler).not.toHaveBeenCalled();
});

it('calls the event handler when predicate returns true', () => {
const handler = jest.fn();
const predicate = jest.fn().mockReturnValue(true);
let capturedListener: ((payload: unknown) => void) | undefined;

const eventSocket = {
id: 'sock-pred2',
handshake: { auth: {}, query: {} },
on: jest.fn((_name: string, listener: (payload: unknown) => void) => {
capturedListener = listener;
}),
};

DynamicApiWsConfigStore.customEvents = [{ name: 'allowed', handler, predicate }];

connectionHandler(eventSocket);
capturedListener!({ data: 'ok' });

expect(handler).toHaveBeenCalledWith(eventSocket, { data: 'ok' }, undefined);
});

it('catches async custom event handler errors', async () => {
const error = new Error('event error');
const handler = jest.fn().mockRejectedValue(error);
const spyError = jest.spyOn(adapter['logger'], 'error').mockImplementation(() => {});
let capturedListener: ((payload: unknown) => void) | undefined;

const eventSocket = {
id: 'sock-err',
handshake: { auth: {}, query: {} },
on: jest.fn((_name: string, listener: (payload: unknown) => void) => {
capturedListener = listener;
}),
};

DynamicApiWsConfigStore.customEvents = [{ name: 'failing-event', handler }];

connectionHandler(eventSocket);
capturedListener!({});

await new Promise((r) => setTimeout(r, 10));

expect(spyError).toHaveBeenCalledWith(
expect.stringContaining("customEvent 'failing-event' handler error"),
expect.any(String),
);
});

it('logs debug warning when predicate blocks event and debug is true', () => {
DynamicApiWsConfigStore.debug = true;
const spyWarn = jest.spyOn(adapter['logger'], 'warn').mockImplementation(() => {});
const handler = jest.fn();
const predicate = jest.fn().mockReturnValue(false);
let capturedListener: ((payload: unknown) => void) | undefined;

const eventSocket = {
id: 'sock-dbg',
handshake: { auth: {}, query: {} },
on: jest.fn((_name: string, listener: (payload: unknown) => void) => {
capturedListener = listener;
}),
};

DynamicApiWsConfigStore.customEvents = [{ name: 'guarded', handler, predicate }];

connectionHandler(eventSocket);
capturedListener!({});

expect(spyWarn).toHaveBeenCalledWith(expect.stringContaining('blocked by predicate'));
});
});
});
});
31 changes: 28 additions & 3 deletions libs/dynamic-api/src/adapters/socket-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ export class SocketAdapter extends IoAdapter {
}

private handleConnection(socket: ExtendedSocket): void {
const { debug, jwtSecret, onConnection } = DynamicApiWsConfigStore;
let user: any;
const { debug, jwtSecret, onConnection, customEvents } = DynamicApiWsConfigStore;
let user: unknown;

if (jwtSecret) {
const token = (socket.handshake?.auth?.token
Expand All @@ -51,7 +51,8 @@ export class SocketAdapter extends IoAdapter {
}

if (debug) {
this.logger.log(`[WS] connection – socket=${socket.id}, user=${user?.id ?? 'anonymous'}`);
const userId = (user as { id?: string })?.id ?? 'anonymous';
this.logger.log(`[WS] connection – socket=${socket.id}, user=${userId}`);
}

if (onConnection) {
Expand All @@ -64,5 +65,29 @@ export class SocketAdapter extends IoAdapter {
});
}
}

// ─── Register declarative custom event handlers ──────────────────────────
for (const eventConfig of customEvents) {
socket.on(eventConfig.name, (payload: unknown) => {
if (eventConfig.predicate && !eventConfig.predicate(user)) {
if (debug) {
this.logger.warn(`[WS] event=${eventConfig.name} blocked by predicate for socket=${socket.id}`);
}
return;
}

const result = eventConfig.handler(socket, payload, user);
if (result instanceof Promise) {
result.catch((err) => {
const message = err instanceof Error ? err.message : String(err);
const stack = err instanceof Error ? err.stack : undefined;
this.logger.error(
`customEvent '${eventConfig.name}' handler error for socket ${socket.id}: ${message}`,
stack,
);
});
}
});
}
}
}
19 changes: 19 additions & 0 deletions libs/dynamic-api/src/helpers/socket-config.helper.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,25 @@ describe('SocketConfigHelper', () => {
expect(DynamicApiWsConfigStore.debug).toBe(true);
expect(DynamicApiWsConfigStore.onConnection).toBe(onConnection);
expect(DynamicApiWsConfigStore.jwtSecret).toBe('test-jwt-secret');
expect(DynamicApiWsConfigStore.customEvents).toEqual([]);
});

it('should populate customEvents in the config store', () => {
const handler = jest.fn();
const customEvents = [
{ name: 'voice-call', handler },
{ name: 'admin-action', predicate: jest.fn(), handler },
];

enableDynamicAPIWebSockets(fakeApp, { customEvents });

expect(DynamicApiWsConfigStore.customEvents).toBe(customEvents);
});

it('should default customEvents to empty array when not provided', () => {
enableDynamicAPIWebSockets(fakeApp);

expect(DynamicApiWsConfigStore.customEvents).toEqual([]);
});

it('should accept a number (deprecated) and warn', () => {
Expand Down
1 change: 1 addition & 0 deletions libs/dynamic-api/src/helpers/socket-config.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ function enableDynamicAPIWebSockets(

// Populate the static config store
DynamicApiWsConfigStore.onConnection = resolvedOptions.onConnection;
DynamicApiWsConfigStore.customEvents = resolvedOptions.customEvents ?? [];
DynamicApiWsConfigStore.debug = resolvedOptions.debug ?? false;

// Read jwtSecret from global state (may be undefined when auth is not configured)
Expand Down
6 changes: 4 additions & 2 deletions libs/dynamic-api/src/helpers/ws-config.store.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import { ExtendedSocket } from '../interfaces';
import { CustomSocketEventConfig, ExtendedSocket } from '../interfaces';

/**
* Static store for WebSocket configuration values.
* Populated by `enableDynamicAPIWebSockets` and consumed by the socket adapter and gateways.
* @deprecated Internal API — will be removed from public exports in v5.
*/
export class DynamicApiWsConfigStore {
static onConnection: ((socket: ExtendedSocket, user?: any) => void | Promise<void>) | undefined;
static onConnection: ((socket: ExtendedSocket, user?: unknown) => void | Promise<void>) | undefined;
static customEvents: CustomSocketEventConfig[] = [];
static debug = false;
static jwtSecret: string | undefined;

/** Reset all values — useful for testing. */
static reset(): void {
this.onConnection = undefined;
this.customEvents = [];
this.debug = false;
this.jwtSecret = undefined;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { CanActivate, Type, ValidationPipeOptions } from '@nestjs/common';
import { CanActivate, NestInterceptor, Type, ValidationPipeOptions } from '@nestjs/common';
import { Model } from 'mongoose';
import { BaseEntity } from '../models';
import { AbilityPredicate, PredicateBehavior } from './dynamic-api-ability.interface';
import { DynamicApiRequest } from './dynamic-api-request.interface';
import { Mappable } from './dynamic-api-route-dtos-bundle.type';
import { DynamicApiWebSocketOptions } from './dynamic-api-web-socket.interface';

Expand Down Expand Up @@ -34,6 +35,26 @@ interface CustomRouteContext<
body: Body;
/** Parsed query string object. */
query: Query;
/**
* The raw HTTP request object.
*
* Available **only** in HTTP context (not in WebSocket/gateway handlers, where it is `undefined`).
*
* Useful for accessing Multer file uploads (via `FileInterceptor`) or other low-level
* request properties that are not available through the typed `body`/`query` fields.
*
* @example — reading a Multer file added by `FileInterceptor`
* ```typescript
* import type { DynamicApiRequest } from 'mongodb-dynamic-api';
*
* const handleUpload = async ({ req }) => {
* interface UploadRequest extends DynamicApiRequest { file?: Express.Multer.File }
* const file = (req as UploadRequest)?.file;
* // ...
* };
* ```
*/
req?: DynamicApiRequest;
}

/**
Expand Down Expand Up @@ -139,6 +160,30 @@ interface CustomRouteConfig<
*/
presenter?: Type & Partial<Mappable<Entity>>;
};

/**
* Route-level NestJS interceptors applied **only** to this custom route.
*
* Use this to attach per-route interceptors such as `FileInterceptor` for multipart
* uploads without touching the controller-level `useInterceptors`.
*
* @example — multipart file upload via `FileInterceptor`
* ```typescript
* import { FileInterceptor } from '@nestjs/platform-express';
*
* {
* method: 'POST',
* path: ':id/attachments/upload',
* useInterceptors: [FileInterceptor('file', { limits: { fileSize: 10 * 1024 * 1024 } })],
* handler: async ({ req }) => {
* interface UploadRequest extends DynamicApiRequest { file?: Express.Multer.File }
* const file = (req as UploadRequest).file;
* // process file ...
* },
* }
* ```
*/
useInterceptors?: Type<NestInterceptor>[];
}

export type { HttpMethod, CustomRouteContext, CustomRouteConfig };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import { DynamicApiWebSocketOptions } from './dynamic-api-web-socket.interface';
/** @deprecated Internal API — will be removed from public exports in v5. */
const DYNAMIC_API_GLOBAL_STATE = Symbol('DYNAMIC_API_GLOBAL_STATE');

interface DynamicApiForRootOptions<Entity extends BaseEntity = any> {
interface DynamicApiForRootOptions<Entity extends BaseEntity = any, RegisterExtra = Record<never, never>> {
useGlobalCache?: boolean;
cacheOptions?: DynamicApiCacheOptions;
useAuth?: DynamicApiAuthOptions<Entity>;
useAuth?: DynamicApiAuthOptions<Entity, RegisterExtra>;
routesConfig?: Partial<RoutesConfig>;
webSocket?: DynamicApiWebSocketOptions;
broadcastGatewayOptions?: GatewayMetadata;
Expand Down
Loading