Nylas Node.js SDK

repository·main·Indexed 41 days ago

https://github.com/nylas/nylas-nodejs

A NodeJS wrapper for the Nylas REST API (version 8.4.0) providing a programmatic interface to integrate with email, calendar, and contact providers such as Gmail, Microsoft, and Zoom.

Tokens
29.4K
Snippets
100
Records
146
Agent score
52%

What's inside Nylas

  1. Capabilities demonstrated in the Messages example

    main

    The Messages example provides implementation patterns for the following features:

    • Message Fields: Querying messages using various field options.
    • Tracking Options: Viewing tracking data within message responses.
    • Raw MIME: Retrieving raw MIME data for messages.
    • Message Operations: Performing operations such as listing, finding, updating, and sending messages.
    • Scheduled Messages: Managing scheduled message functionality.
    • Message Cleaning: Utilizing the clean messages API.
  2. Use the `singleLevel` parameter to control folder hierarchy

    main

    The singleLevel parameter is a query parameter for the nylas.folders.list method that controls how the folder hierarchy is traversed. Note that this parameter is only supported for Microsoft accounts; it is ignored for other providers.

    • singleLevel: true: Retrieves folders from a single-level hierarchy only (direct children of the specified parentId). This is useful for building UI tree views or optimizing performance.
    • singleLevel: false (default): Retrieves folders across a multi-level hierarchy (all descendants).
    // Get only direct children of a specific folder
    const singleLevelFolders = await nylas.folders.list({
      identifier: 'grant-id',
      queryParams: {
        parentId: 'parent-folder-id',
        singleLevel: true
      }
    });
    
    // Get all descendants (default behavior)
    const allFolders = await nylas.folders.list({
      identifier: 'grant-id',
      queryParams: {
        parentId: 'parent-folder-id',
        singleLevel: false // or omit this parameter
      }
    });
  3. Securely Manage Environment Variables

    main

    Never hardcode Nylas API keys or credentials. Use the following patterns for environment variable management:

    • Local Development: Use a .dev.vars file to store secrets.
    • Production: Use wrangler secret to upload secrets to the Cloudflare edge environment.
    • Validation: Ensure input validation is performed on the server side, checking for required fields and ensuring start_date occurs before end_date.
  4. Understand the Calendar Manager Architecture

    main

    The application follows a request-response flow through the edge network:

    Flow: User Browser $\rightarrow$ Cloudflare Worker (Vite) $\rightarrow$ Nylas API $\rightarrow$ Calendar Provider (e.g., Google, Microsoft).

    Key Components

    • Web Interface: An HTML/CSS/JS interface served by the worker.
    • API Endpoints:
      • GET /: Serves the UI.
      • GET /api/events: Lists calendar events.
      • POST /api/events: Creates a new calendar event.
      • OPTIONS /*: Handles CORS preflight.
    • Nylas SDK: Integrated within src/worker.ts to handle authentication and communication with the Nylas API.
    • Node.js Compatibility: The worker requires nodejs_compat and a recent compatibility_date in wrangler.toml to support the Nylas SDK's use of Node.js built-ins like crypto, buffer, and stream.
  5. Use specialized Request Models

    main

    The SDK has moved away from large, monolithic models. Instead, it uses specific TypeScript interfaces for different operations to ensure type safety and clarity.

    For example, instead of a single Calendar model, the SDK provides:

    • Calendar: For retrieving an existing calendar.
    • CreateCalendarRequest: For creating a new calendar (contains required fields like name).
    • UpdateCalendarRequest: For updating an existing calendar (all fields are optional).

    Models are now pure TypeScript interfaces and no longer contain methods like .save(). To perform actions, use the corresponding methods on the resource class (e.g., .create(), .update(), .destroy()).

    // Import only required if you need the typing
    import { CreateCalendarRequest, UpdateCalendarRequest } from "nylas/lib/types/models/calendars";
    
    const createCalendarRequest: CreateCalendarRequest = {
      name: "My Calendar", // Calendar name is required
      description: "This is my calendar", // Calendar description is optional
      location: "My calendar location", // Calendar location is optional
      timezone: "America/New_York", // Calendar timezone is optional,
    }
    
    const updateCalendarRequest: UpdateCalendarRequest = {
      name: "My Updated Calendar", // All fields are optional since we are updating
      hexColor: "#000000", // Other fields not present during creation are now available
    }
  6. How the Nylas SDK handles large email attachments

    main

    The Nylas SDK includes logic to prevent Lambda functions from freezing when sending emails with multiple attachments that exceed a specific size threshold. The SDK automatically switches encoding methods based on the total payload size:

    • Total payload < 3MB: Uses JSON encoding (faster and simpler).
    • Total payload ≥ 3MB: Uses multipart/form-data encoding (handles larger files).

    This automatic switching is handled internally by the SDK (specifically within calculateTotalPayloadSize() in src/resources/messages.ts) when calling nylas.messages.send().

    // The SDK automatically chooses encoding based on total payload size
    const response = await nylas.messages.send({
      identifier: env.NYLAS_GRANT_ID,
      requestBody: sendRequest,
    });
  7. How the Cloudflare Worker handles email attachments

    main

    This implementation optimizes the Nylas SDK for the Cloudflare Workers runtime using the following architecture:

    • Node.js Compatibility: The worker requires compatibility_date = "2024-09-23" (or later) and the nodejs_compat flag in wrangler.toml to support built-in modules like crypto, path, fs, and stream required by the Nylas SDK.
    • Efficient Binary Transfer: Instead of using base64 encoding (which adds ~33% overhead), the worker converts files into native Buffer objects for direct binary transfer.
    • Data Flow: User Browser → Cloudflare Worker → Nylas API → Email Provider.
    • Endpoints:
      • GET /: Serves the HTML upload interface.
      • POST /send-attachment: Processes multipart form data and sends the email.
      • OPTIONS /*: Handles CORS preflight requests.
  8. Handle Response Objects

    main

    The Nylas API v3 uses two primary response types:

    1. NylasResponse<T>: Used for requests returning a single object (e.g., retrieving one calendar). It contains the parameterized object of type T and a requestId string.
    2. NylasListResponse<T>: Used for requests returning a list of objects. It contains a list of objects of type T, a requestId string, and a nextCursor token used for pagination.
  9. What are Nylas Grants?

    main

    In the Nylas API, a Grant represents an authenticated connection to a user's email or calendar account (e.g., Gmail, Outlook, Yahoo).

    Each grant object contains:

    • Authentication details: OAuth tokens and provider information.
    • Scope permissions: The specific data access levels (email, calendar, contacts, etc.).
    • Account metadata: Email address, provider type, and timestamps.
    • Status information: Whether the connection is currently valid, invalid, or expired.
  10. Quick Start: Setup the Nylas AWS Lambda Email Attachments Example

    main

    To set up the AWS Lambda example for sending email attachments, you can use the interactive setup which automates prerequisite checks, Nylas credential configuration, AWS credential configuration, and .env file creation.

    1. Navigate to the directory:
      cd examples/aws-lambda
    2. Run the setup command:
      npm run setup

    Manual Setup

    If you prefer manual configuration:

    1. Install dependencies: npm install in the examples/aws-lambda directory.
    2. Configure Environment Variables: Create a .env file with NYLAS_API_KEY, NYLAS_API_URI, and NYLAS_GRANT_ID.
    3. Configure AWS Credentials: Use aws configure, set environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION), or create a ~/.aws/credentials file.
    4. Deploy: Run npm run deploy to build with esbuild and deploy via the Serverless Framework.
    # Navigate to the aws-lambda directory
    cd examples/aws-lambda
    
    # Run the interactive setup
    npm run setup
  11. Develop and Test the Calendar Manager locally

    main

    To start the local development environment, run:

    npm run dev

    This starts the Vite development server with Cloudflare Workers support, enabling Hot Module Replacement (HMR). The worker will be available at http://localhost:5173 and will load environment variables from .dev.vars.

    Testing the UI

    1. Open http://localhost:5173 in your browser.
    2. Load Events: Click "Load Events" to fetch existing calendar events.
    3. Create Event: Use the form to add a new event with a title, description, start/end times, and location.
    4. Refresh: The list should automatically refresh upon successful creation.