concept server method in category hapi

appears as: Server methods, server method, The server method, server methods
hapi.js in Action

This is an excerpt from Manning's book hapi.js in Action.

Server methods are functions that are attached to a hapi server object. They can then be accessed and called from wherever the server object is in scope. Server methods are intended to be called from within route handlers.

Okay, so they are another way to access shared functions—probably doesn’t sound impressive at this point, right? To be honest, my opinion of server methods was fairly low when I first encountered them too. They seem to be solving a problem that doesn’t exist on the face of it (that’s what modules are for!). But I was won over after seeing some of the powerful functionality you can get for free when opting to use them.

Probably the biggest advantage to using server methods is the simple caching model they provide. Chapter 8 looks at this in-depth.

First things first. Let’s see what server methods look like and how to create and use them.

Server methods are created by calling server.method(). This method has three required arguments, a name for the server method, the function, and an options object. The server method is then usable inside route handlers by calling server.methods.name(), where name is the name you gave to the method. Figure 4.5 shows this pattern.

Figure 4.5. Creating and using a server method

Rather than returning the end result, notice that server methods always call the next callback with the result. Doing so allows for any asynchronous behavior that you may want to include in the server method, such as making an HTTP request or reading from the filesystem.

The following listing shows the example from listing 4.12 rewritten, using a server method to calculate the mean value of the array.

Listing 4.13. Creating and using the mean server method

You should now understand what server methods are and how to create and use them.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest