Skip to content

Commit

Permalink
add error transform
Browse files Browse the repository at this point in the history
  • Loading branch information
Carmine DiMascio committed Mar 21, 2019
1 parent 2420f49 commit 587061a
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 79 deletions.
31 changes: 7 additions & 24 deletions example/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var http = require('http');
var OpenApiMiddleware = require('./middleware').OpenApiMiddleware;
// var OpenApiMiddleware = require('express-middleware-openapi').OpenApiMiddleware;
var OpenApiMiddleware = require('../').OpenApiMiddleware;
var app = express();

app.use(bodyParser.json());
Expand All @@ -17,45 +16,29 @@ app.use(express.static(path.join(__dirname, 'public')));

new OpenApiMiddleware({
apiSpecPath: './openapi.yaml',
validateApiDoc: true, // is the default
enableObjectCoercion: true, // should be default
errorTransformer: (a, b) => {
console.log('---error trans---', a, b);

return a;
},
validateApiDoc: true, // default
enableObjectCoercion: true, // will be default
}).install(app);

app.get('/v1/pets', function(req, res, next) {
console.log('at /v1/pets here');
res.json({
test: 'hi',
});
res.json([{ id: 1, name: 'max' }, { id: 2, name: 'mini' }]);
});

app.post('/v1/pets', function(req, res, next) {
res.json({
test: 'hi',
});
});

app.get('/v1/vets/:id', function(req, res, next) {
console.log('---- get /pets/:id', req.params);
// here
res.json({
id: req.params.id,
name: 'sparky',
});
});

app.get('/v1/pets/:id', function(req, res, next) {
console.log('---- get /pets/:id', req.params);
// here
res.json({
id: req.params.id,
name: 'sparky',
});
});

var server = http.createServer(app);
server.listen(3000);
console.log('Listening on port 3000');

module.exports = app;
126 changes: 86 additions & 40 deletions example/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,47 @@ openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
description: A sample API that uses a petstore as an example to demonstrate features in the OpenAPI 3.0 specification
termsOfService: http://swagger.io/terms/
contact:
name: Swagger API Team
email: [email protected]
url: http://swagger.io
license:
name: MIT
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
servers:
- url: /v1
- url: http://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
description: |
Returns all pets from the system that the user has access to
Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.
Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.
operationId: findPets
parameters:
- name: tags
in: query
description: tags to filter by
required: false
style: form
schema:
type: array
items:
type: string
- name: limit
in: query
description: How many items to return at one time (max 100)
description: maximum number of results to return
required: true
schema:
type: integer
format: int32
minimum: 5
- name: test
in: query
description: Test
description: maximum number of results to return
required: true
schema:
type: string
Expand All @@ -33,56 +51,81 @@ paths:
- two
responses:
"200":
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
description: pet response
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
type: array
items:
$ref: "#/components/schemas/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
operationId: createPets
tags:
- pets
description: Creates a new pet in the store. Duplicates are allowed
operationId: addPet
requestBody:
description: Pet to add to the store
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/NewPet"
responses:
"201":
description: Null response
"200":
description: pet response
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/pets/{petId}:
/pets/{id}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
description: Returns a user based on a single ID, if the user does not have access to the pet
operationId: find pet by id
parameters:
- name: petId
- name: id
in: path
description: ID of pet to fetch
required: true
description: The id of the pet to retrieve
schema:
type: string
type: integer
format: int64
responses:
"200":
description: Expected response to a valid request
description: pet response
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
$ref: "#/components/schemas/Error"
delete:
description: deletes a single pet based on the ID supplied
operationId: deletePet
parameters:
- name: id
in: path
description: ID of pet to delete
required: true
schema:
type: integer
format: int64
responses:
"204":
description: pet deleted
default:
description: unexpected error
content:
Expand All @@ -91,22 +134,25 @@ paths:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
NewPet:
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
items:
$ref: "#/components/schemas/Pet"

Pet:
allOf:
- $ref: "#/components/schemas/NewPet"
- required:
- id
properties:
id:
type: integer
format: int64

Error:
required:
- code
Expand Down
29 changes: 25 additions & 4 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ import OpenAPIFramework, {
OpenAPIFrameworkConstructorArgs,
} from './fw';
// import OpenAPISchemaValidator from 'openapi-schema-validator';
import OpenAPIRequestValidator from // OpenAPIRequestValidatorError,
'openapi-request-validator';
import OpenAPIRequestValidator from 'openapi-request-validator'; // OpenAPIRequestValidatorError,
import OpenAPIRequestCoercer from 'openapi-request-coercer';
// import { OpenAPIResponseValidatorError } from 'openapi-response-validator';
// import { SecurityHandlers } from 'openapi-security-handler';
Expand All @@ -25,10 +24,16 @@ import {
OpenAPIFrameworkVisitor,
OpenAPIFrameworkAPIContext,
} from './fw/types';
import { ValidationError } from 'ajv';

export interface ErrorResponse {
statusCode: number;
error: any;
}
export interface OpenApiMiddlewareOpts extends OpenAPIFrameworkArgs {
name: string;
apiSpecPath: string;
errorTransform?: (validationResult: any) => ErrorResponse;
}

export function OpenApiMiddleware(opts: OpenApiMiddlewareOpts) {
Expand Down Expand Up @@ -117,8 +122,24 @@ OpenApiMiddleware.prototype.middleware = function() {

if (validationResult && validationResult.errors.length > 0) {
const { errors, status } = validationResult;
console.log('----provide to custom error handler', errors, status);
return res.status(status).json(errors);
const transform =
this.opts.errorTransform ||
(v => ({
statusCode: v.status,
error: { errors: v.errors },
}));

const { statusCode, error } = transform(validationResult);
console.log(
'----provide to custom error handler',
errors,
status,
'-----',
error,
statusCode
);

return res.status(statusCode).json(error);
}
}
next();
Expand Down
5 changes: 3 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "express-middleware-openapi",
"version": "0.1.6-alpha",
"version": "0.1.8-alpha",
"description": "",
"main": "dist/index.js",
"scripts": {
Expand All @@ -11,14 +11,14 @@
"author": "Carmine DiMascio <[email protected]>",
"license": "MIT",
"dependencies": {
"@types/node": "^11.11.3",
"js-yaml": "^3.12.2",
"lodash": "^4.17.11",
"openapi-framework": "^0.22.0",
"openapi-schema-validator": "^3.0.3",
"openapi-types": "1.3.4"
},
"devDependencies": {
"@types/node": "^11.11.3",
"@types/mocha": "^5.2.6",
"@types/supertest": "^2.0.7",
"body-parser": "^1.18.3",
Expand Down
Loading

0 comments on commit 587061a

Please sign in to comment.