kevinohara80 / nforce

nforce is a node.js salesforce REST API wrapper for force.com, database.com, and salesforce.com
MIT License
474 stars 167 forks source link

Upsert error #153

Closed Gurenax closed 6 years ago

Gurenax commented 6 years ago

After executing upsert, I receive the error:

Error: { Error: HTTP Method 'PATCH' not allowed. Allowed are GET,HEAD,POST

const sobj = nforce.createSObject(sobjectName)
sobj.setExternalId('Id', recordId)
Object.entries(recordDataWithID).map(([key, value]) => {
  sobj.set(key, value)
})

org.upsert(
  {
    sobject: sobj,
    oauth: oauth
  },
  (error, response) => {
    if (!error) {
      console.log(response)
    } else {
      console.error('Error: ', error)
    }
  }
)

The Connection.prototype.upsert function does specify PATCH in opts.method:

Connection.prototype.upsert = function(data, callback) {
  var opts = this._getOpts(data, callback);
  var type = opts.sobject.getType();
  var extIdField = opts.sobject.getExternalIdField();
  var extId = opts.sobject.getExternalId();
  opts.resource = '/sobjects/' + type + '/' + extIdField + '/' + extId;
  opts.method = 'PATCH';
  opts.body = JSON.stringify(opts.sobject._getPayload(false));
  return this._apiRequest(opts, opts.callback);
};

My suggestion is to change opts.method to POST. Not unless there's a workaround?

Gurenax commented 6 years ago

Figured out that there's a requestOpts option.

After executing the following, I was able to insert:

const sobj = nforce.createSObject(sobjectName)
sobj.setExternalId('Id', recordId)
Object.entries(recordDataWithID).map(([key, value]) => {
  sobj.set(key, value)
})

org.upsert(
  {
    sobject: sobj,
    oauth: oauth,
    requestOpts: {
       method: 'POST'
    }
  },
  (error, response) => {
    if (!error) {
      console.log(response)
    } else {
      console.error('Error: ', error)
    }
  }
)

But after executing it the second time in which I wanted to Upsert for an update, I am now getting the error:

Error: { Error: HTTP Method 'POST' not allowed. Allowed are GET,HEAD,PATCH,DELETE

Gurenax commented 6 years ago

Figured out a solution! I can just set a condition using my recordId parameter:

const sobj = nforce.createSObject(sobjectName)
sobj.setExternalId('Id', recordId)
Object.entries(recordDataWithID).map(([key, value]) => {
  sobj.set(key, value)
})

org.upsert(
  {
    sobject: sobj,
    oauth: oauth,
    requestOpts: {
       method: !recordId ? 'POST' : 'PATCH'
    }
  },
  (error, response) => {
    if (!error) {
      console.log(response)
    } else {
      console.error('Error: ', error)
    }
  }
)

I hope this information can help someone else. Cheers!