Code Monkey home page Code Monkey logo

fuelsdk-node-rest's Introduction

Fuel REST Client (for Node.js) Build Status Greenkeeper badge

This repo used to be located at https://github.com/exacttarget/Fuel-Node-REST

This library allows users access to the Salesforce Marketing Cloud REST API at a low level.

Support

The Salesforce Marketing Cloud SDKs are community-supported projects. The SDK source code, samples, and documentation are publicly available on Github to use as-is or fork and modify for your needs. We invite everyone in the community to collaborate with us on Github and submit pull requests to help improve the source code and samples.

Installation

npm install fuel-rest --save

yarn add fuel-rest

Initialization

new FuelRest(options) - Initialization

  • options.auth
  • options.origin or options.restEndpoint
  • options.headers
    • Required: no
    • Type: Object
    • set headers that apply to all REST requests (not auth requests)
  • options.globalReqOptions
    • Required: no
    • Type: Object
    • set configuration options that apply to all requests (auth + REST)

API

  • apiRequest(options, callback)
    • options - see request modules options
    • options.auth - will be passed into getAccessToken inside Fuel Auth
    • options.uri - can either be a full url or a path that is appended to options.origin used at initialization (url.resolve)
    • options.retry - boolean value representing whether or not to retry request (and request new token) on 401 invalid token response. default: false
    • callback - executed after task is completed.
      • if no callback is passed, you'll need to use the promise interface
  • get | post | put | patch | delete(options, callback)
    • options - see apiRequest options
    • options.retry - see above for description. default: true
    • callback - see apiRequest options
    • Request method will be overwritten by these methods. It will be set to same value as the name of the method used

Setting up the client

const FuelRest = require('fuel-rest');
const options = {
	auth: {
		// options you want passed when Fuel Auth is initialized
		clientId: 'clientId',
		clientSecret: 'clientSecret'
	},
	origin: 'https://alternate.rest.endpoint.com' // default --> https://www.exacttargetapis.com
};

const RestClient = new FuelRest(options);

Examples

const options = {
	uri: '/platform/v1/endpoints',
	headers: {}
	// other request options
};

// CANNOT USE BOTH CALLBACKS AND PROMISES TOGETHER
RestClient.get(options, (err, response) => {
	if (err) {
		// error here
		console.log(err);
	}

	// will be delivered with 200, 400, 401, 500, etc status codes
	// response.body === payload from response
	// response.res === full response from request client
	console.log(response);
});

// or with promises
RestClient.get(options)
	.then(response => {
		// will be delivered with 200, 400, 401, 500, etc status codes
		// response.body === payload from response
		// response.res === full response from request client
		console.log(response);
	})
	.catch(err => console.log(err));

Contributors

Contributing

We welcome all contributions and issues! There's only one way to make this better, and that's by using it. If you would like to contribute, please checkout our guidelines!

Supported Node Versions

We follow the Node.js Release Schedule. When the current date is past the version's "Maintenance LTS End" it will no longer be supported by this library. A major release on this module will be published when this occurs.

ChangeLog

  • See tags/release page for release notes after 0.7.2
  • 0.7.2 - 2014-10-16 - account for content-type header not being present on API response
  • 0.7.1 - 2014-09-09 - removed unneeded "!!"
  • 0.7.0 - 2014-08-29 (public release, 1st npm version)
    • request retry on 401 invalid token response
    • created helpers file for certain functions
    • updated error delivering/throwing
  • 0.6.0 - 2014-08-26 - added patch method
  • 0.5.0 - 2014-08-26 - API overhaul (apiRequest + all http methods) - breaking
  • 0.4.0 - 2014-08-25 - changed object initialization - breaking
  • 0.3.0 - 2014-08-20
    • added ability to use initialized fuel auth
    • updated travis ci config
    • added license
  • 0.2.0 - 2014-08-09 - removed event emitter - breaking
  • 0.1.0 - 2014-08-07
    • initial module
    • initial unit tests

fuelsdk-node-rest's People

Contributors

dougwilson avatar greenkeeper[bot] avatar kellyjandrews avatar kelseylambert avatar manivinesh avatar sf-csarov avatar sfdrogojan avatar svc-scm avatar vernak2539 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

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

fuelsdk-node-rest's Issues

update API for all functions

all http methods should look like this:

FuelRestClient.get( '/my/url/here/', options, function() {});
// OR
FuelRestClient.get( '/my/url/here/', function() {});

It should be easier to default to Fuel data version 1.1

Right now, in order to ensure all requests just default to the (better) Fuel data version 1.1, the only good way looks stupid:

var FuelRest = require('fuel-rest');
var fuelRestClient = new FuelRest(options);

fuelRestClient.defaultHeaders['x-fueldata-version'] = '1.1';

I'm not sure if we should add an option explicitly for "fuelDataVersion", but at least if there was a constructor option to add to default headers, that would be a good general solution :)

More examples in readme

It would be really helpful to have a more comprehensive set of examples, especially while there are discrepancies between the SOAP and REST APIs. Specifically a post request.

Get client to standalone state

  • refactor constructor for better initialization
  • update API for http methods
  • add required headers (authorization - forgot that one)
  • etc.

Allow for use without Fuel Auth

This will allow us to pass in auth headers to the requests, and remove overhead of extra token requests when they are unneeded

Proxy

Would it be possible to add an option to configure proxy settings?

We're using a modified version of this library like this and would like to switch to a non modified npm version for obvious reasons.

Line 100
options.uri     = helpers.resolveUri(self.origin, options.uri);
                options.headers = _.merge({}, self.defaultHeaders, options.headers);
                options.headers.Authorization = options.headers.Authorization || 'Bearer ' + authResponse.accessToken;
                if(proxy.useProxy()) {
                    options.proxy = proxy.getUri();
                }
                options.rejectUnauthorized = merck.security.rejectUnauthorized;

How to perform API calls on auth endpoint?

Hello,
can you please provide an example how to call APIs accessible from auth server?
E.g.: https://{{MC_ENV}}.auth.marketingcloudapis.com/v2/userinfo?
Regards,
Filip

Should this require FuelAuth?

Since the soap and rest libraries both would utilize fuel with, would it make sense to not set it as a requirement, or am I misunderstanding the implementation?

I would think you would create the Auth object outside of this and the soap lib.

Is this repo deprecated/archived?

Would love some support, care and attention of this repo from Salesforce.

npm WARN deprecated [email protected]: πŸ™Œ  Thanks for using Babel: we recommend using babel-preset-env now: please read https://babeljs.io/env to update!
npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated [email protected]: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
npm WARN deprecated [email protected]: this library is no longer supported
npm WARN deprecated [email protected]: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN deprecated [email protected]: This package has been deprecated in favour of @sinonjs/samsam

Primarily request has been deprecated for over a year now.

I've been reluctant to contribute as issues, pull requests and comments are ignored.

Add type definitions

For those of us using Typescript or similar, it would be nice if there were some type definitions for this library.

I looked for a types package in NPM under the standard @types namespace but it appears none has been created:

$ npm install -D @types/fuel-rest
> npm ERR! code E404
> npm ERR! 404 Not Found: @types/fuel-rest@latest
> ...

Error "object" is impossible to work with.

Got this error when posting a new Campaign:

then [Error: Argument error, options.body.]  (see code below)

typeof(response) returned "object". util.isArray(response) returned false. Really couldn't do anything with the "object". Trying to access response.Error was not possible. I'd like to return the error back to the client but the only thing I could is print it to the console.

this.parent.RestClient
    .post(options)
    .then(function(response) {
        //console.log('then',response); //<---- **** tricky result type when there's an error here.
        cb(response); 
    }.bind(this))
    .catch(function(err) {
        cb(err);  
    }.bind(this));

An in-range update of fuel-auth is breaking the build 🚨

The dependency fuel-auth was updated from 3.2.1 to 3.3.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fuel-auth is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for Public/Web App Oauth2 Auth Support and Refresh Token
  • Added support for Public App OAuth2 Authentication
  • Added support for Web App OAuth2 Authentication
  • Added Refresh Token Support for OAuth2 Authentication
Commits

The new version differs by 1 commits.

  • 9dc8c4f Refresh token & public web app auth support (#82)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Retry doesn't help

Version: 2.0.5

On get | post | put | patch | delete requests, the retry options is true by default.
Ideally this will re-fetch the access token and make the request again after receiving a 401 error.

However, by the following logic in _processRequest function, the Authorization header will only be updated when it doesn't exist, which means the second request will still take the old token and then always get a 401 error again.

if (!options.headers.Authorization) {
	options.headers.Authorization = 'Bearer ' + authResponse.accessToken;
	retry = options.retry || false;
}

Authentication error while making request

I'm trying to make a simple GET request using OAuth 2.0 and grant_type: 'client_credentials' but i keep getting an error. I followed the readme doc to initialize and make a request like below.

const FuelRest = require("fuel-rest");

const options = {
  auth: {
    clientId: "CLIENT_ID_HERE",
    clientSecret: "CLIENT_SECRET_HERE",
    authUrl:
      "https://MY_AUTH_URL.auth.marketingcloudapis.com/v2/token/", //Tried without '/v2/token/' also
  },
  origin: "https://MY_ORIGIN.rest.marketingcloudapis.com/",
};

const RestClient = new FuelRest(options);

const getOpts = {
  uri: "/platform/v1/endpoints",
  headers: {},
  // other request options
};

RestClient.get(getOpts)
  .then(function (response) {
    var result = response && response.body ? response.body : response;
    console.log(result);
  })
  .catch(function (err) {
    console.log(err);
  });

Error i am getting is

{ Error: No access token
    at AuthClient.getAccessToken.then.tokenInfo (E:\Development\node-scripts\node_modules\fuel-rest\lib\fuel-rest.js:88:18)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)
  res:
   { error: 'unsupported_grant_type',
     error_description: 'Use "authorization_code" or "refresh_token" or "client_credentials" or "urn:ietf:params:oauth:grant-type:jwt-bearer" as the grant_type.',
     error_uri: 'https://developer.salesforce.com/docs' } }

Please let me know if i did something wrong with the initialization or misunderstood the docs.

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.