From 6c8af311f683254bc910515437ea3827a5b3e0c0 Mon Sep 17 00:00:00 2001 From: Carmine DiMascio Date: Tue, 19 Mar 2019 21:54:28 -0400 Subject: [PATCH] add petstore sample and new tests for post --- index.ts | 23 ++++++- openapi.yaml | 126 +++++++++++++++++++++++++------------ test/app.ts | 10 ++- test/routes.spec.ts | 148 +++++++++++++++++++++++++++++--------------- 4 files changed, 213 insertions(+), 94 deletions(-) diff --git a/index.ts b/index.ts index cba65ebd..4f16100a 100644 --- a/index.ts +++ b/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, @@ -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); @@ -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) { @@ -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) { diff --git a/openapi.yaml b/openapi.yaml index 9086c1ef..a72f7be4 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -2,21 +2,39 @@ 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 @@ -24,7 +42,7 @@ paths: minimum: 5 - name: test in: query - description: Test + description: maximum number of results to return required: true schema: type: string @@ -33,16 +51,13 @@ 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: @@ -50,39 +65,67 @@ paths: 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: @@ -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 diff --git a/test/app.ts b/test/app.ts index bde8c253..6b2b8b91 100644 --- a/test/app.ts +++ b/test/app.ts @@ -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', }); }); diff --git a/test/routes.spec.ts b/test/routes.spec.ts index e60e5683..d547bb5e 100644 --- a/test/routes.spec.ts +++ b/test/routes.spec.ts @@ -14,56 +14,106 @@ describe(packageJson.name, () => { expect('a').to.equal('a'); }); - it('should throw 400 on missing required query parameter', async () => - request(app) - .get('/v1/pets') - .set('Accept', 'application/json') - .expect('Content-Type', /json/) - .expect(400) - .then(r => { - const e = r.body; - expect(e).to.have.length(2); - expect(e[0].path).to.equal('limit'); - expect(e[1].path).to.equal('test'); - })); + describe('GET /pets', () => { + it('should throw 400 on missing required query parameter', async () => + request(app) + .get('/v1/pets') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(400) + .then(r => { + const e = r.body; + expect(e).to.have.length(2); + expect(e[0].path).to.equal('limit'); + expect(e[1].path).to.equal('test'); + })); - it('should respond with json on proper get call', async () => - request(app) - .get('/v1/pets') - .query({ - test: 'one', - limit: 10 - }) - .set('Accept', 'application/json') - .expect('Content-Type', /json/) - .expect(200)); + it('should respond with json on proper get call', async () => + request(app) + .get('/v1/pets') + .query({ + test: 'one', + limit: 10, + }) + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200)); - it('should return 200 with unknown query parameter', async () => - request(app) - .get('/v1/pets') - .query({ - test: 'one', - limit: 10, - bad_param: 'test' - }) - .set('Accept', 'application/json') - .expect('Content-Type', /json/) - .expect(200)); + it('should return 200 with unknown query parameter', async () => + request(app) + .get('/v1/pets') + .query({ + test: 'one', + limit: 10, + bad_param: 'test', + }) + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200)); - it('should return 400 when improper range specified', async () => - request(app) - .get('/v1/pets') - .query({ - test: 'one', - limit: 2 - }) - .set('Accept', 'application/json') - .expect('Content-Type', /json/) - .expect(400) - .then(r => { - const e = r.body; - expect(e).to.have.length(1); - expect(e[0].path).to.equal('limit'); - expect(e[0].message).to.equal('should be >= 5'); - })); + it('should return 400 when improper range specified', async () => + request(app) + .get('/v1/pets') + .query({ + test: 'one', + limit: 2, + }) + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(400) + .then(r => { + const e = r.body; + expect(e).to.have.length(1); + expect(e[0].path).to.equal('limit'); + expect(e[0].message).to.equal('should be >= 5'); + })); + }); + + describe('POST /pets', () => { + it('should return 400 if required body is missing', async () => + request(app) + .post('/v1/pets') + .set({ + 'content-type': 'application/json', + }) + .expect(400) + .then(r => { + const e = r.body; + expect(e[0].message).to.equal("should have required property 'name'"); + })); + + it('should return 400 if required "name" property is missing', async () => + request(app) + .post('/v1/pets') + .send({}) + .expect(400) + .then(r => { + const e = r.body; + expect(e[0].message).to.equal("should have required property 'name'"); + })); + + it('should return 200 when post props are met', async () => + request(app) + .post('/v1/pets') + .send({ + name: 'test', + }) + .expect(200) + .then(r => { + console.log(r.body); + })); + }); + + describe('POST /unknown-routes', () => { + it('should return 200 when post props are met', async () => + request(app) + .post('/v1/unknown-route') + .send({ + name: 'test', + }) + .expect(404) + .then(r => { + console.log(r.body); + })); + }); });