diff options
author | scottmotte <scott@scottmotte.com> | 2013-07-23 16:17:17 -0700 |
---|---|---|
committer | scottmotte <scott@scottmotte.com> | 2013-07-23 16:17:17 -0700 |
commit | 392b40836065918c74237775dc59bfe76ef265fc (patch) | |
tree | 9396faf7431a1374f74054811512539a89bb05d5 | |
parent | dd8a35098e4edf5fd60f3410c2e476ff5e0c799d (diff) | |
download | sendgrid-nodejs-392b40836065918c74237775dc59bfe76ef265fc.zip sendgrid-nodejs-392b40836065918c74237775dc59bfe76ef265fc.tar.gz sendgrid-nodejs-392b40836065918c74237775dc59bfe76ef265fc.tar.bz2 |
Refactors sendgrid.js to be a bit more standard node module like and updates README
-rw-r--r-- | .env.example | 4 | ||||
-rw-r--r-- | .gitignore | 6 | ||||
-rw-r--r-- | README.md | 176 | ||||
-rw-r--r-- | index.js | 6 | ||||
-rw-r--r-- | lib/email.js | 10 | ||||
-rw-r--r-- | lib/file_handler.js | 1 | ||||
-rw-r--r-- | lib/sendgrid.js | 167 | ||||
-rw-r--r-- | lib/validation.js | 26 | ||||
-rw-r--r-- | package.json | 2 | ||||
-rw-r--r-- | test/config.sample.js | 9 | ||||
-rw-r--r-- | test/index.test.js | 9 | ||||
-rw-r--r-- | test/integration/sendgrid.test.js | 4 | ||||
-rw-r--r-- | test/lib/sendgrid.test.js | 22 | ||||
-rw-r--r-- | test/test_helper.js | 13 |
14 files changed, 241 insertions, 214 deletions
diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..87089bc --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +API_USER=yourusername +API_KEY=yourpassword +TO=your@email.com +FROM=your@email.com @@ -2,4 +2,8 @@ node_modules/ npm-debug.log .DS_Store test/config.js -.env* +.env.test +.env.development +.env.production +.env.staging +.env @@ -1,84 +1,126 @@ -# sendgrid # -This nodejs module allows you to quickly and easily send emails through -SendGrid using nodejs. +# Sendgrid-nodejs -[](https://travis-ci.org/sendgrid/sendgrid-nodejs) +This nodejs module allows you to quickly and easily send emails through SendGrid using [nodejs](http://nodejs.org/). -## License ## -Licensed under the MIT License. +[](https://travis-ci.org/sendgrid/sendgrid-nodejs) + +```javascript +var SendGrid = require('sendgrid').SendGrid; +var sendgrid = new SendGrid(user, key); +sendgrid.send({ + to: 'example@example.com', + from: 'other@example.com', + subject: 'Hello World', + text: 'My first email through SendGrid.' +}, function(err, json) { + if (err) { return console.error(err); } + console.log(json); +}); +``` + +## Installation + +The following recommended installation required [npm](https://npmjs.org/). If you are unfamiliar with npm, see [npm docs](https://npmjs.org/doc/). Npm comes installed with Node.js since node version 0.8.x so likely you already have it. -## Install ## +Add the following to your `package.json` file: +```json +{ + ... + "dependencies": { + ... + "sendgrid": "0.3.0" + } +} + +Install sendgrid-nodejs and its dependencies: + +```bash +npm install ``` + +### Alternative Installation + +You can also install sendgrid locally with the following command: + +```bash npm install sendgrid ``` -## Testing ## +## Usage ## -In order to run the integration tests, you'll need to update the config file with your valid SendGrid credentials. Start by making a live copy of the sample: +To begin using this library, initialize the SendGrid object with your SendGrid credentials. -``` -cp test/config.sample.js test/config.js +```javascript +var sendgrid = require('sendgrid')(api_user, api_key); ``` -Next, open up `test/config.js` and fill it in. After you have updated the configuration file with your credentials, you can run the suite using the following command: +Create a new JavaScript object with your message details. -``` -npm test +```javascript +var payload = { + to : 'to@example.com', + from : 'from@other.com', + subject : 'Saying Hi', + text : 'This is my first email through SendGrid' +} ``` -You can run individual tests with the following command: +Send it. +```javascript +sendgrid.send(payload, function(err, json) { + if (err) { console.error(err); } + console.log(json); +}); ``` -./node_modules/.bin/mocha [path to test].js + +**Alternatively you can send it explicitly via Web or SMTP.** + +```javascript +sendgrid.web(payload, function(err, json) { + if (err) { console.error(err); } + console.log(json); +}); ``` -## Usage ## -### It can be this easy ### +Or ```javascript -var SendGrid = require('sendgrid').SendGrid; -var sendgrid = new SendGrid(user, key); -sendgrid.send({ - to: 'example@example.com', - from: 'other@example.com', - subject: 'Hello World', - text: 'My first email through SendGrid' -}, function(err, messages) { - if (err) { - return console.error(err); - } +sendgrid.smtp(payload, function(err, json) { + if (err) { console.error(err); } + console.log(json); }); ``` -And you're done! +### Power Usage + +There are two additioanl objects built into this library that will help you use this library as a power user. + ++ Email ++ SmtpapiHeaders -### Digging in ### -There are two objects that you really need to know to get started: -+ SendGrid -+ Email +#### Email -#### Email #### -Email is the object that will help you easily perpare your message to be sent. +Email helps you more powerfully prepare your message to be sent. -NOTE: anything that is available in the Email constructor is available -for use in both the `sendgrid.send` and `sendgrid.smtp` functions. +NOTE: anything that is available in the Email constructor is available for use in the `sendgrid.send`, `sendgrid.web`, and `sendgrid.smtp` functions. To get started create an Email object: ```javascript -var Email = require('sendgrid').Email; -var email = new Email(optionalParams); +var sendgrid = require('sendgrid')(api_user, api_key); +var Email = sendgrid.Email; +var email = new Email(params); ``` -You can pass in as much or as little to optionalParams as you want, as +You can pass in as much or as little to `params` as you want, as the email object has methods for manipulating all of the data. **params structure** ```javascript -var optionalParams = { +var params = { to: [], toname: [], from: '', @@ -105,7 +147,7 @@ var optionalParams = { }; ``` -Sample for using it: +Here is a sample for using it: ```javascript var email = new Email({ @@ -116,8 +158,9 @@ var email = new Email({ }); ``` -##### Setting data ##### -Here is an example of all of the functions available on the email object. The comments to the right show the current state of the variables as the functions are called. If you have specific question, see the [SendGrid API Docs](http://docs.sendgrid.com/documentation/api/). Feel free to open an issue if you find bugs or missing features. +##### Setting data + +Here is an example of all of the functions available on the email object. The comments to the right show the current state of the variables as the functions are called. If you have a specific question, see the [SendGrid API Docs](http://docs.sendgrid.com/documentation/api/). Please open a [GitHub issue](https://github.com/sendgrid/sendgrid-nodejs/issues) if you find bugs or missing features. ```javascript var email = new Email({ @@ -216,3 +259,44 @@ email.addFile({ }); email.addHtml('<div>Our logo:<img src="cid:the_logo"></div>'); ``` + +## Contributing + +1. Fork it +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Commit your changes (`git commit -am 'Added some feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create new Pull Request + +## Running Tests + +The existing tests can be run using [Mocha](http://visionmedia.github.io/mocha/) with the following command: + +```bash +npm test +``` + +You can run individual tests with the following command: + +```bash +./node_modules/.bin/mocha [path to test].js +``` + +### Integration Tests + +In order to run the integration tests, you'll need to update the environment file with your valid SendGrid credentials. Start by making a live copy of the example: + +```bash +cp .env.example .env.test +``` + +Next, open up `.env.test` and fill it in. After you have updated the environment file with your credentials, you can run the suite using the following command: + +```bash +npm test +``` + +## License + +Licensed under the MIT License. + @@ -1,5 +1 @@ -module.exports = { - SendGrid: require('./lib/sendgrid'), - Email: require('./lib/email'), - SmtpapiHeaders: require('./lib/smtpapi_headers') -}; +module.exports = require("./lib/sendgrid"); diff --git a/lib/email.js b/lib/email.js index a014717..d971566 100644 --- a/lib/email.js +++ b/lib/email.js @@ -53,16 +53,6 @@ function Email(params) { } /** - * Validates an email. This is used before sending, but - * can still be invoked programatically - * - * @return {Boolean} The result of the validation - */ -Email.prototype.validate = function() { - //TODO: add validation -}; - -/** * This method sets the headers on an email, if the value passed in is an object. * * @param {object} val An object of custom headers diff --git a/lib/file_handler.js b/lib/file_handler.js index 23e2500..56e41a6 100644 --- a/lib/file_handler.js +++ b/lib/file_handler.js @@ -1,4 +1,3 @@ -var https = require('https'); var http = require('http'); var mime = require('mime'); var _ = require('underscore'); diff --git a/lib/sendgrid.js b/lib/sendgrid.js index 15fee86..be04e96 100644 --- a/lib/sendgrid.js +++ b/lib/sendgrid.js @@ -1,70 +1,76 @@ "use strict"; -var package_json = require('./../package.json'); -var nodemailer = require('nodemailer'); -var request = require('request'); -var Email = require('./email'); - - -/* - * Class for handling communications with SendGrid. - * - * @param {String} api_user The SendGrid username. - * @param {String} api_key The key credentials for SendGrid. - */ -function SendGrid(api_user, api_key) { - this.api_user = api_user; - this.api_key = api_key; - this.version = package_json.version; - this.SMTP = "SMTP"; - if (process.env.NODE_ENV == "test") { - this.SMTP = "STUB"; - } -} +var package_json = require('./../package.json'); +var nodemailer = require('nodemailer'); +var request = require('request'); +var Email = require('./email'); +var SmtpapiHeaders = require('./smtpapi_headers'); -/* - * Sends an email via web. See .web method for more details. - * - */ -SendGrid.prototype.send = function(email, callback) { - this.web(email, callback); -} +module.exports = function(api_user, api_key) { + var self; -/* - * Sends an email via web and returns true if the - * message was sent successfully. - * - * @param {Email|Object} email An email object or a hash that has - * the values for the email to be sent. - * @param {Function} callback A function to call when the processing is done. - * This parameter is optional. - */ -SendGrid.prototype.web = function(email, callback) { - var api_user = this.api_user; - var api_key = this.api_key; - - var self = this - , cb = callback || function() { }; - - if (email.constructor !== Email) { - email = new Email(email); + var send = function(email, callback) { + web(email, callback); } - function send_web() { + /* + * Sends an email via web and returns true if the + * message was sent successfully. + * + * @param {Email|Object} email An email object or a hash that has + * the values for the email to be sent. + * @param {Function} callback A function to call when the processing is done. + * This parameter is optional. + */ + var web = function(email, callback) { + self = this; + var callback = callback || function() { }; + + if (email.constructor !== Email) { + email = new Email(email); + } + + _sendWeb(email, callback); + }; + + /* + * Sends an email via SMTP and returns true if the + * message was sent successfully. + * + * @param {Email|Object} email An email object or a hash that has + * the values for the email to be sent. + * @param {Function} callback A function to call when the processing is done. + * This parameter is optional. + */ + var smtp = function(email, callback) { + self = this; + var callback = callback || function() { }; + + if (email.constructor !== Email) { + email = new Email(email); + } + + _sendSmtp(email, callback); + }; + + /* + * Psuedo-private methods + */ + var _sendWeb = function(email, callback) { var req = request({ method : 'POST', uri : "https://sendgrid.com/api/mail.send.json" }, function(err, resp, body) { - if(err) return cb(err, null); + if(err) return callback(err, null); var json = JSON.parse(body); if (json.message !== 'success') { var error = 'sendgrid error'; if (json.errors) { error = json.errors.shift(); } - return cb(error, null); + return callback(error, null); } - return cb(null, json); + return callback(null, json); }); var form = email.toWebFormat(); @@ -87,46 +93,37 @@ SendGrid.prototype.web = function(email, callback) { } } - send_web(); -}; - -/* - * Sends an email via SMTP and returns true if the - * message was sent successfully. - * - * @param {Email|Object} email An email object or a hash that has - * the values for the email to be sent. - * @param {Function} callback A function to call when the processing is done. - * This parameter is optional. - */ -SendGrid.prototype.smtp = function(email, callback) { - var self = this - , smtpTransport - , cb = callback || function() { }; - - // SMTP settings - smtpTransport = nodemailer.createTransport(this.SMTP, { - service: 'SendGrid', - auth: { - user: this.api_user, - pass: this.api_key - } - }); + var _sendSmtp = function(email, callback) { + // SMTP settings + var smtpTransport = nodemailer.createTransport(self.SMTP, { + service: 'SendGrid', + auth: { + user: api_user, + pass: api_key + } + }); - function send_smtp() { smtpTransport.sendMail(email.toSmtpFormat(), function(err, response) { smtpTransport.close(); - if(err) { return cb(err.data, null);} + if(err) { return callback(err.data, null);} - return cb(null, {'message': 'success'}); + return callback(null, {'message': 'success'}); }); } - if (email.constructor !== Email) { - email = new Email(email); - } - - send_smtp(); -}; -module.exports = SendGrid; + /* + * Expose public API calls + */ + return { + version : package_json.version, + SMTP : "SMTP", + Email : Email, + SmtpapiHeaders : SmtpapiHeaders, + api_user : api_user, + api_key : api_key, + web : web, + smtp : smtp, + send : send + }; +} diff --git a/lib/validation.js b/lib/validation.js deleted file mode 100644 index e7c8b5c..0000000 --- a/lib/validation.js +++ /dev/null @@ -1,26 +0,0 @@ -var _ = require('underscore'); - -var VALID_TYPE = { - EMAIL : {name: "Email", error: "is not a valid email"}, - STRING : {name: "String", error: "is not a string"}, - DEPENDENT : {name: "Dependent", error: "depencency is also not valid"}, - DATE : {name: "Date", error: "is not a valid RFC 2822 formatted date"} -}; - -function Validation(validType, required, optionalDependent) { - this.validType = validType; - this.required = required; - if (validType === VALID_TYPE.DEPENDENT) { - if (_.isUndefined(optionalDependent) { - throw new Error("Missing dependent field"); - } else { - this.dependent = optionalDependent; - } - } -} - -Validation.prototype.isValid = function(first_argument) { - // body... -}; - -module.exports.Validate = Validate; diff --git a/package.json b/package.json index 0b1ec3c..aaed406 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ ], "name": "sendgrid", "description": "A NodeJS implementation of the SendGrid Api.", - "version": "0.3.0", + "version": "0.3.0-rc.1.0", "homepage": "http://sendgrid.com", "repository": { "type": "git", diff --git a/test/config.sample.js b/test/config.sample.js deleted file mode 100644 index d20b5c2..0000000 --- a/test/config.sample.js +++ /dev/null @@ -1,9 +0,0 @@ -var test_setup = { - api_user: '<username>', - api_key: '<password/api_key>', - single_to: '<your_email>', - multi_to: ['<your_email>', '<another_email>'], - from: '<your_email>' -} -module.exports = test_setup; - diff --git a/test/index.test.js b/test/index.test.js index dc5e6fd..523fb54 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -4,13 +4,4 @@ describe("index.js", function () { it("should exist", function () { expect(index).to.not.be.undefined; }); - it('should export the SendGrid object', function() { - expect(index.SendGrid).to.not.be.undefined; - }); - it('should export the Email object', function() { - expect(index.Email).to.not.be.undefined; - }); - it('should export the SmtpapiHeaders object', function() { - expect(index.SmtpapiHeaders).to.not.be.undefined; - }); }); diff --git a/test/integration/sendgrid.test.js b/test/integration/sendgrid.test.js index c753798..b9fcb9a 100644 --- a/test/integration/sendgrid.test.js +++ b/test/integration/sendgrid.test.js @@ -1,4 +1,6 @@ -process.env.NODE_ENV = 'test'; var dotenv = require('dotenv')(); dotenv.load(); +process.env.NODE_ENV = 'test'; +var dotenv = require('dotenv')(); +dotenv.load(); var API_USER = process.env.API_USER || 'some_sendgrid_username'; var API_KEY = process.env.API_KEY || 'some_sendgrid_password'; diff --git a/test/lib/sendgrid.test.js b/test/lib/sendgrid.test.js index 81b9849..414d790 100644 --- a/test/lib/sendgrid.test.js +++ b/test/lib/sendgrid.test.js @@ -1,9 +1,3 @@ -process.env.NODE_ENV = 'test'; -var dotenv = require('dotenv')(); -dotenv.load(); - -var API_USER = process.env.API_USER || 'some_sendgrid_username'; -var API_KEY = process.env.API_KEY || 'some_sendgrid_password'; var default_payload = { to : process.env.TO || "hello@example.com", from : process.env.FROM || "swift@sendgrid.com", @@ -12,20 +6,20 @@ var default_payload = { html : "<h2>This is an html body</h2>" } -var SendGrid = require('../../lib/sendgrid') - , Email = require('../../lib/email') - , sinon = require('sinon') - , nock = require('nock'); +var sinon = require('sinon') + , nock = require('nock'); describe('SendGrid', function () { - var sendgrid; + it('should export the Email object', function() { + expect(sendgrid.Email).to.not.be.undefined; + }); - beforeEach(function() { - sendgrid = new SendGrid(API_USER, API_KEY); + it('should export the SmtpapiHeaders object', function() { + expect(sendgrid.SmtpapiHeaders).to.not.be.undefined; }); it('version should be set', function() { - expect(sendgrid.version).to.equal("0.3.0"); + expect(sendgrid.version).to.equal("0.3.0-rc.1.0"); }); describe('#send', function() { diff --git a/test/test_helper.js b/test/test_helper.js index 0ba1d3b..e39b2fb 100644 --- a/test/test_helper.js +++ b/test/test_helper.js @@ -1,7 +1,8 @@ -global.expect = require('chai').expect; +process.env.NODE_ENV = 'test'; +var dotenv = require('dotenv')(); +dotenv.load(); -try { - global.setup = require('./config'); -} catch(e) { - global.setup = {}; -} +global.API_USER = process.env.API_USER || 'some_sendgrid_username'; +global.API_KEY = process.env.API_KEY || 'some_sendgrid_password'; +global.sendgrid = require('../lib/sendgrid')(API_USER, API_KEY) +global.expect = require('chai').expect; |