AutoCodeGen - Custom Endpoints Debit Transaction
In this article, we add a custom endpoint to make a debit transaction.In the previous article, we discussed how to add a custom endpoint to perform credit transactions and you can learn more about it by clicking on this link.
First, we finalize our query in the pgAdmin query editor. below is our final query.
Here user wants to spend money from his account, first thing we need to ensure is a user cannot spend more than what s/he has.
We create a record in our transaction table based on three conditions. first, ensure there is an account with the requested account_id exist, next ensure there is an associated customer_id there, and finally, and most importantly ensure that amount to be debited is less than or equal to the amount available in the account. and we will construct our query based on these conditions.
We have two sets of queries here, first is to create a record in the transactions table if the above-mentioned three conditions are met. And next query is to update the account_balance information in the accounts table if the same three aforementioned conditions are met. We wrote the query and we tested it on pgAdmin and it is working.
Now it is time to convert fixed values in the query into variables so we can dump this into AutoCodeGen and generate the custom endpoint.Below is the screenshot of our query with constants replaced by variables.
In the screenshot of AutoCodeGen UI, the third row is ur custom query we wrote and we are passing all the necessary request variables from the body.
Below is the screenshot of the code after generation and merging with our existing code base.
Before we execute the custom query from the thunder-client, we made a get-all-accounts API call to see the account balance of our account holder, Rando. we can see that his account balance is 4801 INR.
Now we are going to debit 301 INR from Mr. Rando's account by making an API call on the custom endpoint we just generated. We pass the necessary request variables in the body and our API request is a success.
Now let us make an API call to get all transactions endpoint. As we can see our latest transaction is recorded in our database.
Now let us check the account balance of our user Mr. Rando and as we can his account_balnce has come down by 301 INR and now it is at 4500 INR.
Now is the most important test of all. Let us make a debit transaction to debit more than 4500 INR from Mr. Rando's account. The expectation is that there should be any record of that transaction in our transaction table and the account balance of Mr. Rando in the accounts table remains the same.
As expected our excess debit transaction has thrown an error, you can handle this based on your business needs.
There is no record of this excess debit transaction, as expected.
And Mr. Rando's balance is unchanged as expected.