How to use function to call API and integerate project record from netsuite.

Call the function in the after submit context of user event script:

const afterSubmit = (scriptContext) => {

            if (scriptContext.type === scriptContext.UserEventType.CREATE || scriptContext.type === scriptContext.UserEventType.EDIT) {

                let newRecord = scriptContext.newRecord;

                let projectId = newRecord.id;

                log.debug(“Record Id:”, projectId)

                let projectDetails = getProjectDetails(projectId);

                log.debug(“Project details:”, projectDetails)

                let endpoint;

                let method;

                if (scriptContext.type === scriptContext.UserEventType.CREATE) {

                    endpoint = ‘/api/jobs’;

                    method = https.Method.POST;

                } else {

                    if (!projectDetails.id) {

                        log.error(‘Missing Id:’, ‘Cannot update project without id’);

                        return;

                    }

                    endpoint = `/api/jobs/${projectDetails.id}`;

                    method = https.Method.PUT;

                }

                let response = callApi(method, endpoint, projectDetails);

                let responseBody;

                try {

                    responseBody = JSON.parse(response.body);

                } catch (e) {

                    log.error(‘Failed to parse API response’, e);

                    return;

                }

                if (scriptContext.type === scriptContext.UserEventType.CREATE && response.code === 201 && responseBody.doc && responseBody.doc.id) {

                    const externalId = responseBody.doc.id;

                    if (externalId) {

                        record.submitFields({

                            type: ‘job’,

                            id: projectId,

                            values: {

                                custentity_jj_project_task_id: externalId

                            }

                        });

                    }

                }

            }

        }

Function to call the API:

function callApi(method, endpoint, body) {

            let response;

            try {

                let headers = {

                    ‘Content-Type’: ‘application/json’

                };

                response = https.request({

                    method: method,

                    url: ‘https://rspportal.net/’ + endpoint,

                    headers: headers,

                    body: JSON.stringify(body)

                });

                log.debug(“RESPONSE:”, response)

            } catch (error) {

                log.error(‘Error in API call’, error);

                response = null;

            }

            return response;

        }

Leave a comment

Your email address will not be published. Required fields are marked *