diff --git a/.eslintrc.js b/.eslintrc.js index 007d54e8..01633734 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -15,7 +15,7 @@ module.exports = { 'curly': 2, 'eqeqeq': 2, 'max-depth': 2, - 'max-statements': [2, 20], + 'max-statements': [2, 22], 'new-cap': 2, 'no-caller': 2, 'no-cond-assign': 2, diff --git a/README.md b/README.md index 30b354a9..2f47bc50 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,16 @@ client.post(path, params, callback); client.stream(path, params, callback); ``` +When the `post` convenience method is used to submit a JSON body, the `params` object must be structured as follows: + +```javascript +{ + json_body: { + // JavaSctript object to be submitted as JSON body + } +} +``` + ## REST API You simply need to pass the endpoint and parameters to one of convenience methods. Take a look at the [documentation site](https://dev.twitter.com/rest/public) to reference available endpoints. @@ -113,6 +123,28 @@ client.post('statuses/update', {status: 'I Love Twitter'}, function(error, twee console.log(response); // Raw response object. }); ``` +Example of POST with JSON body (new [direct_messages/events/new](https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event) API): + +```javascript +let params = { + json_body: { + event: { + type: 'message_create', + message_create: { + target: { recipient_id: '1234567890' }, + message_data: { text: 'Hi there!' } + } + } + } +}; + +client.post('direct_messages/events/new', params, (error, result, response) => { + if (error) throw error; + console.log(result); // Newly created event object. + console.log(response); // Raw response object. +}); +``` + ### Promises diff --git a/lib/twitter.js b/lib/twitter.js index 1dbf3e27..674c105f 100644 --- a/lib/twitter.js +++ b/lib/twitter.js @@ -132,14 +132,18 @@ Twitter.prototype.__request = function(method, path, params, callback) { options.qs = params; } - // Pass form data if post + // Pass form data (or JSON boy if specified) if post if (method === 'post') { - var formKey = 'form'; - - if (typeof params.media !== 'undefined') { - formKey = 'formData'; + if(params.json_body){ + options.json = params.json_body; + } + else{ + var formKey = 'form'; + if (typeof params.media !== 'undefined') { + formKey = 'formData'; + } + options[formKey] = params; } - options[formKey] = params; } // Promisified version @@ -158,7 +162,7 @@ Twitter.prototype.__request = function(method, path, params, callback) { if (data === '') { data = {}; } - else { + else if (typeof data === 'string') { data = JSON.parse(data); } } @@ -196,7 +200,7 @@ Twitter.prototype.__request = function(method, path, params, callback) { if (data === '') { data = {}; } - else { + else if(typeof data === 'string'){ data = JSON.parse(data); } }