nylas / nylas-nodejs

A NodeJS wrapper for the Nylas REST API for email, contacts, and calendar.
MIT License
169 stars 118 forks source link

[v7.0.0] Implement callback instead of event emitter for mailbox token exchange #376

Closed mrashed-dev closed 2 years ago

mrashed-dev commented 2 years ago

Description

To ensure that the token exchange response is properly overridden, we need to use a callback instead of emitting an event as we can’t guarantee that the event gets emitted in-order before we return the response from the API. Especially if the user wants to implement any async code.

Usage

Now, when configuring your server binding, exchangeMailboxTokenCallback is a required field and takes a reference to a function that accepts two parameters; accessToken: AccessToken, res: ServerResponse. Currently, ServerResponse is just Express.Response but it will be expanded to include the response object of other frameworks.

const express = require('express');

const Nylas = require('nylas');
const { Scope } = require('nylas/lib/models/connect');
const { ServerBindings } = require('nylas/lib/config');

// Initialize an instance of the Nylas SDK using the client credentials
const nylasClient = new Nylas({
    clientId: clientId,
    clientSecret: clientSecret,
});

const app = express();

const exchangeMailboxTokenCallback = async (accessTokenObj, res) => {
    const accessToken = accessTokenObj.accessToken
    const emailAddress = accessTokenObj.emailAddress

    user = await db.createUser({
        accessToken,
        emailAddress,
    })

    res.json({
        id: user.id,
        emailAddress: user.emailAddress,
    });
}

const expressBinding = new ServerBindings.express(nylasClient, {
    defaultScopes: [
        Scope.EmailModify,
        Scope.EmailSend,
    ],
    exchangeMailboxTokenCallback,
});
const nylasMiddleware = expressBinding.buildMiddleware();
app.use('/nylas', nylasMiddleware);

License

I confirm that this contribution is made under the terms of the MIT license and that I have the authority necessary to make this contribution on behalf of its copyright owner.