In LoopBack, a Node function attached to a custom REST endpoint is called a remote method.
In this section you're going to add a custom remote method to your API.
Get the app (in the state following the last article) from GitHub and install all its dependencies:
$ git clone https://github.com/strongloop/loopback-getting-started.git $ cd loopback-getting-started $ git checkout step2 $ npm install
Add a remote method
Follow these steps:
Look in your application's
/common/models
directory. You'll notice there is acoffee-shop.js
file there.Open
coffee-shop.js
in your favorite editor. By default, it contains an empty function:module.exports = function(CoffeeShop) { };
Add the following code to this function to extend the model's behavior with a remote method, so it looks as shown here:
module.exports = function(CoffeeShop) { CoffeeShop.status = function(cb) { var currentDate = new Date(); var currentHour = currentDate.getHours(); var OPEN_HOUR = 6; var CLOSE_HOUR = 20; console.log('Current hour is ' + currentHour); var response; if (currentHour > OPEN_HOUR && currentHour < CLOSE_HOUR) { response = 'We are open for business.'; } else { response = 'Sorry, we are closed. Open daily from 6am to 8pm.'; } cb(null, response); }; CoffeeShop.remoteMethod( 'status', { http: {path: '/status', verb: 'get'}, returns: {arg: 'status', type: 'string'} } ); };
This defines a simple remote method called "status" that takes no arguments, and checks the time and returns a JSON status message that says either "Open for business" or "Sorry we are closed depending on the current time.
Of course, in practice you can do much more interesting and complex things with remote methods such as manipulating input data before persisting it to a database. You can also change the route where you call the remote method, and define complex arguments and return values. See 远程方法(Remote methods) for all the details.
Save the file.
Try the remote method
Back in the application root directory, run the app:
$ slc run
Go to http://localhost:3000/explorer to see API Explorer. Then click on CoffeeShops and you'll see there is a new REST endpoint,
GET/CoffeeShop/status
that calls the remote method.- Click Try it Out!
You'll see the result of calling your remote method :{ "status": "Open for business."
}
That's how easy it is to add remote methods with LoopBack!
For more information, see 远程方法(Remote methods).