Giter Site home page Giter Site logo

nylas-nodejs's Introduction

Aimeos logo

Nylas Node.js SDK

npm codecov

This is the GitHub repository for the Nylas Node SDK. This repo is primarily for anyone who wants to make contributions to the SDK, or install it from source. If you are looking to use Node to access the Nylas Email, Calendar, or Contacts API you should refer to our official Node SDK Quickstart Guide.

The Nylas Communications Platform provides REST APIs for Email, Calendar, and Contacts, and the Node SDK is the quickest way to build your integration using JavaScript.

Here are some resources to help you get started:

⚙️ Install

Note: The Nylas Node SDK requires Node.js v16 or later.

Set up using npm

To run the Nylas Node SDK, first install Node and npm on your machine.

Then, head to the nearest command line and run the following: npm install nylas

Alternatively, you can use Yarn to install the Nylas Node SDK by running the yarn add nylas command.

Build from source

To install this package from source, clone this repo and run npm install from inside the project directory.

git clone https://github.com/nylas/nylas-nodejs.git
cd nylas-nodejs
npm install

⚡️ Usage

To use this SDK, you must first get a free Nylas account.

Then, follow the Quickstart guide to set up your first app and get your API keys.

For code examples that demonstrate how to use this SDK, take a look at our Node repos in the Nylas Samples collection.

🚀 Making Your First Request

You access Nylas resources (messages, calendars, events, contacts) through an instance of Nylas. The Nylas object must be initialized with your Nylas API key, and you can provide other additional configurations such as the Nylas API url and the timeout.

import Nylas from "nylas";

const nylas = new Nylas({
  apiKey: "NYLAS_API_KEY",
});

Once initialized you can use the object to make requests for a given account's resources, for example to list all the calendars for a given account:

nylas.calendars.list({ identifier: "GRANT_ID" }).then(calendars => {
  console.log(calendars);
});

📚 Documentation

Nylas maintains a reference guide for the Node SDK to help you get familiar with the available methods and classes.

✨ Upgrading from 6.x

See UPGRADE.md for instructions on upgrading from 6.x to 7.x.

Note: The Node SDK v7.x is not compatible with the Nylas API earlier than v3-beta.

💙 Contributing

Please refer to Contributing for information about how to make contributions to this project. We welcome questions, bug reports, and pull requests.

📝 License

This project is licensed under the terms of the MIT license. Please refer to LICENSE for the full terms.

nylas-nodejs's People

Contributors

aaronddm avatar annielcook avatar bengotow avatar brettgerry avatar dependabot[bot] avatar ericyhwang avatar gerdie avatar gm-polyakov avatar gregory avatar jackiehluo avatar jebschiefer avatar jieunsharonkim avatar jstejada avatar jylauril avatar kaleguy avatar kewitz avatar khamidou avatar kraju3 avatar l8on avatar mrashed-dev avatar pfista avatar philiiiiiipp avatar romainsimon avatar sdwvit avatar singingwolfboy avatar slava-tre avatar smrutherford avatar spang avatar tranced avatar trysound avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nylas-nodejs's Issues

Incorrect file size and contents

Hello!
Thanks for the awesome module!
Tho we experience some difficulties and need some help.
When we upload files using the upload method of the object, created by nylas.drafts.build, resulting file have incorrect size and content - when downloaded or attached to messages.

const fs = require('fs');
fs.readFile(filePath, 'utf8', function (err, data) {
  const file = nylas.files.build({
    filename,
    data,
    contentType: 'application/pdf',
  });

  file.upload(function(err, uploadedFile) {
    const fileToDownload = nylas.files.build({
      id: uploadedFile.id,
    });
    fileToDownload.download((err, file) => {
      fs.writeFile(`copy_${filename}`, file.body);
    });
  });
});

When this code is executed, downloaded file has different size (in our case 282 Kb instead of initial 162 Kb) and resulting PDF consist of two pages (same as initial file), but these pages are just empty.
Same happens when we attach files to messages - empty PDFs with incorrect size are attached.
Please help us to find out what we could miss to let files will have correct size and contents.

Bug in 4.2.1

            if (body.server_error) {
              error = error.message + ' (Server Error: ' + body.server_error + ')';
            }

Line 219 in nylas-connection.js

Getting this error (when we receive the error from gmail): uncaughtException: Cannot create property 'statusCode' on string 'Daily sending quota exceeded

Why? Because it assigning a string to error

Get account object no "nylas.account" method

Still can't retrieve a account data by using current Nylas driver with a method:

nylas.account.get().then(function(model) {
    console.log(model);
});

Having a error as:
Cannot read property 'get' of undefined

nylas.account is undefined

BTW: The issue was already created here #29
any updates?

TypeError: Cannot create property 'statusCode' on string 'Daily sending quota exceeded

/home/talha/Desktop/nylas-test/node_modules/nylas/lib/nylas-connection.js:223
              error.statusCode = response.statusCode;
                               ^

TypeError: Cannot create property 'statusCode' on string 'Daily sending quota exceeded (Server Error: 550 : 5.4.5 Daily user sending quota exceeded. h79sm13695820pfj.186 - gsmtp)'
    at Request._callback (/home/talha/Desktop/nylas-test/node_modules/nylas/lib/nylas-connection.js:223:32)
    at Request.self.callback (/home/talha/Desktop/nylas-test/node_modules/request/request.js:185:22)
    at Request.emit (events.js:182:13)
    at Request.<anonymous> (/home/talha/Desktop/nylas-test/node_modules/request/request.js:1157:10)
    at Request.emit (events.js:182:13)
    at IncomingMessage.<anonymous> (/home/talha/Desktop/nylas-test/node_modules/request/request.js:1079:12)
    at Object.onceWrapper (events.js:273:13)
    at IncomingMessage.emit (events.js:187:15)
    at endReadableNT (_stream_readable.js:1094:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

I was testing the library for quota exceeded error. The error does appear, but crashes the server/script because how it's handled in nylas-connection.js:

if (error || response.statusCode > 299) {
  if (!error) {
    error = new Error(body.message);
  }
  if (body.server_error) {
    error = error.message + ' (Server Error: ' + body.server_error + ')';
  }
  if (response.statusCode) {
    error.statusCode = response.statusCode; // here
  }
  return reject(error);
} else {
  if (options.downloadRequest) {
    return resolve(response);
  } else {
    return resolve(body);
  }
}

I can send a PR, if I know the status of the project. It was last published 10 months ago, which shows it's not actively maintained.

Fetch Multiple Records by ID

Hi, I was wondering if it's possible to fetch multiple records by id?

This is in particular helpful for my receiving webhooks, since initial sync, might send deltas with up to 500 messages. Which in order to process I am currently all looking up individually (500 requests to fetch the message by ID). I was wondering, if it is possible to get all those 500 messages by ID with a single call?

unhandled promise rejection - nylas.folders.list() on a gmail account

Hi,

When making a nylas.folders.list() call on a GMail account, there's a rejected promise that can't be caught.

I know this call will always fail on GMail accounts, but I'd like to be able to handle the error within my app. Am I missing something? I've tried both .catch and callback style. My handlers are never reached.

Expose file download() errors

Descriptive errors are not thrown by the file download method.

Example of good error reporting (file.metadata()):

nylasapi.files.build({id: 'bogusid'}).metadata();

Error: Couldn't find file bogusid 
    at NylasConnection.module.exports.NylasConnection.request (.../npm/node_modules/nylas/lib/nylas-connection.js:104:14)
    at NylasConnection.Nylas.NylasConnection.request (meteor://app/server/lib/nylas.js:206:25)
    at File.module.exports.File.metadata (.../npm/node_modules/nylas/lib/models/file.js:131:30)

Poor error reporting (file.download()):

nylasapi.files.build({id: 'bogusid'}).download();

Error
    at NylasConnection.module.exports.NylasConnection.request (.../npm/node_modules/nylas/lib/nylas-connection.js:104:14)
    at NylasConnection.Nylas.NylasConnection.request (meteor://app/server/lib/nylas.js:206:25)
    at File.module.exports.File.download (.../npm/node_modules/nylas/lib/models/file.js:101:30)
    at File.download (.../npm/node_modules/nylas/lib/models/file.js:3:59)

Message.sendRaw exception after sending

The Message.sendRaw method improperly creates a Message instance after a successful send. This always leads to a Connection object not provided error to be thrown as the first parameter provided is the class rather than the connection.

Problem with accounts endpoint

Hello,

I'm using Nylas-nodejs sdk and i've detected a bug.

I'm trying to get the accounts with:

Nylas.with(ApiToken).accounts.list().then(function(accounts) {
}); 

But this functionality have a bunch of bugs. I've patch the NylasSDK but only on Javascript source (not on coffeescript) but i will list the problems that make this not work:

1-

On management-model-collection.js the code was:

ManagementModelCollection.prototype.path = function() {
      return "/a/" + this.api.appId+ "/accounts";
    };

This not work because api isnt a defined attribute.

I've patched this to:

ManagementModelCollection.prototype.path = function() {
      Nylas = require('../nylas');
      return "/a/" + Nylas.appId+ "/accounts";
    };

2-
On nylas-connection.js the code on line 41 was:

if (options.json == null) {
        options.json = true;
      }
 if (this.accessToken) {
        options.auth = {
          'user': this.accessToken,
          'pass': '',
          'sendImmediately': true
        };
}

I've patched this to:

if (options.json == null) {
        options.json = true;
      }
      if (options.path.substr(0,3) === '/a/' ) {
        options.auth = {
          'user': Nylas.appSecret,
          'pass': '',
          'sendImmediately': true
        };
      }
      else if (this.accessToken) {
        options.auth = {
          'user': this.accessToken,
          'pass': '',
          'sendImmediately': true
        };
      }

I can made a patch in coffeescript source and make a pull request, but i think that with all explained its better to nylas team corrected this bug on your way :)

Regards

Don't spam the console with warnings if the api does not return a version

I've seen cases where the api does not return a version.
The SDK will still print warnings in that case

warning += `WARNING: SDK version may not support your Nylas API version.`;

This is something I, as a user of the api, can't fix and is extremely annoying.
If the version mismatches it is totally fine to warn, I even like it that it does that. But in this specific case it is not helpful at all.
Would you take a PR to remove this? Or make it smarter?

Expose sending errors

When an SMTP error occurs when sending a message, the Nylas API exposes it in the server_error field. We should expose it in the exception.

API for Message.sendRaw is weird

Currently, we do not export the Message class, making Message.sendRaw hard to access.

var Nylas = require('nylas');
var accessToken = 'example';
var conn = Nylas.with(accessToken);
var message = 'example';

conn.messages.modelClass.sendRaw(conn, msg);

We should expose a better API for interacting with the raw send endpoint.

Maybe we could export the Message class, or expose sendRaw on conn.messages (the latter would be hackish to implement as far as I can tell, though it's nice that it maintains the invariant that all of the SDK's functionality is exposed on the NylasConnection object).

cannot set offset parameter in messages.list api ...

cannot set offset while fetching the messages.... whteva i set in offset field..it always take it to zero...?? i dont know wht n where m doing it wrng.... thanquu

            var nylas = Nylas.with(token);
            nylas.messages.list({offset:10,limit:50},function(err, messages) {
              console.log(messages)
            })

Tracking is not working

Hello,

im trying to send email and have email opened tracking

My draft code looks a little something like this


const tracking = {
        "links": true,
        "opens": true,
        "thread_replies": true,
        "payload": "12346"
      }
    if(req.body.message_id && req.body.message_id !== "") {
        console.log("Has message id: ", req.body.message_id);
        draft = await req.user.drafts.build({
            to: [{ email: req.body.to }],
            subject: req.body.subject,
            replyMessageId: req.body.message_id,
            replyToMessageId: req.body.message_id,
            body: req.body.emailbody,
            tracking
        });
    }

I also placed it in the send function here:

draft.send(null, tracking).then( message => {
      console.log("Draft sent:", message.id);
      res.json(message);
  }).catch(err => {
      console.log("Draft error:",err);
      res.json(err);
  });

however i am not receiving any of the open data here at my endpoint:

image

so far the only request ive gotten was the GET request for the challenge token:

image

console.log in NPM version #3.1.0

In version posted to NPM as v3.1.0 in nylas-connection.coffee line 72 there is console.log(options), which logs at any consumers log, which is typo I believe and fixed in master, while NPM latest still has this issue :(

Thread object model missing message_ids array

When calling any of the methods in the thread namespace, the returned thread object is missing the message_ids array.

Nylas.with(<access_token>).namespaces.first({}).then(function(namespace){
    namespace.threads.first({from:<email_address>}).then(function(thread){
        console.log(thread.message_ids); // undefined
        console.log(thread.messages); // undefined
    })
})

Status is not included in event model

Hey Nylas team,

Im using this for syncing calendar events, and it seems the restful api returns status but the node library is not including it. I was able to fix by adding the code below to the models/event.js file.

'status': Attributes.String({ modelKey: 'status' }),

Assuming that you'd want to fix this. Thanks in advance!

Docs

Seems like some of the docs might be outdated. I tried filtering with label: 'inbox' and tag: 'inbox' and got an 'Unexpected query parameters...' error.

It worked when I used in: 'inbox'

TypeError: jsonArray.map

The request might not return an array which causes things to break:

https://sentry.io/share/issue/327dc86d02484e10b4c68957dda47f8c/

TypeError: jsonArray.map is not a function
  File "/app/node_modules/nylas/lib/models/restful-model-collection.js", line 266, col 30, in null.<anonymous>
    models = jsonArray.map(function(json) {
  File "/app/node_modules/newrelic/lib/transaction/tracer/index.js", line 183, col 28, in wrapped
    var result = handler.apply(this, arguments)
  File "/app/node_modules/newrelic/lib/instrumentation/promise.js", line 297, col 65, in Promise.linkTransaction
    var result = agent.tracer.bindFunction(fn, segment, true).apply(ctx, args)
  File "/app/node_modules/newrelic/lib/transaction/tracer/index.js", line 183, col 28, in Promise.wrapped
    var result = handler.apply(this, arguments)
  File "/app/node_modules/newrelic/lib/instrumentation/promise.js", line 473, col 26, in __NR_wrappedThenHandler
    return promise.__NR_wrapper(this, fn, name, next, arguments, promise)
  File "domain.js", line 301, col 14, in bound
  File "domain.js", line 314, col 12, in runBound
  File "/app/node_modules/nylas/node_modules/bluebird/js/main/util.js", line 26, col 23, in tryCatcher
    return target.apply(this, arguments);
  File "/app/node_modules/nylas/node_modules/bluebird/js/main/promise.js", line 510, col 31, in Promise._settlePromiseFromHandler
    x = tryCatch(handler).call(receiver, value);
  File "/app/node_modules/nylas/node_modules/bluebird/js/main/promise.js", line 584, col 18, in Promise._settlePromiseAt
    this._settlePromiseFromHandler(handler, receiver, value, promise);
  File "/app/node_modules/nylas/node_modules/bluebird/js/main/promise.js", line 700, col 14, in Promise._settlePromises
    this._settlePromiseAt(i);
  File "/app/node_modules/nylas/node_modules/bluebird/js/main/async.js", line 123, col 16, in Async._drainQueue
    fn._settlePromises();
  File "/app/node_modules/nylas/node_modules/bluebird/js/main/async.js", line 133, col 10, in Async._drainQueues
    this._drainQueue(this._normalQueue);
  File "/app/node_modules/nylas/node_modules/bluebird/js/main/async.js", line 15, col 14, in Immediate.Async.drainQueues
    self._drainQueues();
  File "timers.js", line 785, col 20, in runCallback
  File "timers.js", line 747, col 5, in tryOnImmediate
  File "timers.js", line 718, col 5, in processImmediate [as _immediateCallback]

Is expanded view working for streams?

I am not being able to get it working. I'm using

      stream = nylas.deltas.startStream(cursor, {
        excludeTypes: DELTA_EXCLUDE_TYPES,
        expanded: true,
      })

and the output looks like

{ delta: 
   { cursor: '14f3gq7maaa6gae7jzg1wlatn',
     attributes: 
      { body: '<div dir="ltr">ok</div>',
        files: [],
        headers: [Object],
        labels: [Object],
        from: [Object],
        account_id: '3ejpsidsaaaaa8pndxfcnmvfp',
        thread_id: '13z262huaaaaaw6k0dhkafasy',
        cc: [],
        object: 'message',
        bcc: [],
        snippet: 'ok',
        to: [Object],
        date: 1473384628,
        reply_to: [],
        events: [],
        starred: false,
        unread: true,
        id: '7vzmqbmuxl0gr1pdaaaangfj2',
        subject: 'ok' },
     object: 'message',
     event: 'create',
     id: '7vzmqbmuxl0gr1pdtirwngfj2' } }

which contains no Message-Id.

Am I doing something wrong?

Thank you.

Unable to delete drafts

For a delete request, the API requires that the draft version number be included in the request body. As far as I can tell, there's no way to do this yet.

Ideally, this code would work:
Nylas.with(access_token).drafts.delete(id, {"version": draft.version});

But this adds the version number as a query string rather than putting it in the request body.

Generates broken HTML

Input

  console.log(emailObject)
  const response = await nylas.with(nylasToken).drafts.build(emailObject).send()
  // { to: [ { email: 'REDACTED' } ],
  //   cc: [],
  //   bcc: [],
  //   body: '<div><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAaCAIAAADJ6rCnAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADaUlEQVRIiY2Vy44bVRCG/6pza9ttm4xQIhSBxIKHYAfPgQRvjsIKSCYTuz3uyzl1YeGZiNX01LZb3/n+OlXd9NMPP3bdRmpLIW63m36/y7l8/vwxxFRKIrNSNsMw/PzrL+7ubu747Y/f8b8yMxE5nU5v374FEIlIVR3OMXTbrtbWpA7DJcZYvr1zommciGBucHcAhJcr5hgVfjvM3Wur8zLt+p2qXMexlOIiqRQCnED+9OoLxapqamr2+Hi9v79PKZjZ8XjY9TtpreScu1KX+avamiKimjlxYJ6WCQxiTild51GacAjuLiLn89ltVe6ZGGM0IMVk7n2/g/PhcDidz2Lt2B+aSK015mzuRABo3bE2aVVbrDllAh6+PIRAIsIhTNN03B9yf3j48hevo76mVt312xBiXaZheAwMeOz7npin69UdpWQ4+Ss6+EQ0AAAzdWW7KSmV9OXhYRqn4+GQDvucc0jp7s2du4H4lY4yjZMm6XLJMX/37l1kvgyDuW3KxkSGcQLwakVEMyu7vN/2ZLbM86d/P6YQj8fjPM/j9ZpiNFUzpec+3sb8RUczDqF0HYmqtpyiSM2lc9fzaViYAlFt1c2A23ivEZvU0+nkTfddd+h7Bl0uj3muZZv7/U5aE5VSyjNmVRHMzFBVbamk4903w2UoOYYSzLHdbjabblmWeZ4Af7Jb3WvAHCD2/rA/D+dZ6mZTruPITMNFW6sl52Wa3V+x0jeiq3EM0tqn+0+mVuscclykBg6BXFpzEXvGOdbBMYaYchaxy/nU73bkzoA3XazmEJe5unuI8Qbyr9lf6GMI1NrSlUREwzAQoUptJkutY13ARMyq6u7uDndb+2TE99+/n8fxcjlLlZTTJHMbpUpTVxXZdJtAfB2vcDjB1xXBXZdTTOM0EdG+34vZslSHA8EMIEYI6rAnxxUcgPjhzw91rjmXuzd34zSWWFTV/CZErYkJSt4At/lZHUcwg7rSwR1AV7oUY4oR6taEQNrM3Pb7IxzuboCtbiGZublJ/fjP3zmn7XY3Xa8iFmKEGTHc6Hz6bLe7fkXyeLvApkIOt/j4eBERAFqFiFNKkUndbnFfERpR2N1JQEzQwHWutwdmxuQBobm0Knhu5DpxqdUMBmcOopZKcjUzD4GYGOwqTVTotqzw1T/Nfy+ndSa09wNoAAAAAElFTkSuQmCC"></div>',       
  //   subject: 'test',
  //   files: undefined }

Output

image

The problem

Nylas is adding 3D to my HTML (which is suspicious since unescape('%3D') == '=') which is making images not show up on Gmail (and is costing us business).

Thoughts?

DeltaStream only allows 1 stream to be consumed at a time

When trying to listen for deltas on multiple accounts, it seems like all accounts are bottlenecked through the same connection.

Furthermore, the total throughput when running with multiple accounts is dramatically lower than running with one account. Seems as though there's some non-trivial switching cost.

MAINTENANCE STATUS

Hello guys,

I was just wondering if this was still maintained or if you could use some help to maintain it?
Would be sad to see this forked & maintained by someone else.
Your API is evolving yet no one maintaining the clients...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.