In this article, we will discuss creating and testing a Node/Express microservice using Swagger.
Technologies
- node.js
- express.js
- swagger
- supertest
Installing swagger
Before installing swagger for node.js, we need to make sure node and npm are installed.
Check the same using following commands :
node -v
npm -v
Now, we can install swagger using npm using :
npm install – g swagger
Create swagger project
We can create a swagger project using following command :
swagger project create hello-world
This command will ask you to choose the framework.. select “express” :
$ swagger project create hello-world
? Framework?
connect
❯ express
hapi
restify
sails
Here are some of the files we need to check :
swagger.yaml
The swagger.yaml contains documentation on the resource paths, routes and request/response schema definitions.
The below swagger.yaml contains details for any request for “/hello”.
swagger: "2.0" info: version: "0.0.1" title: Hello World App # during dev, should point to your local machine host: localhost:10010 # basePath prefixes all resource paths basePath: / # schemes: # tip: remove http to make production-grade - http - https # format of bodies a client can send (Content-Type) consumes: - application/json # format of the responses to the client (Accepts) produces: - application/json paths: /hello: # binds a127 app logic to a route x-swagger-router-controller: hello_world get: description: Returns 'Hello' to the caller # used as the method name of the controller operationId: hello parameters: - name: name in: query description: The name of the person to whom to say hello required: false type: string responses: "200": description: Success schema: # a pointer to a definition $ref: "#/definitions/HelloWorldResponse" # responses may fall through to errors default: description: Error schema: $ref: "#/definitions/ErrorResponse" /swagger: x-swagger-pipe: swagger_raw # complex objects have schema definitions definitions: HelloWorldResponse: required: - message properties: message: type: string ErrorResponse: required: - message properties: message: type: string
hello_world.js
The swagger yaml contains the controller definition.
x-swagger-router-controller: hello_world
The hello_world.js controller will contain the business logic for handling the operation.
'use strict'; var util = require('util'); module.exports = { hello: hello }; function hello(req, res) { // variables defined in the Swagger document can be referenced using req.swagger.params.{parameter_name} var name = req.swagger.params.name.value || 'stranger'; var hello = util.format('Hello, %s!', name); // this sends back a JSON response which is a single string res.json(hello); }
app.js
'use strict'; var SwaggerExpress = require('swagger-express-mw'); var app = require('express')(); module.exports = app; // for testing var config = { appRoot: __dirname // required config }; SwaggerExpress.create(config, function(err, swaggerExpress) { if (err) { throw err; } // install middleware swaggerExpress.register(app); var port = process.env.PORT || 10010; app.listen(port); if (swaggerExpress.runner.swagger.paths['/hello']) { console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott'); } });
Running project
The project can be started using following command :
swagger project start
$ swagger project start
Starting: /services/hello-world/app.js...
project started here: http://localhost:10010/
project will restart on changes.
to restart at any time, enter `rs`
try this:
curl http://127.0.0.1:10010/hello?name=Scott
At this point, we can test the service using the curl or directly using the url:
http://127.0.0.1:10010/hello
“Hello, stranger!”
We can also pass a name as :
http://127.0.0.1:10010/hello?name=John
“Hello, John!”
Swagger UI
swagger project edit
The project can be tested using swagger UI using following command :
swagger project edit
$ swagger project edit
Starting Swagger Editor.
Opening browser to: http://127.0.0.1:51396/#/edit
Do not terminate this process or close this window until finished editing.
Testing project
The swagger project would automatically create the supertest test script in test folder.
var should = require('should'); var request = require('supertest'); var server = require('../../../app'); describe('controllers', function() { describe('hello_world', function() { describe('GET /hello', function() { it('should return a default string', function(done) { request(server) .get('/hello') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .end(function(err, res) { should.not.exist(err); res.body.should.eql('Hello, stranger!'); done(); }); }); it('should accept a name parameter', function(done) { request(server) .get('/hello') .query({ name: 'Scott'}) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .end(function(err, res) { should.not.exist(err); res.body.should.eql('Hello, Scott!'); done(); }); }); }); }); });
The project can be tested using :
swagger project test
$ swagger project test
Running tests in: /services/hello-world/test...
try this:
curl http://127.0.0.1:10010/hello?name=Scott
controllers
hello_world
GET /hello
✓ should return a default string (96ms)
✓ should accept a name parameter
2 passing (2s)
done
© 2021, https:. All rights reserved. On republishing this post, you must provide link to original post