Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(api): paginate the contact, group, and chat list endpoints (#401)
Yudhi Armyndharisc50a3f52bdd1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c24bb3b57..0d0059a0f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Changed+- **The contact, group, and chat list endpoints are now paginated (default cap 1000).** ⚠️ Behavior+ change. `GET /sessions/:id/contacts`, `/groups`, and `/chats` previously serialized the operator's+ *entire* address book / group / chat set into one response — a heap/GC hazard for very large+ accounts. They now accept optional `limit` (clamped `[1, 1000]`) and `offset` query params, and+ default to returning at most **1000** items when no `limit` is given. Accounts under 1000 items are+ unaffected; larger accounts page with `offset`. Chats are returned **most-recent first**, so a+ capped response is the newest chats rather than an arbitrary slice. In-process callers (plugins+ using the engine directly) still receive the full set. (#401)- **Fresh databases no longer create the unused `api_keys`/`audit_logs` tables on the dataconnection.** Those auth/audit tables belong solely to the separate "main" SQLite connection, butthe data-connection baseline migration also created them (with a stale `keyPrefix` width), leavingdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex e83928569..42f2c52d9 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1049,6 +1049,8 @@ DELETE /api/sessions/:sessionId/templates/:idGET /api/sessions/:sessionId/contacts```+**Query parameters (optional):** `limit` — max items to return, clamped to `[1, 1000]` (default `1000`); `offset` — items to skip, for paging.+**Response (200 OK):**```json[@@ -1133,6 +1135,8 @@ To get this resolved automatically on each incoming message instead of calling tGET /api/sessions/:sessionId/groups```+**Query parameters (optional):** `limit` — max items to return, clamped to `[1, 1000]` (default `1000`); `offset` — items to skip, for paging.+**Response (200 OK):**```json[diff --git a/src/common/utils/paginate.spec.ts b/src/common/utils/paginate.spec.tsnew file mode 100644index 000000000..1dfa72240--- /dev/null+++ b/src/common/utils/paginate.spec.ts@@ -0,0 +1,31 @@+import { paginate } from './paginate';++describe('paginate', () => {+ const items = Array.from({ length: 1500 }, (_, i) => i);++ it('caps an unbounded request at the default limit (1000)', () => {+ const out = paginate(items);+ expect(out.length).toBe(1000);+ expect(out[0]).toBe(0);+ expect(out[999]).toBe(999);+ });++ it('returns exactly `limit` items, clamped to the max (1000)', () => {+ expect(paginate(items, 10)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);+ expect(paginate(items, 99999).length).toBe(1000); // explicit huge limit clamped to the cap+ expect(paginate(items, 0).length).toBe(1); // clamped up to the minimum of 1+ });++ it('pages with offset', () => {+ expect(paginate(items, 5, 10)).toEqual([10, 11, 12, 13, 14]);+ });++ it('treats a non-finite limit/offset as the safe default (NaN limit -> cap, NaN offset -> 0)', () => {+ expect(paginate(items, NaN).length).toBe(1000);+ expect(paginate(items, 5, NaN)).toEqual([0, 1, 2, 3, 4]);+ });++ it('returns the whole collection when it is under the cap', () => {+ expect(paginate([1, 2, 3])).toEqual([1, 2, 3]);+ });+});diff --git a/src/common/utils/paginate.ts b/src/common/utils/paginate.tsnew file mode 100644index 000000000..c4fc27a77--- /dev/null+++ b/src/common/utils/paginate.ts@@ -0,0 +1,30 @@+/** Default and maximum number of items returned by a paginated list endpoint. */+export const DEFAULT_LIST_LIMIT = 1000;++/** Optional pagination window for a list endpoint. */+export interface ListOptions {+ limit?: number;+ offset?: number;+}++/**+ * Bound an in-memory list for an HTTP response.+ *+ * Engine-backed list endpoints (contacts, groups, chats) can return the operator's entire address+ * book / chat set; serializing tens of thousands of items into one JSON body is a heap/GC hazard.+ * This clamps the response window:+ * - an omitted or non-finite `limit` falls back to {@link DEFAULT_LIST_LIMIT} (the default cap),+ * - an explicit `limit` is clamped to `[1, DEFAULT_LIST_LIMIT]`,+ * - `offset` (non-finite -> 0) pages beyond the first window.+ *+ * Pagination is applied at the HTTP/service boundary only — the engine still returns the full set+ * to in-process callers (e.g. plugins), so this never narrows what those consumers see.+ */+export function paginate<T>(items: T[], limit?: number, offset?: number): T[] {+ const off = typeof offset === 'number' && Number.isFinite(offset) ? Math.max(Math.trunc(offset), 0) : 0;+ const lim =+ typeof limit === 'number' && Number.isFinite(limit)+ ? Math.min(Math.max(Math.trunc(limit), 1), DEFAULT_LIST_LIMIT)+ : DEFAULT_LIST_LIMIT;+ return items.slice(off, off + lim);+}diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.tsindex 5fa5aeab1..efeb41303 100644--- a/src/modules/contact/contact.controller.ts+++ b/src/modules/contact/contact.controller.ts@@ -1,5 +1,5 @@-import { Controller, Get, Post, Delete, Param, HttpCode, HttpStatus } from '@nestjs/common';-import { ApiTags, ApiOperation, ApiResponse, ApiParam } from '@nestjs/swagger';+import { Controller, Get, Post, Delete, Param, Query, HttpCode, HttpStatus } from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';import { ContactService } from './contact.service';import { RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';@@ -18,8 +18,17 @@ export class ContactController {})@ApiResponse({ status: 400, description: 'Session not ready' })@ApiResponse({ status: 404, description: 'Session not found' })- async findAll(@Param('sessionId') sessionId: string) {- return this.contactService.getContacts(sessionId);+ @ApiQuery({ name: 'limit', required: false, description: 'Max contacts to return (1–1000, default 1000)' })+ @ApiQuery({ name: 'offset', required: false, description: 'Number of contacts to skip (for paging)' })+ async findAll(+ @Param('sessionId') sessionId: string,+ @Query('limit') limit?: string,+ @Query('offset') offset?: string,+ ) {+ return this.contactService.getContacts(sessionId, {+ limit: limit ? parseInt(limit, 10) : undefined,+ offset: offset ? parseInt(offset, 10) : undefined,+ });}@Get(':contactId')diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.tsindex 292ded452..549555180 100644--- a/src/modules/contact/contact.service.spec.ts+++ b/src/modules/contact/contact.service.spec.ts@@ -13,6 +13,20 @@ describe('ContactService', () => {expect(() => makeService(undefined).getContacts('s1')).toThrow(BadRequestException);});+ it('caps an unbounded contacts list at the default limit (1000)', async () => {+ const big = Array.from({ length: 1500 }, (_, i) => ({ id: `${i}@c.us` }));+ const getContacts = jest.fn().mockResolvedValue(big);+ await expect(makeService({ getContacts }).getContacts('s1')).resolves.toHaveLength(1000);+ });++ it('applies limit/offset to the contacts list', async () => {+ const big = Array.from({ length: 50 }, (_, i) => ({ id: `${i}@c.us` }));+ const getContacts = jest.fn().mockResolvedValue(big);+ const page = (await makeService({ getContacts }).getContacts('s1', { limit: 5, offset: 10 })) as { id: string }[];+ expect(page).toHaveLength(5);+ expect(page[0].id).toBe('[email protected]');+ });+it('maps a missing contact to 404', async () => {const svc = makeService({ getContactById: jest.fn().mockResolvedValue(null) });await expect(svc.getContactById('s1', 'c404')).rejects.toBeInstanceOf(NotFoundException);diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.tsindex 710e22264..a45323b97 100644--- a/src/modules/contact/contact.service.ts+++ b/src/modules/contact/contact.service.ts@@ -1,6 +1,7 @@import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';import { SessionService } from '../session/session.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';+import { paginate, ListOptions } from '../../common/utils/paginate';/*** Owns engine access for contact operations so the "session not started" guard and@@ -18,8 +19,12 @@ export class ContactService {return engine;}- getContacts(sessionId: string) {- return this.getEngine(sessionId).getContacts();+ getContacts(sessionId: string, opts: ListOptions = {}) {+ // getEngine throws synchronously (keeps the "session not started" guard a sync 400); the+ // engine returns the full set and we bound the HTTP response window via paginate().+ return this.getEngine(sessionId)+ .getContacts()+ .then(contacts => paginate(contacts, opts.limit, opts.offset));}async getContactById(sessionId: string, contactId: string) {diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.tsindex cbebab244..cead7bd87 100644--- a/src/modules/group/group.controller.ts+++ b/src/modules/group/group.controller.ts@@ -1,5 +1,5 @@-import { Controller, Get, Post, Put, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';-import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';+import { Controller, Get, Post, Put, Delete, Param, Query, Body, HttpCode, HttpStatus } from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody, ApiQuery } from '@nestjs/swagger';import { GroupService } from './group.service';import { CreateGroupDto, ParticipantsDto, GroupSubjectDto, GroupDescriptionDto } from './dto/group.dto';import { RequireRole } from '../auth/decorators/auth.decorators';@@ -14,8 +14,17 @@ export class GroupController {@ApiOperation({ summary: 'Get all groups for a session' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiResponse({ status: 200, description: 'List of groups' })- async findAll(@Param('sessionId') sessionId: string) {- return this.groupService.getGroups(sessionId);+ @ApiQuery({ name: 'limit', required: false, description: 'Max groups to return (1–1000, default 1000)' })+ @ApiQuery({ name: 'offset', required: false, description: 'Number of groups to skip (for paging)' })+ async findAll(+ @Param('sessionId') sessionId: string,+ @Query('limit') limit?: string,+ @Query('offset') offset?: string,+ ) {+ return this.groupService.getGroups(sessionId, {+ limit: limit ? parseInt(limit, 10) : undefined,+ offset: offset ? parseInt(offset, 10) : undefined,+ });}@Get(':groupId')diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.tsindex 6afe294cb..8a84a628a 100644--- a/src/modules/group/group.service.spec.ts+++ b/src/modules/group/group.service.spec.ts@@ -24,6 +24,22 @@ describe('GroupService', () => {expect(getGroups).toHaveBeenCalledTimes(1);});+ it('caps an unbounded groups list at the default limit (1000)', async () => {+ const big = Array.from({ length: 1500 }, (_, i) => ({ id: `g${i}` }));+ const svc = makeService({ getGroups: jest.fn().mockResolvedValue(big) });+ await expect(svc.getGroups('s1')).resolves.toHaveLength(1000);+ });++ it('applies limit/offset to the groups list', async () => {+ const big = Array.from({ length: 50 }, (_, i) => ({ id: `g${i}` }));+ const page = (await makeService({ getGroups: jest.fn().mockResolvedValue(big) }).getGroups('s1', {+ limit: 5,+ offset: 10,+ })) as { id: string }[];+ expect(page).toHaveLength(5);+ expect(page[0].id).toBe('g10');+ });+it('maps a missing group to 404 (business rule lives in the service)', async () => {const svc = makeService({ getGroupInfo: jest.fn().mockResolvedValue(null) });await expect(svc.getGroupInfo('s1', 'g404')).rejects.toBeInstanceOf(NotFoundException);diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.tsindex 39c5f40e3..b7d6c89bd 100644--- a/src/modules/group/group.service.ts+++ b/src/modules/group/group.service.ts@@ -1,6 +1,7 @@import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';import { SessionService } from '../session/session.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';+import { paginate, ListOptions } from '../../common/utils/paginate';/*** Owns engine access for group operations. Controllers depend on this service instead of@@ -19,8 +20,12 @@ export class GroupService {return engine;}- getGroups(sessionId: string) {- return this.getEngine(sessionId).getGroups();+ getGroups(sessionId: string, opts: ListOptions = {}) {+ // getEngine throws synchronously (sync 400 guard); the engine returns the full set and we+ // bound the HTTP response window via paginate().+ return this.getEngine(sessionId)+ .getGroups()+ .then(groups => paginate(groups, opts.limit, opts.offset));}async getGroupInfo(sessionId: string, groupId: string) {diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 70936746b..c35f68972 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -1,5 +1,5 @@-import { Controller, Get, Post, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';-import { ApiTags, ApiOperation, ApiResponse, ApiParam } from '@nestjs/swagger';+import { Controller, Get, Post, Delete, Param, Query, Body, HttpCode, HttpStatus } from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';import { SessionService } from './session.service';import {CreateSessionDto,@@ -212,18 +212,36 @@ export class SessionController {})@ApiResponse({ status: 400, description: 'Session not ready' })@ApiResponse({ status: 404, description: 'Session not found' })- async getGroups(@Param('id') id: string): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {- return this.sessionService.getGroups(id);+ @ApiQuery({ name: 'limit', required: false, description: 'Max groups to return (1–1000, default 1000)' })+ @ApiQuery({ name: 'offset', required: false, description: 'Number of groups to skip (for paging)' })+ async getGroups(+ @Param('id') id: string,+ @Query('limit') limit?: string,+ @Query('offset') offset?: string,+ ): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {+ return this.sessionService.getGroups(id, {+ limit: limit ? parseInt(limit, 10) : undefined,+ offset: offset ? parseInt(offset, 10) : undefined,+ });}@Get(':id/chats')@ApiOperation({ summary: 'Get active chats for a session' })@ApiParam({ name: 'id', description: 'Session ID' })- @ApiResponse({ status: 200, description: 'List of active chats' })+ @ApiResponse({ status: 200, description: 'List of active chats (most recent first)' })@ApiResponse({ status: 400, description: 'Session not ready' })@ApiResponse({ status: 404, description: 'Session not found' })- async getChats(@Param('id') id: string): Promise<ChatSummary[]> {- return this.sessionService.getChats(id);+ @ApiQuery({ name: 'limit', required: false, description: 'Max chats to return (1–1000, default 1000)' })+ @ApiQuery({ name: 'offset', required: false, description: 'Number of chats to skip (for paging)' })+ async getChats(+ @Param('id') id: string,+ @Query('limit') limit?: string,+ @Query('offset') offset?: string,+ ): Promise<ChatSummary[]> {+ return this.sessionService.getChats(id, {+ limit: limit ? parseInt(limit, 10) : undefined,+ offset: offset ? parseInt(offset, 10) : undefined,+ });}@Post(':id/chats/read')diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 371e2d2aa..42e528e61 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1149,6 +1149,47 @@ describe('SessionService', () => {expect(result).toEqual(chats);});+ it('caps an unbounded chat list at the default limit (1000), most-recent first', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');++ const chats = Array.from({ length: 1500 }, (_, i) => ({+ id: `${i}@c.us`,+ name: `c${i}`,+ isGroup: false,+ unreadCount: 0,+ timestamp: i,+ }));+ mockEngine.getChats.mockResolvedValue(chats);++ const result = await service.getChats('sess-uuid-1');+ expect(result).toHaveLength(1000);+ expect(result[0].timestamp).toBe(1499); // sorted timestamp DESC before capping+ expect(result[999].timestamp).toBe(500);+ });++ it('applies limit/offset to the chat list', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');++ const chats = Array.from({ length: 50 }, (_, i) => ({+ id: `${i}@c.us`,+ name: `c${i}`,+ isGroup: false,+ unreadCount: 0,+ timestamp: i,+ }));+ mockEngine.getChats.mockResolvedValue(chats);++ const result = await service.getChats('sess-uuid-1', { limit: 5, offset: 0 });+ expect(result).toHaveLength(5);+ expect(result[0].timestamp).toBe(49); // most-recent first+ });+it('should throw BadRequestException when session is not started', async () => {const session = createMockSession();(repository.findOne as jest.Mock).mockResolvedValue(session);@@ -1157,6 +1198,21 @@ describe('SessionService', () => {});});+ describe('getGroups pagination', () => {+ it('caps an unbounded group list at the default limit (1000)', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');++ const groups = Array.from({ length: 1500 }, (_, i) => ({ id: `g${i}`, name: `G${i}` }));+ mockEngine.getGroups.mockResolvedValue(groups);++ const result = await service.getGroups('sess-uuid-1');+ expect(result).toHaveLength(1000);+ });+ });+// ── sendSeen (markChatRead) ───────────────────────────────────────describe('sendSeen', () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex c803874f4..a415855a1 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -13,6 +13,7 @@ import { Session, SessionStatus } from './entities/session.entity';import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';import { CreateSessionDto } from './dto';import { EngineFactory } from '../../engine/engine.factory';+import { paginate, ListOptions } from '../../common/utils/paginate';import {IWhatsAppEngine,EngineStatus,@@ -1032,7 +1033,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn phone;}- async getGroups(id: string): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {+ async getGroups(+ id: string,+ opts: ListOptions = {},+ ): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {await this.findOne(id); // Verify session existsconst engine = this.engines.get(id);@@ -1041,14 +1045,15 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}const groups = await engine.getGroups();- return groups.map(g => ({+ const mapped = groups.map(g => ({id: g.id,name: g.name,linkedParentJID: g.linkedParentJID,}));+ return paginate(mapped, opts.limit, opts.offset);}- async getChats(id: string): Promise<ChatSummary[]> {+ async getChats(id: string, opts: ListOptions = {}): Promise<ChatSummary[]> {await this.findOne(id); // Verify session existsconst engine = this.engines.get(id);@@ -1056,7 +1061,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatthrow new BadRequestException('Session is not started');}- return engine.getChats();+ // Most-recent first, then bound the response window. Sorting before the cap means a capped+ // response is the N newest chats (what clients show first) rather than an arbitrary slice.+ const chats = [...(await engine.getChats())].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));+ return paginate(chats, opts.limit, opts.offset);}async sendSeen(id: string, chatId: string): Promise<boolean> {