Step 3 - Build and test a microservice
Let's build a service called hello. We'll use the handy Hydra generator and mostly select the defaults.
$ yo fwsp-hydra
? Name of the service (`-service` will be appended automatically) hello
? Host the service runs on?
? Port the service runs on? 0
? What does this service do? Says hello
? Does this service need auth? No
? Is this a hydra-express service? Yes
? Set up a view engine? No
? Enable CORS on serverResponses? No
? Run npm install? No
create hello-service/.editorconfig
create hello-service/.eslintrc
create hello-service/.gitattributes
create hello-service/.nvmrc
create hello-service/.jscsrc
create hello-service/specs/test.js
create hello-service/specs/helpers/chai.js
create hello-service/.gitignore
create hello-service/package.json
create hello-service/README.md
create hello-service/hello-service.js
create hello-service/config/sample-config.json
create hello-service/config/config.json
create hello-service/routes/hello-v1-routes.js
Done!
'cd hello-service' then 'npm install' and 'npm start'
Here's what was created:
.
├── README.md
├── config
│ ├── config.json
│ └── sample-config.json
├── hello-service.js
├── node_modules
├── package.json
├── routes
│ └── hello-v1-routes.js
└── specs
├── helpers
└── test.js
Edit the `routes/hello-v1-routes.js` to make things more interesting.
Change line 18 from:
result: {}
to:
result: {
msg: `${hydra.getServiceName()} - ${hydra.getInstanceID()}`
}
Following the instructions above we can continue to build our service.
$ cd hello-service
$ npm install
$ npm start
After starting the service we see that it launched using a random port.
serviceInfo { serviceName: 'hello-service',
serviceIP: '10.1.1.163',
servicePort: 8891 }
You can access the service via curl:
$ curl 10.1.1.163:8891/v1/hello
{"statusCode":200,"statusMessage":"OK","statusDescription":"Request succeeded without error","result":{"msg":"hello-service - 50bf4346dd492c2036cfd57ad8bd2844"}}
or via your browser: http://10.1.1.163:8891/v1/hello
We can also use the hydra-cli app we installed to obtain information about our service:
$ hydra-cli nodes
[
{
"serviceName": "hello-service",
"serviceDescription": "Says hello",
"version": "0.0.1",
"instanceID": "b1554f404acc3268c1511dc84ae43c50",
"updatedOn": "2016-11-15T18:18:56.438Z",
"processID": 20542,
"ip": "10.1.1.163",
"port": 8891,
"elapsed": 4
}
]
{
"hello-service": [
"[GET]/_config/hello-service",
"[get]/v1/hello/"
]
}
This information is being emitted by our service and it allows services to discover one another and send messages to each other. Combined with the Hydra-Router you can build an entire network of microservices.
To find out what you can do with your new microservice see the Hydra methods.