diff --git a/CHANGELOG.md b/CHANGELOG.md index 9572c312..28279498 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- Added Events batch endpoint (Google and Microsoft). - Add `EventResource` and optional `resources` fields to event response, create, and update models for room/resource booking (CUST-5373) - Add optional `trackingOptions.domainName` support for custom link and open tracking hostnames - Add Contact metadata request/response types and `metadataPair` filtering, with contact webhook compatibility documentation diff --git a/examples/calendars/event_batch.ts b/examples/calendars/event_batch.ts new file mode 100644 index 00000000..9bc78924 --- /dev/null +++ b/examples/calendars/event_batch.ts @@ -0,0 +1,90 @@ +import dotenv from 'dotenv'; +import path from 'path'; +import Nylas, { BatchEventOperation } from 'nylas'; + +// From examples/: npx ts-node calendars/event_batch.ts +// Set NYLAS_API_KEY, NYLAS_GRANT_ID, and NYLAS_CALENDAR_ID in examples/.env. +// NYLAS_UPDATE_EVENT_ID and NYLAS_DELETE_EVENT_ID must name distinct existing events. +async function main(): Promise { + dotenv.config({ path: path.resolve(__dirname, '../.env') }); + + const apiKey = process.env.NYLAS_API_KEY || ''; + const grantId = process.env.NYLAS_GRANT_ID || ''; + const calendarId = process.env.NYLAS_CALENDAR_ID || ''; + const updateEventId = process.env.NYLAS_UPDATE_EVENT_ID || ''; + const deleteEventId = process.env.NYLAS_DELETE_EVENT_ID || ''; + const apiUri = process.env.NYLAS_API_URI || 'https://api.us.nylas.com'; + + if ( + [apiKey, grantId, calendarId, updateEventId, deleteEventId].some( + (value) => !value.trim() + ) || + updateEventId === deleteEventId || + (apiUri !== 'https://api.us.nylas.com' && + apiUri !== 'https://api.eu.nylas.com') + ) { + throw new Error('Invalid example configuration.'); + } + + const nylas = new Nylas({ apiKey, apiUri }); + const queryParams = { calendarId }; + const startTime = Math.floor(Date.now() / 1000) + 24 * 60 * 60; + const operations: BatchEventOperation[] = [ + { + method: 'create', + body: { + title: 'Standup', + when: { startTime, endTime: startTime + 30 * 60 }, + }, + }, + { method: 'update', eventId: updateEventId, body: { title: 'Renamed' } }, + { method: 'delete', eventId: deleteEventId }, + ]; + const result = await nylas.events.batch({ + identifier: grantId, + queryParams, + requestBody: { operations }, + }); + + // HTTP 207 returns normally, even if every operation failed. + // Results correspond to operations at the same index. + const retryOperations: BatchEventOperation[] = []; + let retryDelay = 0; + for (const [index, item] of result.data.entries()) { + console.log(`Operation ${index}: ${item.status}`); + + // Never retry: the provider created the event before a later step failed. + if (item.providerEventCreated) continue; + if (item.status !== 429 && item.status !== 503) continue; + if ( + typeof item.retryAfter !== 'number' || + !Number.isFinite(item.retryAfter) || + item.retryAfter < 0 + ) { + continue; + } + + retryOperations.push(operations[index]); + retryDelay = Math.max(retryDelay, item.retryAfter); + } + + // One caller-controlled retry after the provider delay, including zero. + // Longer delays need application scheduling; Node timers would truncate them. + if (retryOperations.length === 0 || retryDelay * 1000 > 2 ** 31 - 1) return; + await new Promise((resolve) => setTimeout(resolve, retryDelay * 1000)); + const retried = await nylas.events.batch({ + identifier: grantId, + queryParams, + requestBody: { operations: retryOperations }, + }); + for (const [index, item] of retried.data.entries()) { + console.log(`Retry ${index}: ${item.status}`); + } +} + +if (require.main === module) { + main().catch(() => { + console.error('Unable to complete the batch example.'); + process.exitCode = 1; + }); +} diff --git a/src/models/events.ts b/src/models/events.ts index 00302c4f..396d0f6d 100644 --- a/src/models/events.ts +++ b/src/models/events.ts @@ -274,6 +274,48 @@ export type UpdateEventRequest = Omit< resources?: EventResource[]; }; +/** + * An event operation in a batch. Results are returned in the order provided. + */ +export type BatchEventOperation = + | { method: 'create'; body: CreateEventRequest } + | { method: 'update'; eventId: string; body: UpdateEventRequest } + | { method: 'delete'; eventId: string }; + +/** + * Request to create, update, or delete events in a single call. + * Batch size and operation validity are checked by the API. + */ +export interface BatchEventsRequest { + operations: BatchEventOperation[]; +} + +/** + * The result of the operation at the same index in the request. + */ +export interface BatchEventResult { + /** The HTTP status of this operation. */ + status: number; + /** The Event from a successful create or update; absent for a delete. */ + data?: Event; + /** Error details for a failed operation. */ + error?: NylasApiErrorResponseData; + /** Seconds to wait before retrying a throttled operation; may be zero. */ + retryAfter?: number; + /** + * The provider created the event before a later step failed. + * Never retry this operation: doing so would create a duplicate. + */ + providerEventCreated?: boolean; +} + +/** + * A batch response, including failed operations returned with HTTP 207. + */ +export interface BatchEventsResponse extends NylasBaseResponse { + data: BatchEventResult[]; +} + /** * Interface representing a request to send RSVP to an event. */ @@ -426,6 +468,17 @@ export type UpdateEventQueryParams = CreateEventQueryParams; */ export type DestroyEventQueryParams = CreateEventQueryParams; +/** + * Query parameters applied to every operation in an Events batch. + * Participant notifications default to true; Microsoft rejects false. + */ +export interface BatchEventsQueryParams extends CreateEventQueryParams { + /** The email address of the grant to use. */ + grantEmail?: string; + /** Comma-separated fields to include in each returned Event. */ + select?: string; +} + /** * Interface representing of the query parameters for sending RSVP to an event. */ diff --git a/src/resources/events.ts b/src/resources/events.ts index 4bc82a7d..4e2efbc4 100644 --- a/src/resources/events.ts +++ b/src/resources/events.ts @@ -1,5 +1,8 @@ import { Overrides } from '../config.js'; import { + BatchEventsQueryParams, + BatchEventsRequest, + BatchEventsResponse, CreateEventQueryParams, CreateEventRequest, DestroyEventQueryParams, @@ -52,6 +55,17 @@ export interface CreateEventParams { queryParams: CreateEventQueryParams; } +/** + * @property identifier The identifier of the grant to act upon + * @property requestBody The ordered event operations to execute + * @property queryParams The query parameters applied to every operation + */ +export interface BatchEventsParams { + identifier: string; + requestBody: BatchEventsRequest; + queryParams: BatchEventsQueryParams; +} + /** * @property identifier The identifier of the grant to act upon * @property eventId The id of the Event to retrieve. @@ -179,6 +193,39 @@ export class Events extends Resource { }); } + /** + * Create, update, or delete events in a single call (Google and Microsoft). + * HTTP 207 responses return normally; inspect each result's status and error. + * Operations are not automatically retried or split into smaller batches. + * @return The ordered results of the batch operations + */ + public batch({ + identifier, + requestBody, + queryParams, + overrides, + }: BatchEventsParams & Overrides): Promise { + // URL parsing normalizes dot segments, including encoded dots. Reject them + // before they can change the grant-scoped request path. + if ( + typeof identifier !== 'string' || + !identifier.trim() || + /^(?:\.|%2e){1,2}$/i.test(identifier) + ) { + throw new TypeError('Invalid grant identifier.'); + } + + return this.apiClient.request({ + method: 'POST', + path: makePathParams('/v3/grants/{identifier}/events/batch', { + identifier, + }), + queryParams, + body: requestBody, + overrides, + }); + } + /** * Update an Event * @return The updated Event diff --git a/src/utils.ts b/src/utils.ts index 5e65c724..6e8c7fd3 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -163,7 +163,7 @@ function convertCase( newObj[applyCasing(casingFunction, key)] = (obj[key] as any[]).map( (item) => { if (typeof item === 'object') { - return convertCase(item, casingFunction); + return convertCase(item, casingFunction, excludeKeys); } else { return item; } @@ -172,7 +172,8 @@ function convertCase( } else if (typeof obj[key] === 'object' && obj[key] !== null) { newObj[applyCasing(casingFunction, key)] = convertCase( obj[key] as Record, - casingFunction + casingFunction, + excludeKeys ); } else { newObj[applyCasing(casingFunction, key)] = obj[key]; diff --git a/tests/resources/eventBatch.spec.ts b/tests/resources/eventBatch.spec.ts new file mode 100644 index 00000000..93a21905 --- /dev/null +++ b/tests/resources/eventBatch.spec.ts @@ -0,0 +1,334 @@ +import fetchMock from 'jest-fetch-mock'; +import APIClient from '../../src/apiClient'; +import { Events } from '../../src/resources/events'; +import { + BatchEventOperation, + BatchEventsQueryParams, + BatchEventsRequest, + BatchEventsResponse, + Event, + NylasApiError, +} from '../../src/nylas'; + +// These assignments are checked by ts-jest as part of the test suite. +// @ts-expect-error A create operation needs an event body. +const createWithoutBody: BatchEventOperation = { method: 'create' }; +// @ts-expect-error An update operation needs an event ID. +const updateWithoutId: BatchEventOperation = { + method: 'update', + body: { title: 'Renamed' }, +}; +// @ts-expect-error An update operation needs a body. +const updateWithoutBody: BatchEventOperation = { + method: 'update', + eventId: 'event-updated', +}; +// @ts-expect-error A delete operation needs an event ID. +const deleteWithoutId: BatchEventOperation = { method: 'delete' }; +const invalidMethod: BatchEventOperation = { + // @ts-expect-error Batch operations use a literal method allow-list. + method: 'patch', + eventId: 'event', +}; +// @ts-expect-error Every batch must identify a calendar. +const queryWithoutCalendar: BatchEventsQueryParams = {}; +void createWithoutBody; +void updateWithoutId; +void updateWithoutBody; +void deleteWithoutId; +void invalidMethod; +void queryWithoutCalendar; + +describe('Events batch', () => { + const metadata = { externalRecordId: 'record-fixture', custom_key: 'value' }; + const eventJson = { + id: 'event-created', + grant_id: 'grant-fixture', + calendar_id: 'primary', + object: 'event', + busy: true, + read_only: false, + participants: [], + visibility: 'public', + when: { + start_time: 1798794000, + end_time: 1798795800, + object: 'timespan', + }, + metadata, + }; + const requestBody: BatchEventsRequest = { + operations: [ + { + method: 'create', + body: { + title: 'Standup', + when: { startTime: 1798794000, endTime: 1798795800 }, + hideParticipants: true, + metadata, + }, + }, + { + method: 'update', + eventId: 'event-updated', + body: { title: 'Renamed' }, + }, + { method: 'delete', eventId: 'event-deleted' }, + ], + }; + const queryParams = { calendarId: 'primary' }; + let events: Events; + + beforeEach(() => { + fetchMock.resetMocks(); + events = new Events( + new APIClient({ + apiKey: '', + apiUri: 'https://example.invalid', + timeout: 30, + headers: {}, + }) + ); + }); + + it.each([ + undefined, + null, + 123, + {}, + '', + ' \t\n', + '.', + '..', + '%2e', + '%2E%2e', + '.%2e', + '%2e.', + ])( + 'rejects an invalid grant identifier before sending HTTP: %p', + (identifier) => { + expect(() => + events.batch({ + identifier: identifier as unknown as string, + queryParams, + requestBody, + }) + ).toThrow(new TypeError('Invalid grant identifier.')); + expect(fetchMock).not.toHaveBeenCalled(); + } + ); + + it('sends all operations and shared query parameters with wire casing and overrides', async () => { + fetchMock.mockResponseOnce( + JSON.stringify({ request_id: 'request-fixture', data: [] }) + ); + + await events.batch({ + identifier: 'grant/fixture', + queryParams: { + ...queryParams, + notifyParticipants: false, + tentativeAsBusy: false, + grantEmail: 'grant@example.com', + select: 'id,title', + }, + requestBody, + overrides: { + apiUri: 'https://override.example.invalid', + headers: { 'X-Custom-Header': 'batch-fixture' }, + }, + }); + + const request = fetchMock.mock.calls[0][0] as Request; + const url = new URL(request.url); + expect(request.method).toBe('POST'); + expect(url.origin).toBe('https://override.example.invalid'); + expect(url.pathname).toBe('/v3/grants/grant%2Ffixture/events/batch'); + expect(Object.fromEntries(url.searchParams)).toEqual({ + calendar_id: 'primary', + notify_participants: 'false', + tentative_as_busy: 'false', + grant_email: 'grant@example.com', + select: 'id,title', + }); + expect(request.headers.get('x-custom-header')).toBe('batch-fixture'); + expect(request.headers.get('content-type')).toBe('application/json'); + expect(JSON.parse(await request.text())).toEqual({ + operations: [ + { + method: 'create', + body: { + title: 'Standup', + when: { start_time: 1798794000, end_time: 1798795800 }, + hide_participants: true, + metadata, + }, + }, + { + method: 'update', + event_id: 'event-updated', + body: { title: 'Renamed' }, + }, + { method: 'delete', event_id: 'event-deleted' }, + ], + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('returns typed create/update events and an empty delete result in request order for 200', async () => { + fetchMock.mockResponseOnce( + JSON.stringify({ + request_id: 'request-fixture', + data: [ + { status: 200, data: eventJson }, + { + status: 200, + data: { ...eventJson, id: 'event-updated', title: 'Renamed' }, + }, + { status: 200 }, + ], + }), + { status: 200 } + ); + + const result: BatchEventsResponse = await events.batch({ + identifier: 'grant-fixture', + queryParams, + requestBody, + }); + const createdEvent: Event | undefined = result.data[0].data; + expect(result.requestId).toBe('request-fixture'); + expect(result.data).toHaveLength(requestBody.operations.length); + expect(result.data.map((item) => item.data?.id)).toEqual([ + 'event-created', + 'event-updated', + undefined, + ]); + expect(createdEvent?.grantId).toBe('grant-fixture'); + expect(createdEvent?.readOnly).toBe(false); + expect(createdEvent?.when).toEqual({ + startTime: 1798794000, + endTime: 1798795800, + object: 'timespan', + }); + expect(createdEvent?.metadata).toEqual(metadata); + expect(result.data[1].data?.title).toBe('Renamed'); + expect(result.data[2].data).toBeUndefined(); + expect(result).not.toHaveProperty('nextCursor'); + const request = fetchMock.mock.calls[0][0] as Request; + expect(new URL(request.url).searchParams.has('notify_participants')).toBe( + false + ); + }); + + it('returns mixed 207 results including provider errors and zero retry delay without retrying', async () => { + fetchMock.mockResponseOnce( + JSON.stringify({ + request_id: 'request-mixed', + data: [ + { status: 200, data: eventJson }, + { + status: 503, + error: { + type: 'provider_error', + message: 'Try again later', + provider_error: { error_code: 'unavailable' }, + }, + retry_after: 0, + provider_event_created: true, + }, + { + status: 404, + error: { type: 'not_found_error', message: 'Event not found' }, + }, + ], + }), + { status: 207 } + ); + + const result = await events.batch({ + identifier: 'grant-fixture', + queryParams, + requestBody, + }); + + expect(result.requestId).toBe('request-mixed'); + expect(result.data.map((item) => item.status)).toEqual([200, 503, 404]); + expect(result.data[1]).toEqual({ + status: 503, + error: { + type: 'provider_error', + message: 'Try again later', + providerError: { errorCode: 'unavailable' }, + }, + retryAfter: 0, + providerEventCreated: true, + }); + expect(result.data[2].error?.type).toBe('not_found_error'); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('returns normally when every operation in a 207 response failed', async () => { + fetchMock.mockResponseOnce( + JSON.stringify({ + request_id: 'request-failed', + data: [ + { + status: 429, + error: { type: 'rate_limit_error', message: 'Slow down' }, + retry_after: 5, + }, + { + status: 503, + error: { type: 'provider_error', message: 'Unavailable' }, + }, + { + status: 404, + error: { type: 'not_found_error', message: 'Event not found' }, + }, + ], + }), + { status: 207 } + ); + + const result = await events.batch({ + identifier: 'grant-fixture', + queryParams, + requestBody, + }); + + expect(result.requestId).toBe('request-failed'); + expect(result.data.map((item) => item.status)).toEqual([429, 503, 404]); + expect(result.data[0].retryAfter).toBe(5); + expect(result.data.every((item) => item.error !== undefined)).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('throws the standard API error for a rejected batch request', async () => { + fetchMock.mockResponseOnce( + JSON.stringify({ + request_id: 'request-invalid', + error: { + type: 'invalid_request_error', + message: 'Invalid batch request', + }, + }), + { status: 400, headers: { 'x-request-id': 'request-invalid' } } + ); + + const result = events.batch({ + identifier: 'grant-fixture', + queryParams, + requestBody: { operations: [] }, + }); + + await expect(result).rejects.toBeInstanceOf(NylasApiError); + await expect(result).rejects.toMatchObject({ + statusCode: 400, + requestId: 'request-invalid', + type: 'invalid_request_error', + message: 'Invalid batch request', + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/tests/utils.spec.ts b/tests/utils.spec.ts index 2b5c07d0..abb4065c 100644 --- a/tests/utils.spec.ts +++ b/tests/utils.spec.ts @@ -145,6 +145,30 @@ describe('convertCase', () => { expect(result).toEqual({ first_name: 'John', lastName: 'Doe' }); }); + it('preserves excluded metadata keys inside nested objects and arrays', () => { + const metadata = { + externalRecordId: 'record-fixture', + custom_key: 'value', + }; + const request = { + operations: [ + { method: 'create', body: { hideParticipants: true, metadata } }, + ], + }; + expect(objKeysToSnakeCase(request, ['metadata'])).toEqual({ + operations: [ + { method: 'create', body: { hide_participants: true, metadata } }, + ], + }); + expect( + objKeysToCamelCase({ data: [{ data: { read_only: false, metadata } }] }, [ + 'metadata', + ]) + ).toEqual({ + data: [{ data: { readOnly: false, metadata } }], + }); + }); + it('should handle null and undefined values in camelCase conversion', () => { const obj = { first_name: 'John', address_data: null, user_age: undefined }; const result = objKeysToCamelCase(obj);