Skip to content

Add missing endpoints#126

Open
IgorDobryn wants to merge 15 commits into
mainfrom
MT-21858-add-missing-endpoints
Open

Add missing endpoints#126
IgorDobryn wants to merge 15 commits into
mainfrom
MT-21858-add-missing-endpoints

Conversation

@IgorDobryn
Copy link
Copy Markdown
Contributor

@IgorDobryn IgorDobryn commented Apr 30, 2026

Motivation

Changes

Webhooks

  • POST /api/accounts/{account_id}/webhooks — createWebhook
  • GET /api/accounts/{account_id}/webhooks — listWebhooks
  • GET /api/accounts/{account_id}/webhooks/{webhook_id} — getWebhook
  • PATCH /api/accounts/{account_id}/webhooks/{webhook_id} — updateWebhook
  • DELETE /api/accounts/{account_id}/webhooks/{webhook_id} — deleteWebhook

API Tokens

  • GET /api/accounts/{account_id}/api_tokens — listApiTokens
  • POST /api/accounts/{account_id}/api_tokens — createApiToken
  • GET /api/accounts/{account_id}/api_tokens/{id} — getApiToken
  • DELETE /api/accounts/{account_id}/api_tokens/{id} — deleteApiToken
  • POST /api/accounts/{account_id}/api_tokens/{id}/reset — resetApiToken

Sub-Accounts

  • GET /api/organizations/{organization_id}/sub_accounts — getOrganizationSubAccounts
  • POST /api/organizations/{organization_id}/sub_accounts — createOrganizationSubAccount

Summary by CodeRabbit

  • New Features

    • Webhooks CRUD for accounts; API tokens CRUD + reset; organizations API with sub-account management; organization-level config support
  • Tests

    • Added coverage for webhooks, API tokens, organizations, and sub-accounts
  • Documentation / Examples

    • README updated and new example scripts demonstrating webhooks, API tokens, and sub-accounts
  • Chores

    • Environment variables for Mailtrap injected; JetBrains IDE files ignored

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 30, 2026

📝 Walkthrough

Walkthrough

Adds organization-scoped APIs (organizations.subAccounts), account-scoped webhooks and API tokens surfaces, new resource classes and types, tests and examples, README entries, and minor repo config/env updates (.envrc, .gitignore). Client gains optional organizationId and new getters for webhooks and organizations.

Changes

Organization / Webhooks / ApiTokens feature

Layer / File(s) Summary
Client config & types
src/types/mailtrap.ts
Adds optional organizationId?: number to MailtrapClientConfig.
Core client
src/lib/MailtrapClient.ts
Stores organizationId, exposes get webhooks() (account-scoped) and get organizations() (organization-scoped), and adds organization-id presence validation constant usage.
General API extension
src/lib/api/General.ts
Adds lazy apiTokens getter that validates accountId and constructs ApiTokensApi.
Base API wrappers
src/lib/api/Webhooks.ts, src/lib/api/Organizations.ts
Introduces WebhooksBaseAPI (binds WebhooksApi methods) and OrganizationsBaseAPI (exposes subAccounts).
Resource implementations
src/lib/api/resources/Webhooks.ts, src/lib/api/resources/ApiTokens.ts, src/lib/api/resources/SubAccounts.ts
Adds WebhooksApi, ApiTokensApi, and SubAccountsApi with typed methods performing Axios calls to constructed endpoints (list/create/get/update/reset/delete).
Type definitions
src/types/api/webhooks.ts, src/types/api/api-tokens.ts, src/types/api/sub-accounts.ts
New TS types for webhooks, api-tokens, and sub-accounts (requests/responses/models).
Config constants
src/config/index.ts
Adds ERRORS.ORGANIZATION_ID_MISSING constant.
Tests — base APIs & client
src/__tests__/lib/api/General.test.ts, src/__tests__/lib/api/Organizations.test.ts, src/__tests__/lib/api/Webhooks.test.ts
Adds tests validating availability of new getters, lazy instantiation, and validation errors when IDs are missing.
Tests — resources
src/__tests__/lib/api/resources/ApiTokens.test.ts, src/__tests__/lib/api/resources/SubAccounts.test.ts, src/__tests__/lib/api/resources/Webhooks.test.ts
Comprehensive axios-mock-ed tests covering success and error paths for each resource method (URL, body, response, and MailtrapError handling).
Examples & docs
examples/webhooks/everything.ts, examples/general/api-tokens.ts, examples/sub-accounts/everything.ts, README.md
Adds end-to-end example scripts for webhooks, api-tokens, and sub-accounts; updates README supported-features list to reference examples.

Environment & repo config

Layer / File(s) Summary
Envrc
.envrc
Exports Mailtrap-related environment variables: MAILTRAP_ACCOUNT_ID, MAILTRAP_ORGANIZATION_ID, MAILTRAP_API_KEY, MAILTRAP_ORGANIZATION_API_KEY sourced from 1Password references.
Gitignore
.gitignore
Adds .idea/ to ignore JetBrains IDE files.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant Client as MailtrapClient
    participant WebhooksAPI as WebhooksBaseAPI
    participant Resource as WebhooksApi
    participant HTTP as Axios

    User->>Client: access webhooks (accountId present)
    Client->>Client: checkAccountIdPresence()
    Client->>WebhooksAPI: new WebhooksBaseAPI(axios, accountId)
    WebhooksAPI->>Resource: new WebhooksApi(axios, accountId)
    WebhooksAPI-->>Client: return WebhooksBaseAPI

    User->>WebhooksAPI: getList()
    WebhooksAPI->>Resource: getList()
    Resource->>HTTP: GET /api/.../webhooks
    HTTP-->>Resource: 200 + data
    Resource-->>WebhooksAPI: typed list
    WebhooksAPI-->>User: webhook list
Loading
sequenceDiagram
    actor User
    participant Client as MailtrapClient
    participant OrgAPI as OrganizationsBaseAPI
    participant Resource as SubAccountsApi
    participant HTTP as Axios

    User->>Client: access organizations (organizationId present)
    Client->>Client: checkOrganizationIdPresence()
    Client->>OrgAPI: new OrganizationsBaseAPI(axios, orgId)
    OrgAPI->>Resource: new SubAccountsApi(axios, orgId)
    OrgAPI-->>Client: return OrganizationsBaseAPI

    User->>OrgAPI: subAccounts.create(params)
    OrgAPI->>Resource: create({ account: params })
    Resource->>HTTP: POST /api/.../organizations/{orgId}/sub-accounts
    HTTP-->>Resource: 201 + data
    Resource-->>OrgAPI: created SubAccount
    OrgAPI-->>User: SubAccount
Loading
sequenceDiagram
    actor User
    participant Client as MailtrapClient
    participant General as GeneralAPI
    participant Resource as ApiTokensApi
    participant HTTP as Axios

    User->>Client: access general.apiTokens (accountId present)
    User->>General: apiTokens.create(params)
    General->>General: checkAccountIdPresence()
    General->>Resource: new ApiTokensApi(axios, accountId)
    Resource->>HTTP: POST /api/.../api-tokens with { name, resources }
    HTTP-->>Resource: 201 + ApiTokenWithToken
    Resource-->>General: ApiTokenWithToken
    General-->>User: ApiTokenWithToken (includes token)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested labels

feature request

Suggested reviewers

  • mklocek
  • leonid-shevtsov

Poem

🐰 I hopped through code with ears held high,
New webhooks, tokens, orgs beneath the sky.
Types and tests in tidy rows,
Examples show how usage goes.
A little hop — the client’s spry!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description lists all implemented endpoints across three categories with HTTP methods, but lacks the "Motivation" and "How to test" sections specified in the template, and includes no test evidence or verification details. Add a Motivation section explaining the business need and a How to test section with concrete test steps or checkboxes to verify the implementation.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title "Add missing endpoints" accurately reflects the primary change: implementing three groups of API endpoints (Webhooks, API Tokens, and Sub-Accounts) that were previously unavailable.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch MT-21858-add-missing-endpoints

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@IgorDobryn IgorDobryn marked this pull request as ready for review April 30, 2026 09:45

constructor(client: AxiosInstance, accountId: number) {
this.client = client;
this.apiTokensURL = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/api_tokens`;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we start moving to accountId-less endpoints already?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should, but it should be done as a separate change. API is working in compatibility mode

@IgorDobryn IgorDobryn requested a review from mklocek May 4, 2026 09:13
Comment thread src/lib/api/Webhooks.ts
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/webhooks/everything.ts`:
- Line 53: The call to webhooksFlow() is invoked without handling its returned
promise which can cause unhandled promise rejections; update the invocation to
either await webhooksFlow() (if using top-level await) or append a rejection
handler like webhooksFlow().catch(err => { /* log and exit or handle error */ })
so any thrown error (e.g., in webhooksFlow or client initialization) is caught
and logged/handled; locate the webhooksFlow invocation and replace it with one
of these safe patterns and ensure the handler uses the existing logger or
process.exit as appropriate.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f34d0b69-b93c-47ed-bd8f-9ea5d0b63182

📥 Commits

Reviewing files that changed from the base of the PR and between 35d7ee4 and 1f9f47d.

📒 Files selected for processing (4)
  • README.md
  • examples/general/api-tokens.ts
  • examples/sub-accounts/everything.ts
  • examples/webhooks/everything.ts
✅ Files skipped from review due to trivial changes (2)
  • examples/sub-accounts/everything.ts
  • README.md

}
}

webhooksFlow();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add promise rejection handler to prevent unhandled rejection.

The async function is invoked without await or .catch(), which can lead to unhandled promise rejections if an error escapes the internal try/catch block (e.g., during client initialization). In Node.js 15+, unhandled rejections may terminate the process.

🛡️ Proposed fix
-webhooksFlow();
+webhooksFlow().catch((err) => {
+  console.error("Unhandled error:", err);
+  process.exit(1);
+});

Alternatively, if targeting Node.js 14.8+, use top-level await:

-webhooksFlow();
+await webhooksFlow();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
webhooksFlow();
webhooksFlow().catch((err) => {
console.error("Unhandled error:", err);
process.exit(1);
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/webhooks/everything.ts` at line 53, The call to webhooksFlow() is
invoked without handling its returned promise which can cause unhandled promise
rejections; update the invocation to either await webhooksFlow() (if using
top-level await) or append a rejection handler like webhooksFlow().catch(err =>
{ /* log and exit or handle error */ }) so any thrown error (e.g., in
webhooksFlow or client initialization) is caught and logged/handled; locate the
webhooksFlow invocation and replace it with one of these safe patterns and
ensure the handler uses the existing logger or process.exit as appropriate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants