Search code examples
restsalesforcenetsuitesuitescriptsuitescript2.0

How to call https.patch in Netsuite to update Salesforce record?


I am trying to update custom 'city' field in salesforce customer record using user event script. Patch is supported in salesforce to update records but does not support in Netsuite.

I have created user event script. But its not updating the record by trying many ways. please help!

define(['N/record', 'N/https', 'N/log'], function(record, https, log) {

function afterSubmit(context) {
    if (context.type === context.UserEventType.EDIT) {
        var city = 'Mumbai';
        var accessToken = '73475874586867u589487';

        try {
            // Update customer in Salesforce
            var salesforceResponse = updateSalesforceCustomer(accessToken, {
                City__c: city
            });
            log.debug("salesforceResponse", salesforceResponse);

            if (salesforceResponse.success) {
                log.debug("Customer Created in Salesforce", "Customer ID: " + salesforceResponse.id);
            } else {
                throw new Error('Failed to create customer in Salesforce: ' + JSON.stringify(salesforceResponse.error));
            }
        } catch (e) {
            log.error('Error creating customer in Salesforce', e.message);
        }
    }
}

function updateSalesforceCustomer(accessToken, updateData) {
    var response = https.post({
        url: 'https://dshcbshfvb-dev-ed.develop.my.salesforce.com/services/data/v61.0/sobjects/Customer/0o6dM00000008dVQAQ',
        headers: {
            'Authorization': 'Bearer ' + accessToken,
            'Content-Type': 'application/json',
            'X-HTTP-Method-Override': 'PATCH'
        },
        body: JSON.stringify(updateData)
    });

    var responseBody = JSON.parse(response.body);
    if (response.code === 201) {
        return {
            success: true,
            id: responseBody.id
        };
    } else {
        log.error('Error creating customer in Salesforce', responseBody);
        return {
            success: false,
            error: responseBody
        };
    }
}

Solution

  • You can work around this limitation by sending a POST request and including a query string parameter _HttpMethod to override the HTTP method.

    For example, if you need to perform a PATCH requestyou can modify your request as follows by adding ?_HttpMethod=PATCH to the end of your url

    POST /your/endpoint?_HttpMethod=PATCH
    

    I found this solution in the Salesforce Developers Guide. Here's a relevant excerpt:

    If you use an HTTP library that doesn't allow overriding or setting an arbitrary HTTP method name, you can send a POST request and provide an override to the HTTP method via the query string parameter _HttpMethod. In the PATCH example, you can replace the PostMethod line with one that doesn't use override.

    This approach allows you to use the PATCH HTTP method with N/https module in NetSuite.