Skip to content

Commit

Permalink
add petstore sample and new tests for post
Browse files Browse the repository at this point in the history
  • Loading branch information
Carmine DiMascio committed Mar 20, 2019
1 parent cda1baa commit 6c8af31
Show file tree
Hide file tree
Showing 4 changed files with 213 additions and 94 deletions.
23 changes: 20 additions & 3 deletions index.ts
@@ -1,6 +1,7 @@
import { Application, ErrorRequestHandler, RequestHandler } from 'express';
import * as fs from 'fs';
import * as path from 'path';
const util = require('util');
const jsYaml = require('js-yaml');
import OpenAPIFramework, {
BasePath,
Expand Down Expand Up @@ -33,6 +34,7 @@ export function OpenApiMiddleware(opts: OpenApiMiddlewareOpts) {
throw new Error(`spec could not be read at ${opts.apiSpecPath}`);
const apiDoc = handleYaml(apiContents);
const framework = createFramework({ ...opts, apiDoc });
this.apiDoc = framework.apiDoc;
this.opts = opts;
this.opts.name = this.opts.name || 'express-middleware-openapi';
this.routeMap = buildRouteMap(framework);
Expand All @@ -45,8 +47,18 @@ OpenApiMiddleware.prototype.middleware = function() {
return (req, res, next) => {
const { path, method } = req;
if (path && method) {
const schema = this.routeMap[path][method.toUpperCase()];
console.log('found schema', schema);
// TODO add option to enable undocumented routes to pass through without 404
const documentedRoute = this.routeMap[path];
if (!documentedRoute) return res.status(404).end();

// TODO add option to enable undocumented methods to pass through
const schema = documentedRoute[method.toUpperCase()];
if (!schema) return res.status(415).end();

// TODO coercer and request validator fail on null parameters
if (!schema.parameters) {
schema.parameters = [];
}

// Check if route is in map (throw error - option to ignore)
if (this.opts.enableObjectCoercion) {
Expand All @@ -60,7 +72,12 @@ OpenApiMiddleware.prototype.middleware = function() {

const validationResult = new OpenAPIRequestValidator({
errorTransformer: this.errorTransformer,
...schema,
parameters: schema.parameters || [],
requestBody: schema.requestBody,
// schemas: this.apiDoc.definitions, // v2
componentSchemas: this.apiDoc.components // v3
? this.apiDoc.components.schemas
: undefined,
}).validate(req);

if (validationResult && validationResult.errors.length > 0) {
Expand Down
126 changes: 86 additions & 40 deletions openapi.yaml
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: apiteam@swagger.io
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
10 changes: 8 additions & 2 deletions test/app.ts
Expand Up @@ -28,14 +28,20 @@ app.use(
console.log('---error trans---', a, b);

return a;
}
},
}).middleware()
);
/* GET home page. */
app.get('/v1/pets', function(req, res, next) {
console.log('at /v1/pets here');
res.json({
test: 'hi'
test: 'hi',
});
});

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

Expand Down

0 comments on commit 6c8af31

Please sign in to comment.