Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

hapi-swagger

Package Overview
Dependencies
Maintainers
1
Versions
163
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

hapi-swagger - npm Package Compare versions

Comparing version 3.1.1 to 3.2.0

public/extend.js

103

bin/routes.js

@@ -161,2 +161,85 @@ 'use strict';

method: 'PUT',
path: '/contenttype/1',
config: {
handler: defaultHandler,
description: 'Add',
tags: ['api'],
plugins: {
'hapi-swagger': {
consumes: ['application/json','application/json;charset=UTF-8','application/json; charset=UTF-8'],
order: 2
}
},
validate: {
payload: {
a: Joi.number()
.required()
.description('the first number'),
b: Joi.number()
.required()
.description('the second number')
}
},
payload:{
allow: ['application/json','application/json;charset=UTF-8','application/json; charset=UTF-8']
}
}
},{
method: 'PUT',
path: '/contenttype/2',
config: {
handler: defaultHandler,
description: 'Add',
tags: ['api'],
plugins: {
'hapi-swagger': {
produces: ['application/json','application/xml'],
order: 1
}
},
validate: {
payload: Joi.object({
a: Joi.number()
.required()
.description('the first number'),
b: Joi.number()
.required()
.description('the second number')
}).label('sum_input')
}
}
},{
method: 'PUT',
path: '/contenttype/3',
config: {
handler: defaultHandler,
description: 'Add',
tags: ['api'],
plugins: {
'hapi-swagger': {
order: 1
}
},
validate: {
payload: {
a: Joi.number()
.required()
.description('the first number'),
b: Joi.number()
.required()
.description('the second number')
},
headers: Joi.object({
'content-type': Joi.string().valid([
'application/json',
'application/json;charset=UTF-8',
'application/json; charset=UTF-8'])
}).unknown()
}
}
},{
method: 'PUT',
path: '/sum/add/{a}/{b}',

@@ -170,3 +253,3 @@ config: {

'hapi-swagger': {
responses: resultHTTPStatus
consumes: ['application/json', 'application/xml']
}

@@ -183,10 +266,5 @@ },

.description('the second number')
},
headers: Joi.object({
'x-format': Joi.string()
.valid('decimal', 'binary')
.default('decimal')
.description('return result as decimal or binary')
}).unknown()
}
}
}

@@ -228,3 +306,4 @@ }, {

'hapi-swagger': {
responses: resultHTTPStatus
responses: resultHTTPStatus,
order: 3
}

@@ -253,3 +332,4 @@ },

'hapi-swagger': {
responses: resultHTTPStatus
responses: resultHTTPStatus,
order: 2
}

@@ -460,3 +540,4 @@ },

responses: fileHTTPStatus,
payloadType: 'form'
payloadType: 'form',
consumes: ['multipart/form-data']
}

@@ -463,0 +544,0 @@ },

16

bin/test-server.js

@@ -60,4 +60,4 @@ 'use strict';

tags: [{
'name': 'store',
'description': 'Storing a sum',
'name': 'contenttype',
'description': 'temp endpoints for content-type',
'externalDocs': {

@@ -69,3 +69,3 @@ 'description': 'Find out more',

'name': 'sum',
'description': 'API of sums',
'description': 'working with maths',
'externalDocs': {

@@ -75,4 +75,10 @@ 'description': 'Find out more',

}
}],
derefJSONSchema: false
}, {
'name': 'store',
'description': 'storing data',
'externalDocs': {
'description': 'Find out more',
'url': 'http://example.org'
}
}]
};

@@ -79,0 +85,0 @@

@@ -78,3 +78,3 @@ 'use strict';

routes = Filter.byTags(['api'], routes);
Sort.paths(settings.sortPath, routes);
Sort.paths(settings.sortPaths, routes);

@@ -167,2 +167,4 @@ // filter routes displayed based on tags passed in query string

'lang',
'sortTags',
'sortEndpoints',
'sortPaths',

@@ -169,0 +171,0 @@ 'addXProperties',

@@ -23,2 +23,4 @@ 'use strict';

lang: Joi.string().valid(['en', 'es', 'pt', 'ru']),
sortTags: Joi.string().valid(['default', 'name']),
sortEndpoints: Joi.string().valid(['path', 'method', 'ordered']),
sortPaths: Joi.string().valid(['unsorted', 'path-method']),

@@ -42,2 +44,4 @@ addXProperties: Joi.boolean(),

'lang': 'en',
'sortTags': 'default',
'sortEndpoints': 'path',
'sortPaths': 'unsorted',

@@ -59,3 +63,4 @@ 'addXProperties': false,

const settings = Hoek.applyToDefaults(defaults, options);
const swaggerDirPath = __dirname + Path.sep + '..' + Path.sep + 'public' + Path.sep + 'swaggerui';
const publicDirPath = __dirname + Path.sep + '..' + Path.sep + 'public';
const swaggerDirPath = publicDirPath + Path.sep + 'swaggerui';

@@ -127,2 +132,11 @@ // add routing swagger json

}
},{
method: 'GET',
path: settings.swaggerUIPath + 'extend.js',
config: {
auth: settings.auth
},
handler: {
file: publicDirPath + Path.sep + 'extend.js'
}
}]);

@@ -129,0 +143,0 @@ }

@@ -74,2 +74,3 @@ 'use strict';

security: Hoek.reach(routeOptions, 'security') || null,
order: Hoek.reach(routeOptions, 'order') || null,
groups: route.group

@@ -79,2 +80,4 @@ };

// user configured interface through route plugin options

@@ -140,5 +143,7 @@ if (Hoek.reach(routeOptions, 'validate.query')) {

'description': route.notes,
'parameters': []
'parameters': [],
'consumes': [],
'produces': []
};
let path = route.path;
let path = internals.cleanPathParameters( route.path );

@@ -155,19 +160,3 @@ // tags in swagger are used for grouping

let payloadType = internals.overload(settings.payloadType, route.payloadType);
let consumes = internals.overload(settings.consumes, route.consumes);
let produces = internals.overload(settings.consumes, route.produces);
if (route.consumes) {
out.consumes = route.consumes;
}
if (route.produces) {
out.produces = route.produces;
}
// use mimetype to override payloadType
if (Array.isArray(consumes)
&& (consumes.indexOf('application/x-www-form-urlencoded') > -1
|| consumes.indexOf('multipart/form-data') > -1)) {
payloadType = 'form';
}
// build payload either with JSON or form input

@@ -201,8 +190,22 @@ let payloadParameters;

// add form mimetype
out.consumes = (out.consumes) ? out.consumes : [];
if (out.consumes.indexOf('application/x-www-form-urlencoded') === -1) {
out.consumes = ['application/x-www-form-urlencoded'];
}
out.consumes = ['application/x-www-form-urlencoded'];
}
// change form mimetype based on meta property 'swaggerType'
if (internals.hasFileType(route)) {
out.consumes = ['multipart/form-data'];
}
// add user defined over automaticlly dicovered
if (settings.consumes || route.consumes) {
out.consumes = internals.overload(settings.consumes, route.consumes);
}
if (settings.produces || route.produces) {
out.produces = internals.overload(settings.produces, route.produces);
}
out.parameters = out.parameters.concat(

@@ -217,9 +220,5 @@ Properties.toParameters(internals.getJOIObj(route, 'headerParams'), swagger.definitions, 'header'),

// change form mimetype based on meta property 'swaggerType'
if (internals.hasFileType(route)) {
out.consumes = (out.consumes) ? out.consumes : [];
// add to front of array so swagger-ui picks it up
if (out.consumes.indexOf('multipart/form-data') === -1) {
out.consumes = ['multipart/form-data'];
}
// if the api sets the content-type header pramater use that
if (internals.hasContentTypeHeader(out)) {
delete out.consumes;
}

@@ -236,6 +235,10 @@

if (route.order) {
out['x-order'] = route.order;
}
if (!pathObj[path]) {
pathObj[path] = {};
}
pathObj[path][method.toLowerCase()] = out;
pathObj[path][method.toLowerCase()] = Utilities.deleteEmptyProperties(out);
});

@@ -289,1 +292,32 @@

};
/**
* clear path parameters of optional char flag
*
* @param {String} path
* @return {String}
*/
internals.cleanPathParameters = function (path) {
return path.replace('?}','}');
};
/**
* does path parameters have a content-type header
*
* @param {String} path
* @return {boolean}
*/
internals.hasContentTypeHeader = function (path) {
let out = false;
path.parameters.forEach(function (prama) {
if (prama.in === 'header' && prama.name.toLowerCase() === 'content-type') {
out = true;
}
});
return out;
};

@@ -86,8 +86,9 @@ 'use strict';

let name = obj.key;
let definitionName = name;
let joiChildObj = obj.schema;
// get name form label if set
if (Hoek.reach(joiChildObj, '_settings.language.label')) {
name = Hoek.reach(joiChildObj, '_settings.language.label');
definitionName = Hoek.reach(joiChildObj, '_settings.language.label');
}
propertiesObj[name] = properties.parseProperty(name, joiChildObj, definitionCollection, type);
propertiesObj[name] = properties.parseProperty(definitionName, joiChildObj, definitionCollection, type);
});

@@ -156,3 +157,3 @@ }

return item !== '';
return item !== '' && item !== null;
});

@@ -159,0 +160,0 @@ if (enums.length > 0) {

@@ -64,5 +64,11 @@ 'use strict';

}
} else {
// add default Successful if we still have no responses
out[200] = {
}
// use plug-in overrides to enchance hapi objects and properties
if (Utilities.hasProperties(userDefindedSchemas) === true) {
out = internals.override(out, userDefindedSchemas, definitionCollection, altName);
}
if (Utilities.hasProperties(out) === false) {
out.default = {
'schema': {

@@ -75,8 +81,2 @@ 'type': 'string'

// use plug-in overrides to enchance hapi objects and properties
if (Utilities.hasProperties(userDefindedSchemas)) {
out = internals.override(out, userDefindedSchemas, definitionCollection, altName);
}
return Utilities.deleteEmptyProperties(out);

@@ -98,25 +98,24 @@ };

for (let key in userDefindedSchemas) {
if (userDefindedSchemas.hasOwnProperty(key)) {
// create a new object by cloning - dont modify user definded objects
let out = Hoek.clone(userDefindedSchemas[key]);
// create a new object by cloning - dont modify user definded objects
let out = Hoek.clone(userDefindedSchemas[key]);
// test for any JOI objects
if (Hoek.reach(userDefindedSchemas[key], 'schema.isJoi') && userDefindedSchemas[key].schema.isJoi === true) {
// test for any JOI objects
if (Hoek.reach(userDefindedSchemas[key], 'schema.isJoi') && userDefindedSchemas[key].schema.isJoi === true) {
const responseName = Hoek.reach(userDefindedSchemas[key].schema, '_settings.language.label');
// convert JOI objects into Swagger defination references
out.schema = {
'$ref': '#/definitions/' + Definitions.appendJoi(
responseName,
userDefindedSchemas[key].schema,
definitionCollection,
internals.altLabel(altName, key)
)
};
}
const responseName = Hoek.reach(userDefindedSchemas[key].schema, '_settings.language.label');
// convert JOI objects into Swagger defination references
out.schema = {
'$ref': '#/definitions/' + Definitions.appendJoi(
responseName,
userDefindedSchemas[key].schema,
definitionCollection,
internals.altLabel(altName, key)
)
};
}
// overwrite discovery with user definded
discoveredSchemas[key] = Utilities.deleteEmptyProperties(out);
}
// overwrite discovery with user definded
discoveredSchemas[key] = Utilities.deleteEmptyProperties(out);
}

@@ -123,0 +122,0 @@ return discoveredSchemas;

@@ -17,6 +17,8 @@ 'use strict';

if (sortType === 'path-method') {
//console.log('path-method')
routes.sort(
Utilities.firstBy('path').thenBy('method')
);
);
}

@@ -26,4 +28,1 @@

};

@@ -18,3 +18,4 @@ 'use strict';

url: Joi.string().uri()
})
}),
'x-order': Joi.number()
})

@@ -21,0 +22,0 @@ .label('Tag')

'use strict';
var Hoek = require('hoek');
const Hoek = require('hoek');
var utilities = module.exports = {};
const utilities = module.exports = {};

@@ -6,0 +6,0 @@

@@ -9,2 +9,8 @@ MIT License - hapi-swagger

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
curl -X PUT
--header "Content-Type: application/json"
--header "Accept: application/json"
--header "content-type: application/json;charset=UTF-8"
"http://localhost:3000/sum/add/345/3452"
{
"name": "hapi-swagger",
"description": "A swagger documentation UI generator plugin for hapi",
"version": "3.1.1",
"version": "3.2.0",
"author": "Glenn Jones",

@@ -23,7 +23,7 @@ "repository": {

"dependencies": {
"boom": "^3.0.0",
"boom": "^3.1.0",
"handlebars": "^4.0.5",
"hoek": "^3.0.4",
"http-status": "0.2.0",
"joi": "7.0.1",
"joi": "7.2.1",
"shortid": "2.2.4",

@@ -36,5 +36,5 @@ "json-schema-ref-parser": "^1.4.0"

"blipp": "^2.1.3",
"lab": "8.0.0",
"code": "2.0.1",
"hapi": "^12.0.0",
"lab": "8.1.0",
"code": "2.1.0",
"hapi": "^12.1.0",
"wreck": "7.0.0",

@@ -41,0 +41,0 @@ "coveralls": "2.11.6",

# hapi-swagger
This is a [The OpenAPI (aka Swagger)](https://openapis.org/) plug-in for [HAPI](http://hapijs.com/) v9.x to v12.x When installed it will self document the API interface
This is a [OpenAPI (aka Swagger)](https://openapis.org/) plug-in for [HAPI](http://hapijs.com/) v9.x to v12.x When installed it will self document the API interface
in a project.

@@ -12,3 +12,3 @@

__NEW VERSION (v3.0.0 DEC 2015) - PLEASE REVIEW UPDATE INFORMATION - [Breaking changes in release notes](https://github.com/glennjones/hapi-swagger/issues/180)__
__NEW VERSION (v3.x DEC 2015) - PLEASE REVIEW UPDATE INFORMATION - [Breaking changes in release notes](https://github.com/glennjones/hapi-swagger/issues/180)__

@@ -23,3 +23,3 @@

If you want to view the documentation from your API you will also need to install the `inert` and `vision` plugs-ins which support templates and static
content serving. If you wish just to used swagger.json without the documentation for example with swagger-codegen simply set `enableDocumentation` to `false`.
content serving. If you wish just to used swagger.json without the documentation for example with swagger-codegen simply set `options.enableDocumentation` to `false`.

@@ -33,2 +33,3 @@ $ npm install inert --save

```Javascript

@@ -47,3 +48,3 @@ const Hapi = require('hapi');

const swaggerOptions = {
const options = {
info: {

@@ -59,4 +60,4 @@ 'title': 'Test API Documentation',

{
register: HapiSwagger,
options: swaggerOptions
'register': HapiSwagger,
'options': options
}], (err) => {

@@ -81,3 +82,3 @@ server.start( () => {

config: {
handler: handlers.mapUsername,
handler: handlers.getToDo,
description: 'Get todo',

@@ -106,3 +107,3 @@ notes: 'Returns a todo item by the id passed in the path',

* `schemes`: (array) The transfer protocol of the API ie `['http']`
* `host`: (string) The host (name or ip) serving the API including port if any i.e. `localhost:8080`
* `host`: (string) The host (name or IP) serving the API including port if any i.e. `localhost:8080`
* `basePath`: (string) The base path from where the API starts i.e. `/v2/` (note, needs to start with `/`) - default: `/`

@@ -115,5 +116,7 @@ * `pathPrefixSize`: (number) Selects what segment of the URL path is used to group endpoints

* `expanded`: (boolean) If UI is expanded when opened - default: `true`
* `sortPaths`: (string) the path sort method for JSON. `unsorted` or `path-method`,
* `tags`: (array) containing array of [Tag Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#tagObject) used to group endpoints in UI.
* `lang`: (string) The language of the UI either `en`, `es`, `pt` or `ru` - default: `en`
* `tags`: (object) Containing [Tag Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#tagObject) used to group endpoints in swagger-ui.
* `sortTags`: (string) a sort method for `tags` i.e. groups in UI. `default` or `name`
* `sortEndpoints`: (string) a sort method for endpoints in UI. `path`, `method`, `ordered`
* `sortPaths`: (string) a sort method for `path` objects in JSON. `unsorted` or `path-method`
* `securityDefinitions:`: (array) Containing [Security Definitions Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securityDefinitionsObject). No defaults are provided.

@@ -139,3 +142,3 @@

```Javascript
const swaggerOptions = {
const options = {
'info': {

@@ -158,7 +161,8 @@ 'title': 'Test API Documentation',

* `security:`: (array) Containing [Security Requirement Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#securityRequirementObject). No defaults are provided.
* `order`: (int) The order in which endpoints are displayed, works with `options.sortEndpoints = 'ordered'`
### Grouping endpoints with tags
## Grouping endpoints with tags
Swagger provides a tag object which allows you to group your endpoints in the swagger-ui interface. The name of the tag needs to match path of your endpoinds, so in the example below all enpoints with the path `/store` and `/sum` will be group togther.
```Javascript
let swaggerOptions = {
let options = {
info: {

@@ -169,2 +173,5 @@ 'title': 'Test API Documentation',

tags: [{
'name': 'users',
'description': 'Users data'
},{
'name': 'store',

@@ -186,4 +193,25 @@ 'description': 'Storing a sum',

```
The groups are order in the same sequence you add them to the `tags` array in the plug-in options. You can enforce the order by name A-Z by switching the plugin `options.sortTags = 'name'`.
### Route option example
## Ordering the endpoints with groups
The endpoints within the UI groups can be order with the property `options.sortEndpoints`, by default the are ordered A-Z using the `path` information. Can also order them by `method`. Finnally if you wish to enforce you own order then you added route option `order` to each endpoint and switch `options.sortEndpoints = 'ordered'`.
```Javascript
{
method: 'PUT',
path: '/test',
config: {
description: 'Add',
tags: [
'api'
],
plugins: {
'hapi-swagger': {
order: 2
}
}
}
}
```
## Route option example
The route level options are always placed within the `plugins.hapi-swagger` object under `config`. These options are only assigned to the route they are apply to.

@@ -217,3 +245,3 @@ ```Javascript

### Response Object
## Response Object
HAPI allow you to define a response object for an API endpoint. The response object is used by HAPI to both validation and description the output of an API. It uses the same JOI validation objects to describe the input parameters. The plugin turns these object into visual description and examples in the Swagger UI.

@@ -253,3 +281,3 @@

### Status Codes
## Status Codes
You can add HTTP status codes to each of the endpoints. As HAPI routes don not directly have a property for status codes so you need to add them the plugin configuration. The status codes need to be added as an array of objects with an error code and description. The `description` is required, the schema is optional and unlike added response object the example above this method does not validate the API response.

@@ -288,3 +316,3 @@

```
### File upload
## File upload
The plug-in has basic support for file uploads into your API's. Below is an example of a route with a file upload, the three important elements are:

@@ -324,3 +352,3 @@

### Naming
## Naming
There are times when you may wish to name a object so that its label in the Swagger interface make more sense to humans. This is most common when you have endpoint which take JSON structures. To label a object simply wrap it as a JOI object and chain the label function as below. __You need to give different structure its own unique name.__

@@ -336,3 +364,3 @@ ```Javascript

### Default values and examples
## Default values and examples
You can add both default values and examples to your JOI objects which are displayed within the Swagger interface. Defaults are turned into pre-fill values, either in the JSON of a payload or in the text inputs of forms.

@@ -359,3 +387,3 @@

### Headers and .unknown()
## Headers and .unknown()
A common issue with the use of headers is that you may only want to validate some of the headers sent in a request and you are not concerned about other headers that maybe sent also. You can use JOI .unknown() to allow any all other headers to be sent without validation errors.

@@ -407,2 +435,3 @@ ```Javascript

<script src='{{hapiSwagger.swaggerUIPath}}lib/swagger-oauth.js' type='text/javascript'></script>
<script src='{{hapiSwagger.swaggerUIPath}}extend.js' type='text/javascript'></script>

@@ -442,3 +471,4 @@ <!-- Some basic translations -->

docExpansion: "{{hapiSwagger.expanded}}",
apisSorter: "alpha",
apisSorter: apisSorter.{{hapiSwagger.sortTags}},
operationsSorter: operationsSorter.{{hapiSwagger.sortEndpoints}},
showRequestHeaders: false

@@ -455,2 +485,8 @@ });

});
// creates a list of tags in the order they where created
var tags = []
{{#each hapiSwagger.tags}}
tags.push('{{name}}');
{{/each}}
</script>

@@ -491,5 +527,10 @@ ```

## Features from HAPI that cannot be ported to Swagger
Not all the flexibility of HAPI and JOI can to ported over to the Swagger schema. Below is a list of the most common asked for features that cannot be ported.
* __`Joi.alternatives()`__ This allows parameters to be more than one type. i.e. string or int. Swagger does not yet support this because of a number codegen tooles using swagger build to typesafe languages. This __maybe__ added to the next version of OpenAPI spec
* __`{/filePath*}`__ The path parameters with the `*` char are not supported, either is the `{/filePath*3}` the pattern. This will mostly likely be added to the next version of OpenAPI spec.
* __`.allow( null )`__ The current Swagger spec does not support `null`. This __maybe__ added to the next version of OpenAPI spec.
### Lab test
## Lab test
The project has integration and unit tests. To run the test within the project type one of the following commands.

@@ -503,9 +544,14 @@ ```bash

If you are considering sending a pull request please add tests for the functionality you add or change.
### Thanks
I would like all that have contributed to the project over the last couple of years.
## Thanks
I would like all that have contributed to the project over the last couple of years. This is a hard project to maintain getting HAPI to work with Swagger
is like putting a round plug in a square hole. Without the help of others it would not be possible.
### Issues
If you find any issue please file here on github and I will try and fix them.
## Issues
If you find any issue please file here on github and I will try and fix them.

@@ -48,3 +48,2 @@ 'use strict';

lab.test('summary and description', (done) => {

@@ -221,2 +220,61 @@

lab.test('auto "application/x-www-form-urlencoded" do not add two', (done) => {
let testRoutes = Hoek.clone(routes);
testRoutes.config.validate = {
payload: {
file: Joi.string()
.description('json file')
}
},
testRoutes.config.plugins = {
'hapi-swagger': {
consumes: ['application/x-www-form-urlencoded']
}
};
Helper.createServer({}, testRoutes, (err, server) => {
server.inject({ method: 'GET', url: '/swagger.json' }, function (response) {
expect(err).to.equal(null);
//console.log(JSON.stringify(response.result));
expect(response.statusCode).to.equal(200);
expect(response.result.paths['/test'].post.consumes).to.deep.equal(['application/x-www-form-urlencoded']);
done();
});
});
});
lab.test('a user set content-type header removes consumes', (done) => {
let consumes = [
'application/json',
'application/json;charset=UTF-8',
'application/json; charset=UTF-8'];
let testRoutes = Hoek.clone(routes);
testRoutes.config.validate.headers = Joi.object({
'content-type': Joi.string().valid(consumes)
}).unknown();
Helper.createServer({}, testRoutes, (err, server) => {
server.inject({ method: 'GET', url: '/swagger.json' }, function (response) {
expect(err).to.equal(null);
//console.log(JSON.stringify(response.result));
expect(response.statusCode).to.equal(200);
expect(response.result.paths['/test'].post.consumes).to.not.exist();
done();
});
});
});
lab.test('payloadType form', (done) => {

@@ -245,2 +303,27 @@

lab.test('path parameters {note*}', (done) => {
let testRoutes = Hoek.clone(routes);
testRoutes.path = '/servers/{id}/{note?}';
testRoutes.config.validate = {
params: {
id: Joi.number().integer().required().description('ID of server to delete'),
note: Joi.string().description('Note..')
}
};
Helper.createServer({}, testRoutes, (err, server) => {
server.inject({ method: 'GET', url: '/swagger.json' }, function (response) {
expect(err).to.equal(null);
//console.log(JSON.stringify(response.result));
expect(response.statusCode).to.equal(200);
expect(response.result.paths['/servers/{id}/{note}']).to.exist();
done();
});
});
});
});

@@ -215,2 +215,3 @@ 'use strict';

expect(Properties.parseProperty('x', Joi.string().allow(''))).to.deep.equal({ 'type': 'string' });
expect(Properties.parseProperty('x', Joi.string().allow(null))).to.deep.equal({ 'type': 'string' });

@@ -280,3 +281,3 @@ //console.log(JSON.stringify(Properties.parseProperty('x', Joi.array().allow('a','b','c'), {}, 'query')))

let definatition = {};
let definition = {};
const parsed = Properties.parseProperties(

@@ -290,6 +291,6 @@ Joi.object().keys( {

).label('ans-l')
} ).label('ans-parent'), definatition, 'query');
} ).label('ans-parent'), definition, 'query');
const parsedExpected = {
'ans-l': {
'ans_list': {
type: 'array',

@@ -302,3 +303,3 @@ items: {

};
const definatitionExpected = {
const definitionExpected = {
'ans-o': {

@@ -318,3 +319,3 @@ 'type': 'object',

expect(parsed).to.deep.equal(parsedExpected);
expect(definatition).to.deep.equal(definatitionExpected);
expect(definition).to.deep.equal(definitionExpected);

@@ -321,0 +322,0 @@ done();

@@ -369,3 +369,3 @@ 'use strict';

expect(response.result.paths['/store/'].post.responses).to.deep.equal({
'200': {
'default': {
'schema': {

@@ -385,3 +385,3 @@ 'type': 'string'

const objA = Helper.objWithNoOwnProperty();
let objA = Helper.objWithNoOwnProperty();
const objB = Helper.objWithNoOwnProperty();

@@ -393,3 +393,3 @@ const objC = Helper.objWithNoOwnProperty();

expect(Responses.build({}, {}, {}, {})).to.deep.equal({
'200': {
'default': {
'schema': {

@@ -402,3 +402,3 @@ 'type': 'string'

expect(Responses.build(objA, objB, objC, {})).to.deep.equal({
'200': {
'default': {
'schema': {

@@ -411,4 +411,9 @@ 'type': 'string'

objA[200] = { description : 'Successful' };
expect(Responses.build( objA,objB,objC,{ } )).to.deep.equal({ 200:{ 'description': 'Successful' } });
objA = { 200: { description: 'Successful' } };
//console.log(JSON.stringify( Responses.build(objA, objB, objC, {}) ));
expect(Responses.build(objA, objB, objC, {})).to.deep.equal({
'200': {
'description': 'Successful'
}
});

@@ -415,0 +420,0 @@ done();

'use strict';
const Code = require('code');
const Lab = require('lab');
const Hoek = require('hoek');
const Sort = require('../lib/sort.js');
const Helper = require('../test/helper.js');

@@ -16,12 +15,12 @@ const expect = Code.expect;

method: 'POST',
path: '/a',
path: '/x',
config: {
tags: ['api']
tags: ['api'],
handler: Helper.defaultHandler,
plugins: {
'hapi-swagger': {
order: 7
}
}
}
},{
method: 'GET',
path: '/a',
config: {
tags: ['api']
}
}, {

@@ -31,3 +30,9 @@ method: 'GET',

config: {
tags: ['api']
tags: ['api'],
handler: Helper.defaultHandler,
plugins: {
'hapi-swagger': {
order: 5
}
}
}

@@ -38,15 +43,33 @@ }, {

config: {
tags: ['api']
tags: ['api'],
handler: Helper.defaultHandler,
plugins: {
'hapi-swagger': {
order: 4
}
}
}
}, {
method: 'GET',
path: '/b/a/b',
method: 'POST',
path: '/b/c/d',
config: {
tags: ['api']
tags: ['api'],
handler: Helper.defaultHandler,
plugins: {
'hapi-swagger': {
order: 1
}
}
}
}, {
method: 'GET',
path: '/b/a/b',
path: '/b/c/d',
config: {
tags: ['api']
tags: ['api'],
handler: Helper.defaultHandler,
plugins: {
'hapi-swagger': {
order: 2
}
}
}

@@ -57,57 +80,63 @@ },{

config: {
tags: ['api']
tags: ['api'],
handler: Helper.defaultHandler,
plugins: {
'hapi-swagger': {
order: 3
}
}
}
},{
method: 'POST',
path: '/a',
config: {
tags: ['api'],
handler: Helper.defaultHandler,
plugins: {
'hapi-swagger': {
order: 7
}
}
}
},{
method: 'GET',
path: '/a',
config: {
tags: ['api'],
handler: Helper.defaultHandler,
plugins: {
'hapi-swagger': {
order: 6
}
}
}
}];
lab.test('sort unsort default', (done) => {
lab.test('sort ordered unsorted', (done) => {
let testRoutes = Hoek.clone(routes);
Sort.paths('unsorted', testRoutes);
Helper.createServer({ sortPaths: 'unsorted' }, routes, (err, server) => {
server.inject({ method: 'GET', url: '/swagger.json' }, function (response) {
//console.log(JSON.stringify(testRoutes));
expect(testRoutes[0]).to.deep.equal({
'method':'POST',
'path':'/a',
'config':{
'tags':['api']
}
//console.log(JSON.stringify(response.result.paths['/a']));
expect(Object.keys(response.result.paths['/a'])).to.deep.equal(['get', 'post', 'delete']);
done();
});
});
expect(testRoutes[6]).to.deep.equal({
'method':'DELETE',
'path':'/a',
'config':{
'tags':['api']
}
});
done();
});
lab.test('sort ordered path-method', (done) => {
lab.test('sort path-method', (done) => {
Helper.createServer({ sortPaths: 'path-method' }, routes, (err, server) => {
server.inject({ method: 'GET', url: '/swagger.json' }, function (response) {
let testRoutes = Hoek.clone(routes);
Sort.paths('path-method', testRoutes);
//console.log(JSON.stringify(testRoutes));
expect(testRoutes[4]).to.deep.equal({
'method':'GET',
'path':'/b/a/b',
'config':{
'tags':['api']
}
//console.log(JSON.stringify(Object.keys(response.result.paths['/a'])));
expect(Object.keys(response.result.paths['/a'])).to.deep.equal(['delete', 'get', 'post']);
done();
});
});
expect(testRoutes[0]).to.deep.equal({
'method':'DELETE',
'path':'/a',
'config':{
'tags':['api']
}
});
done();
});
});

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc