21
Lab 2 Implement the customer creation logic

Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

Lab 2Implement the customer creation logic

Page 2: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

OverviewIn the previous lab, we created the project skeleton from the Customer API. Now it’s time toimplement it. The Customer API contains all the operations for managing customer data - create(POST), read (GET) , update (PUT) and delete (DELETE). For the purposes of this lab, we will onlyimplement the customer creation represented by the POST method.

Step 1: Customer ImplementationThe customer creation logic is as follows:

1. Create the Account in SDFC to represent the customer

2. Validate the successful creation of the account

3. If validation fails,

a. Raise an error mapped to Bad Request (400 is the status code for Bad Requests)

4. If successful,

a. Get Account Details

b. Convert Response to JSON

The steps that need to be executed are:

1. With the api view selected, click the Add Module sign in the Mule Palette view in order toadd the Salesforce Connector and Validation module required for our implementation in thenext step.

2. Drag and Drop Salesforce Connector and Validation Module and click Finish

1

Page 3: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

NOTE

Notice that we’re leveraging the mule lightweight module-based framework tosupport our use case. The Salesforce Connector provides connectivity toSalesforce and the Validation Module is a component to implement validations,similar to the concept of an assertion, for validation checks like booleanexpressions, null values, specific values, and other conditions. Subsequently, theflow execution can generate out of the box and custom Error Types to theError handling scopes within your flow.

At the end the palette should look similar to the following image.

3. Now, you are ready to implement the POST resource operation. Find thepost:\customer:application\json:api-config resource flow (at the bottom of the api view)

4. Delete the generated Transform Message step that returned the sample response from the APIspecification

2

Page 4: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

5. From the Mule Palette, select Salesforce, scroll to Create Single and drag and drop thecomponent to the flow.

WARNING You might be asked to select the version. Always choose the latest one.

6. Click on Salesforce icon and the configuration will be shown below.

7. Change its name to Create Account

In order to implement best practices, create a properties file to hold connection credentials forour API implementation. To be ordered, we are going to first create a folder and then create theconfig file.

8. Click on src/main/resources in the Package Explorer view, right click and create a New →Folder, name it configuration and click Finish

9. Click on src/main/resources/configuration in the Package Explorer view, right click andcreate a New → File, name it config.yaml and click Finish

3

Page 5: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

4

Page 6: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

10. Copy the following contents into config.yaml. These are the connection credentials your APIwill use for the Salesforce connector.

sfdc:  username: "[email protected]"  password: "Elum1379"  securityToken: "7ZDtkYMazEtbvgdaaPrtMGit"

11. To finish the configuration of the properties file for your API, click on the api view and click onthe Global Elements tab.

5

Page 7: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

12. Click Create, search for properties, select Configuration Properties, click OK, enterconfig.yaml in the File: attribute and click OK.

6

Page 8: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

13. Click the Save All button

14. Now that you have your properties defined, let’s configure a new connector configuration. Goback to the Message Flow tab where you previously dropped the Salesforce connector andselect it.

15. Click on button on the Connector Configuration.

16. For the connector configuration we are going to put the following properties:

◦ username: ${sfdc.username}

◦ password: ${sfdc.password}

◦ securityToken: ${sfdc.securityToken}

17. Press Test Connection… to check everything is in place.

7

Page 9: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

18. Press OK (2 times).

Let’s configure the Salesforce connector to create an Account.

19. Adjacent to the Type: property click the refresh button, then select Account.

20. Remove payload word in the Record box and press Refresh Metadata.

Now that we have configured the Salesforce connector, we need to create a mapping that will

8

Page 10: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

convert the JSON message from the Request to the Account Object that is going to be saved inSalesforce.

21. Drag and Drop a Transform Component and place it before the Salesforce Connector.

22. You can use the drag and drop to connect each field from the request (input) to the Salesforceobject (output). In this mapping you will also use a function, uuid(), to generate a uniqueAccountNumber.

This is the mapping code that the picture reflects. You can copy and paste it into yourDataweave text editor and the UI will reflect the changes

9

Page 11: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

%dw 2.0output application/java---{  Name: payload.name,  BillingStreet: payload.billingAddress.address1,  BillingCity: payload.billingAddress.city,  BillingState: payload.billingAddress.state,  BillingPostalCode: payload.billingAddress.postalCode,  BillingCountry: payload.billingAddress.country,  ShippingStreet: payload.shippingAddress.address1,  ShippingCity: payload.shippingAddress.city,  ShippingState: payload.shippingAddress.state,  ShippingPostalCode: payload.shippingAddress.postalCode,  ShippingCountry: payload.shippingAddress.country,  Phone: payload.phone,  AccountNumber: uuid(),  Account_Email__c: payload.email}

NOTENotice that we first configured the Salesforce connector and then we created themapping. This was done on purpose. Doing it this way, we can have themetadata that needs to be mapped from the Request to Salesforce.

Once the Customer is saved, we need to evaluate the response from Salesforce (the request mayfail if the information being sent is invalid).

23. To do this, we are going to add a Validation: is true component. Type is true in the Mule Palette

24. Drag and drop the icon at the end of the Flow.

WARNING You might be asked to select the version. Always choose the latest one.

25. Implement the validation properties

a. Display Name: Validate Response

b. Expression: #[payload.success == true]

c. Message: Account Creation was Unsuccessful

10

Page 12: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

In the Validation component we are evaluating the Salesforce response.

26. In the Validation, there are going to be two configuration changes, the Expression and theMessage. Also, You will ensure that the out of the box error type is used to generate a validationerror.

a. Validate the response value

b. If there was an error, we are going to respond with a Bad Request.

27. Check the error mapping for the validation. Click the Error Mapping tab and click the button to view the out of the box error types, note the VALIDATION:INVALID_BOOLEAN is pre-populated so you don’t have to do anything else here.

In this case we are not going to map the error validation to a custom error. Instead, we aregoing to add the VALIDATION:INVALID_BOOLEAN to the APIKIT errors.

28. Now, set the VALIDATION:INVALID_BOOLEAN in the APIKIT:BAD_REQUEST Error handler.Navigate towards the top of the api Message Flow view, locate the error handler, and select theError Type.

11

Page 13: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

CAUTION If the Error is not listed write the error name manually.

NOTENotice that mule provides an easy way to generate and capture out of the box, aswell as, custom error types, to enable easy configuration of error handlingscenarios.

You have validated the response, the remaining step consists of retrieving the new account andmapping to the response.

29. Similar to the earlier step, drag and drop a Query Single component within the Salesforceconnector to the end of the flow and configure the following properties:

a. Display Name: Get Account Detail

b. Connector Configurator: Salesforce_Config (we are reusing the configuration we createdbefore).

c. Salesforce query: SELECT Id, AccountNumber, Name FROM Account where Id = ':id'

d. Parameters:

i. Name: "id"

ii. Value: payload.id

12

Page 14: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

30. Now we will create the transform step that will build the service response. To do that drag anddrop a Transform Message after the Salesforce icon that was created in the previous step.

31. Right click on the Transform Message and select Rename. Change the Transform Message textwith SFDC Account Detail to JSON.

32. Click on the icon and let’s see the transformation

You will see the response from SFDC and the API Response.

33. Map each SFDC field with its corresponding response.

13

Page 15: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

NOTEIf you look carefully, you will notice that the Id and AccountNumber are definedas optional in the input. While in the output they are mandatory. That’s why youset a default value.

34. Click the Save button.

This concludes the customer creation logic and we are ready to test the API.

Step 2: Error HandlingWe built the flow that will create a new user. If there’s an error in Salesforce, you’ll receive a BadRequest. This error message doesn’t give you full visibility into what really happened.

In this section we are going to catch the exception and send the correct error message.

1. Go to the palette and search for the Try component.

2. Insert the Try component after the Salesforce connector.

3. Move the Validation icon inside the Try component.

Now we need to configure the error handling. To do that we are going to add an On ErrorPropagate handler to the Error handling part.

4. Go to the palette and search for On Error Propagate. Drag and Drop the component inside theError handling part.

14

Page 16: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

5. Click on the component.

6. In the Type section click the magnifier glass on the right

7. Select VALIDATION:INVALID_BOOLEAN

8. Add a Logger component to log the response.

15

Page 17: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

9. Configure the component with the value output application/json --- payload

NOTEWhen you press the f(x) button, you will see that a #[] is added to the field. Thisis because we are going to use a dataweave expression to log the Salesforceresponse.

After logging the response, we are going to raise a new error

10. Search for Raise Error component and insert after the logger.

11. Configure the component with the following values:

◦ Type: APP:CONFLICT

◦ Description: #[payload.errors[0].message]

In the last step, we are raising a new error type called APP:CONFLICT and we arepopulating the details, with the Salesforce error message.

Now we are going to build the Response for this exception.

12. Go to the APIKit Error handling. Add an On Error Propagate component at the bottom.

16

Page 18: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

13. Click on the Component and configure the Type value with APP:CONFLICT.

14. Add a Transform component inside the On Error Propagate.

17

Page 19: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

15. Add the following transformation

%dw 2.0output application/json---{message: error.description}

NOTEWe are mapping the description message we set in the Raised Error component.If you want to see the complete error object, you can add a logger before thetransformation.

We also need to set the http status code. To do that we are going to add a variable inside thetransformation component

16. Click on the inside the transformation component.

A new window will appear

18

Page 20: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

17. Select Variable in the combo and write httpStatus as Variable Name.

18. Click OK

19. Remove the script and only add 409

That’s it we are ready to go to the next Lab where you will test the API.

SummaryIn this lab, we

• Implemented Post Flow

19

Page 21: Lab 2: Implement the customer creation logicmule4.workshop.tools.mulesoft.com/pdf/module3_lab2.pdf1. With the api view selected, click the Add Module sign in the Mule Palette view

• Configured Salesforce Connector

• Save and Retrieve a Salesforce Account Object

• Handled Salesforce Error

Go Further:

• See the link Dataweave doc for more information

• See the link Salesforce Connector doc for more information

• See the link Validation Module for more information

• See the link Raise Error Component for more module3_lab2_error_mapping_transformation

• See the link Error Handling for more information

Congratulations! You have completed Lab 2.

Please proceed to Lab 3

Take me to the TOP

20