Only show these results:

Migrate the Nylas Node.js SDK from v5 to v6

Version 6.0.0 of the Nylas Node.js SDK is a major release that brings many breaking changes from v5.x. The goal of this release was to refactor and improve the SDK to better follow TypeScript conventions. We also improved the usability for better and stricter type hinting and expected parameters.

Because of these updates, you'll need to make a few changes to your application before upgrading.

Migrate to Nylas Node.js SDK v6

To migrate from the Nylas Node.js SDK v5.x to v6, use either npm or yarn to download and install the new version of the SDK.

npm install nylas   
yarn add nylas   

Import schemas

You must import schemas for v6 of the Nylas Node.js SDK. You can import them using one of these methods:

  • Use your IDE (for example, VS Code) to automatically import schemas from /nylas/lib/models. For example, to import the schema for the File class, select nylas/lib/models/file from the suggestion list.

  • Manually add import statements for the objects that you're using from the Node.js SDK. For example, the following snippet imports the calendar-availability class.

    const Nylas = require('nylas')
    const {Days} = require('nylas/lib/models/calendar-availability')

RestfulModelCollection.build() is removed

Previously, you would create a new object by invoking the build() function and optionally passing key-value pairs that would instantiate the object with those values. This approach allowed for any value to be passed in to the object, and it bypassed any type hinting or strictness.

In v6, each model class has an accompanying interface type. The type represents the fields that the model expects and the strictness of those fields. Each model's constructor takes an optional prop object of that specific interface type.

To instantiate a new model object, you can import the model from the Nylas package and use the new keyword.

Instantiate object with no prop

The new Model(); notation creates an object whose default values are already set. These values are defined at the class level.

Instantiate object with prop

If a prop is passed to a new object (for example, Model(props);), it must match the model class' expected type, and must include all of the required properties. The prop object will set the properties of the model to its defined values.

For models that are of the RestfulModel type (Calendars, Events, Drafts), a NylasConnection object must be passed in as well. This is because these objects can be directly saved and loaded from the Nylas API.

Example: Create a Draft using Node.js SDK v5.x and v6

The following examples create and send a Draft object using the Node.js SDK v5.x and v6.

Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

/*
* Create a new Draft object.
*
* For `Draft`, the accompanying `DraftProperties` type outlines all the fields and, at the very
* least, you must provide a 'to' field.
*/


const draftProperties = {
to: [{ name: 'Nylas Swag', email: '[email protected]' }],
subject: 'With Love, From Nylas',
body: 'This email was sent using the Nylas Email API. Visit https://nylas.com for details.',
files: [{ id: '{file_id}' }],
replyToMessageId: '<message_id>'
}

/*
* Note that because `Draft` is a `RestfulModel` type, we must pass a `NylasConnection` type.
*
* Pass in the 'draftProperties' from above to initialize our `Draft` object with the desired values.
*/

const draft = new Draft(nylas, draftProperties);

// Save the Draft to send it.
draft.save()
Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

// Create a new Draft object.
const draft = nylas.drafts.build({
to: [{ name: 'Nylas Swag', email: '[email protected]' }],
subject: 'With Love, From Nylas',
body: 'This email was sent using the Nylas email API. Visit https://nylas.com for details.',
files: [{ id: '{file_id}' }],
replyToMessageId: '<message_id>'
});

// Save the Draft to send it.
draft.save()

All classes and properties in the v6 example are exported by the package and can be imported to your application for your use.

Type changes

The Node.js SDK now has more typing, which covers return types for functions and proper typing for attributes. With this change, we identified a few properties that were too abstract or well-defined and turned them into Model type classes.

Event.when properties changed to when

You can specify an Event's when properties when it's being initialized using WhenProperties. You can also set the when properties after you create an empty Event.

The helper-setter functions Event.start() and Event.end() are still available in v6.

The following examples demonstrate how to set the when properties in the Node.js SDK v6.

Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

const eventProperties = {
calendarId: '{CALENDAR_ID}',
when: {
startTime: 1577829600,
endTime: 1577840400,
startDate: '2022-08-29',
endDate: '2022-09-01'
},
title: 'Party!',
location: 'My House!',
description: 'Let\'s celebrate our calendar integration!!',
busy: true
}

const event = new Event(nylas, eventProperties);
Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

const event = new Event(nylas);
event.calendarId = '{CALENDAR_ID}';
event.when.startTime = 1577829600;
event.when.endTime = 1577840400;
event.when.startDate = '2022-08-29';
event.when.endDate = '2022-09-01';
event.title = 'Party!';
event.location = 'My House!';
event.description = 'Let\'s celebrate our calendar integration!!';
event.busy = true;
Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

const event = new Event(nylas);
event.calendarId = '{CALENDAR_ID}';
event.start = 1577829600;
event.end = 1577840400;
event.title = 'Party!';
event.location = 'My House!';
event.description = 'Let\'s celebrate our calendar integration!!';
event.busy = true;

Neural Message Options interface class changed to model class

Previously, NeuralMessageOptions was an interface class. As of the Node.js SDK v6, it is a model class.

The following example uses the NeuralMessageOptions class to extract a signature from a message.

Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

const extractedSignature = nylas.neural.extractSignature(['MESSAGE_ID'], {
ignoreImages: true,
ignoreLinks: true,
ignoreTables: true,
imagesAsMarkdown: true,
});

When you call the neural.extractSignature() function, the options parameter is of the NeuralMessageOptionsProperties type instead of NeuralMessageOptions. This means that options' key values are defined in camelCase instead of snake_case for consistency.

New model classes for Calendar Restful Model Collection functions

The CalendarRestfulModelCollection class has these functions for scheduling-related operations:

  • .freeBusy()
  • .availability()
  • .consecutiveAvailability()

Previously, these functions provided limited type hinting, limited hinting for request parameters, and no structure for the object that is returned from the API. Nylas would simply return JSON.

As of the Node.js SDK v6, Nylas provides an interface type for each method's options parameter, as well as a Model representing the expected API response.

Free-busy function changes

In v6, the .freeBusy() function expects options to be an object that matches FreeBusyQuery. .freeBusy() returns a FreeBusy response.

The example below demonstrates how to use the .freeBusy() function in the Node.js SDK v6.

Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

const freeBusy: FreeBusy[] = await nylas.calendars.freeBusy({
startTime: 1577829600,
endTime: 1577840400,
emails: ['[email protected]']
})
const email = freeBusy[0].email;
const timeSlot: TimeSlot = freeBusy[0].timeSlots[0];
const timeSlotStatus = timeSlot.status;
const timeSlotStartTime = timeSlot.startTime;
const timeSlotEndTime = timeSlot.status;

Availability function changes

In v6, the .availability() function expects options to be an object that matches SingleAvailabilityQuery. .availability() returns a CalendarAvailability response.

In SingleAvailabilityQuery, freeBusy is of the FreeBusyProperties type and openHours is of the OpenHoursProperties type. To make things easier when setting openHours, you can set the days property using the Days enum. This correctly formats the day of the week to its corresponding numerical value instead of referring back to the API reference.

The following example demonstrates how to use the .availability() function in the Node.js SDK v6.

Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

const availability: CalendarAvailability = await nylas.calendars.availability({
startTime: 1590454800,
endTime: 1590780800,
interval: 5,
duration: 30,
emails: ['[email protected]'],
openHours: [
{
emails: ['[email protected]'],
days: [Days.Sunday],
timezone: 'America/Chicago',
start: '10:00',
end: '14:00',
},
],
});
const timeSlot = availability.timeSlots[0];
const timeSlotStatus = timeSlot.status;
const timeSlotStartTime = timeSlot.startTime;
const timeSlotEndTime = timeSlot.status;

Consecutive Availability function changes

In v6, the .consecutiveAvailability() function expects options to be objects that match ConsecutiveAvailabilityQuery. .consecutiveAvailability() returns a CalendarConsecutiveAvailability response.

The example below demonstrates how to use the .consecutiveAvailability() function in the Node.js SDK v6.

Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

// Consecutive availability.
const consecutiveAvailability: CalendarConsecutiveAvailability = await nylas.calendars.consecutiveAvailability({
startTime: 1590454800,
endTime: 1590780800,
interval: 5,
duration: 30,
emails: [['[email protected]'], ['[email protected]']],
openHours: [
{
emails: ['[email protected]', '[email protected]'],
days: [Days.Sunday],
timezone: 'America/Chicago',
start: '10:00',
end: '14:00',
},
],
});
const emails = consecutiveAvailability.emails;
const startTime = consecutiveAvailability.startTime;
const endTime = consecutiveAvailability.endTime;

Changes to Connect functions

The v6 update includes changes to the connect.authorize() and connect.token() functions.

Connect Authorize function changes

In v6, connect.authorize() takes new parameter types and a new return type. When sending authorization, the auth parameter takes either a VirtualCalendarProperties or NativeAuthenticationProperties type, depending on the type of authentication that needs to be performed. In both cases, the return is an AuthorizationCode type. This is an object that contains one key: a code (string).

For convenience, we've also provided two useful enum types that you can import and use in your application. Scope provides all possible authorization scopes, and NativeAuthenticationProvider contains all of the providers supported by native authentication.

The following example demonstrates how to use connect.authorize() in the Node.js SDK v6.

// For Virtual Calendar authorization.
const virtualCalendarAuth = await Nylas.connect.authorize({
name: "Virtual Calendar",
emailAddress: "virtual_account_unique_id",
clientId: "CLIENT_ID", // Note that clientId is optional. Defaults to the clientId configured in Nylas.config().
});
const code = virtualCalendarAuth.code;

// For other authorization.
const googleAuth = await Nylas.connect.authorize({
clientId: "CLIENT_ID",
emailAddress: "[email protected]",
scopes: [Scope.EmailReadOnly, Scope.CalendarReadOnly, Scope.ContactsReadOnly],
name: "Google",
provider: NativeAuthenticationProvider.Gmail,
settings: {
google_client_id: "{google_api_client_id}",
google_client_secret: "{geoogle_api_client_secret}",
google_refresh_token: "{google_api_refresh_token}"
}
});
const code = googleAuth.code;

Connect Token function changes

Previously, exchanging a token would result in the Nylas API returning a JSON response. The object returned from the API was actually an account object, however. In v6, instead of the SDK returning a JSON response of any type or an unknown type, it now returns an Account type response.

Nylas.application() takes camel case parameters only

Previously, the Nylas.application() function's options parameter took both camelCase and snake_case parameters. To eliminate confusion and improve consistency, we've removed the snake_case parameters. Nylas.application() now takes the applicationName and redirectUris parameters only.

Removed functions

In addition to the RestfulModelCollection.build() function, we've removed other functions from the Node.js SDK v6:

  • Connect.newAccount(): The function body was empty and commented out, and therefore had no purpose.
  • File.metadata(): This is the same as making a nylas.files.find(``'``ID``'``); call and is redundant.

These functions being removed should have little to no impact on your implementation.