Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update service.md #36

Open
wants to merge 1 commit into
base: v3
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions en/build/service.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Let's build a simple web service that returns the latest version of some popular
```js
// api/controller/VersionController.js

const Controller = require('trails/controller')

module.exports = class VersionController extends Controller {

/**
Expand All @@ -25,7 +27,7 @@ module.exports = class VersionController extends Controller {
getLatest (request, reply) {
const { packageName } = request.params

this.services.VersionService.getLatest(packageName)
this.app.services.VersionService.getLatest(packageName)
.then(version => {
return reply({
[packageName]: `v${version}`
Expand All @@ -40,9 +42,15 @@ module.exports = class VersionController extends Controller {

`VersionService` will request version information from [semver.io](http://semver.io), an external web service that hosts version information on nodejs, npm, yarn, and other tools. Separating out this business logic from the request-handling duties of the Controller is a good practice for separating concerns and organizing code.

We will use request-promise module for http request. To install this module, simply do `npm install --save request-promise`

Content of the service file:

```js
// api/services/VersionService.js

const Service = require('trails/service')

const request = require('request-promise')

module.exports = class VersionService extends Service {
Expand All @@ -61,11 +69,11 @@ module.exports = class VersionService extends Service {
* @param packageName
*/
getLatest (packageName) {
if (!VersionService.supportedPackages.find(packageName)) {
if (!VersionService.supportedPackages.find(x => x == packageName)) {
throw new Error(`${packageName} not supported`)
}

return request(`semver.io/${packageName}`)
return request(`http://semver.io/${packageName}`)
}
}
```
Expand Down