From 68793869f0f6b8ec8b7d2a116131c5c009395dca Mon Sep 17 00:00:00 2001 From: teifip Date: Mon, 8 Jan 2018 15:03:37 -0800 Subject: [PATCH] Support for POST with JSON body Added support for POST requests with JSON body. See updated README.md for usage information. --- README.md | 32 ++++++++++++++++++++++++++++++++ lib/twitter.js | 19 ++++++++++++------- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 30b354a9..a189cf3c 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. @@ -114,6 +124,28 @@ client.post('statuses/update', {status: 'I Love Twitter'}, function(error, twee }); ``` +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 The REST API convenience methods will also return Promises if: diff --git a/lib/twitter.js b/lib/twitter.js index 1dbf3e27..6bbae069 100644 --- a/lib/twitter.js +++ b/lib/twitter.js @@ -132,14 +132,19 @@ Twitter.prototype.__request = function(method, path, params, callback) { options.qs = params; } - // Pass form data if post + // Pass either form data or JSON body if post if (method === 'post') { - var formKey = 'form'; + if (params.json_body) { + options.json = params.json_body; - if (typeof params.media !== 'undefined') { - formKey = 'formData'; + } else { + var formKey = 'form'; + + if (typeof params.media !== 'undefined') { + formKey = 'formData'; + } + options[formKey] = params; } - options[formKey] = params; } // Promisified version @@ -158,7 +163,7 @@ Twitter.prototype.__request = function(method, path, params, callback) { if (data === '') { data = {}; } - else { + else if (typeof data === 'string') { data = JSON.parse(data); } } @@ -196,7 +201,7 @@ Twitter.prototype.__request = function(method, path, params, callback) { if (data === '') { data = {}; } - else { + else if (typeof data === 'string') { data = JSON.parse(data); } }