We run lb remote-method and select product model. The name of our remote method will be buy. This is not a static method, so it will live on the prototype. The description will be, "Buy this product." The HTTP endpoint will be /buy, and the verb will be post. Then we hit enter, because we only want to add one endpoint.
Next, the generator will ask us which arguments we want to accept. We enter quantity, which is of type number and is required. In this description, we will enter the number of products to buy.
We will let LoopBack autodetect where to get the value from, and because we only need one argument, we will hit enter. Now, the generator asks us what we want the remote method to return. The name of our argument will be results, which is a type of object, and it will be the full response body.
As a description, we will enter the results of the purchase. Now, we hit enter to finalize the generator. The generator tells us where it created the metadata and where we can define the actual remote method. It also gives us an example method we can use in our model.
When we look at product.json in our IDE, we see that our buy method got defined here. When we open the API explorer and look in the product model, we see that our new endpoint got defined.
When we enter the ID of a product and the quantity, and execute the remote method, we see that we get an error message. This is because we did not define the actual method, only the metadata.
Let's open up product.js, and paste in the example code from the generator. When we execute the method again, instead of an error message, we now get no contents. This is because our result variable is empty. When we change it to an object literal and enter the quantity, we finally get a result.
We can make the method a bit more useful by changing the result to an object with a status key and a friendly message. The result will now say, "You bought one product."
Now, there's one thing that we need to fix here, and that's that we don't want to allow a quantity less than one. To do this, we first create a helper method in our model that checks for a valid quantity. This method will return false if the quantity is smaller than one.
Now, we add a condition in our remote method that invokes the helper method. If the quantity is too low, we will return our callback with an error message. Let's try this out. We enter a quantity of -1, execute it, and an error message will be returned.