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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
90 changes: 90 additions & 0 deletions examples/calendars/event_batch.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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;
});
}
53 changes: 53 additions & 0 deletions src/models/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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.
*/
Expand Down
47 changes: 47 additions & 0 deletions src/resources/events.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Overrides } from '../config.js';
import {
BatchEventsQueryParams,
BatchEventsRequest,
BatchEventsResponse,
CreateEventQueryParams,
CreateEventRequest,
DestroyEventQueryParams,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<BatchEventsResponse> {
// 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<BatchEventsResponse>({
method: 'POST',
path: makePathParams('/v3/grants/{identifier}/events/batch', {
identifier,
}),
queryParams,
body: requestBody,
overrides,
});
}

/**
* Update an Event
* @return The updated Event
Expand Down
5 changes: 3 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -172,7 +172,8 @@ function convertCase(
} else if (typeof obj[key] === 'object' && obj[key] !== null) {
newObj[applyCasing(casingFunction, key)] = convertCase(
obj[key] as Record<string, unknown>,
casingFunction
casingFunction,
excludeKeys
);
} else {
newObj[applyCasing(casingFunction, key)] = obj[key];
Expand Down
Loading
Loading