From de5d4d6fc7058766546ba168b9a89e6842435a08 Mon Sep 17 00:00:00 2001 From: Carmine DiMascio Date: Sat, 30 Nov 2019 21:39:58 -0500 Subject: [PATCH] improve example --- example/app.js | 21 ++++-------- example/example.yaml | 21 +++++------- example/pets.js | 41 ++++++++++++++++++++++++ example/pets.json | 20 ------------ example/test.js | 76 -------------------------------------------- 5 files changed, 56 insertions(+), 123 deletions(-) create mode 100644 example/pets.js delete mode 100644 example/pets.json delete mode 100644 example/test.js diff --git a/example/app.js b/example/app.js index 58639e50..15916546 100644 --- a/example/app.js +++ b/example/app.js @@ -4,8 +4,8 @@ const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const logger = require('morgan'); const http = require('http'); -const pets = require('./pets.json'); -const OpenApiValidator = require('express-openapi-validator').OpenApiValidator; +const { pets } = require('./pets'); +const { OpenApiValidator } = require('express-openapi-validator'); const app = express(); // 1. Install bodyParsers for the request types your API will support @@ -20,8 +20,6 @@ app.use(express.static(path.join(__dirname, 'public'))); const spec = path.join(__dirname, 'example.yaml'); app.use('/spec', express.static(spec)); -let id = 3; - // 2. Install the OpenApiValidator on your express app new OpenApiValidator({ apiSpec: './example.yaml', @@ -34,22 +32,17 @@ new OpenApiValidator({ .then(() => { // 3. Add routes app.get('/v1/pets', function(req, res, next) { - res.json(pets); + res.json(pets.findAll(req.query)); }); app.post('/v1/pets', function(req, res, next) { - res.json({ id: id++, ...req.body }); + res.json(pets.add({ ...req.body })); }); app.get('/v1/pets/:id', function(req, res, next) { - const id = req.params.id; - const r = pets.filter(p => p.id === id); - if (id === 99) { - // return a response that does not match the spec - return res.json({ bad_format: 'bad format' }); - } - return r.length > 0 - ? res.json(r) + const pet = pets.findById(req.params.id); + return pet + ? res.json(pet) : res.status(404).json({ message: 'not found', errors: [] }); }); diff --git a/example/example.yaml b/example/example.yaml index ceeb2a75..f010b6fa 100644 --- a/example/example.yaml +++ b/example/example.yaml @@ -60,7 +60,7 @@ paths: $ref: '#/components/schemas/Error' post: - description: Creates a new pet in the store. Duplicates are allowed + description: Creates a new pet in the store. operationId: addPet security: - ApiKeyAuth: [] @@ -70,7 +70,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/NewPet' + $ref: '#/components/schemas/Pet' responses: '200': description: pet response @@ -170,10 +170,15 @@ paths: components: schemas: - NewPet: + Pet: required: + - id - name + - type properties: + id: + readOnly: true + type: number name: type: string tag: @@ -181,16 +186,6 @@ components: type: $ref: '#/components/schemas/PetType' - Pet: - allOf: - - $ref: '#/components/schemas/NewPet' - - required: - - id - properties: - id: - type: integer - format: int64 - PetType: type: string enum: diff --git a/example/pets.js b/example/pets.js new file mode 100644 index 00000000..2c4c11cf --- /dev/null +++ b/example/pets.js @@ -0,0 +1,41 @@ +const data = [ + { + id: 1, + name: 'sparky', + type: 'dog', + tags: ['sweet'], + }, + { + id: 2, + name: 'buzz', + type: 'cat', + tags: ['purrfect'], + }, + { + id: 3, + name: 'max', + type: 'dog', + tags: [], + }, +]; + +class Pets { + constructor() { + this.id = 4; + } + findAll({ type, limit }) { + return data.filter(d => d.type === type).slice(0, limit); + } + + findById(id) { + return data.filter(p => p.id === id)[0]; + } + + add(pet) { + const npet = { id: this.id++, ...pet}; + data.push(npet); + return npet; + } +} + +exports.pets = new Pets(); diff --git a/example/pets.json b/example/pets.json deleted file mode 100644 index 9088bed7..00000000 --- a/example/pets.json +++ /dev/null @@ -1,20 +0,0 @@ -[ - { - "id": 1, - "name": "sparky", - "type": "dog", - "tags": [] - }, - { - "id": 2, - "name": "buzz", - "type": "cat", - "tags": [] - }, - { - "id": 3, - "name": "max", - "type": "dog", - "tags": [] - } -] diff --git a/example/test.js b/example/test.js deleted file mode 100644 index e54e328a..00000000 --- a/example/test.js +++ /dev/null @@ -1,76 +0,0 @@ -const express = require('express'); -const path = require('path'); -const cookieParser = require('cookie-parser'); -const bodyParser = require('body-parser'); -const logger = require('morgan'); -const http = require('http'); -const app = express(); - -// 1. Import the express-openapi-validator library -const OpenApiValidator = require('express-openapi-validator').OpenApiValidator; - -// 2. Set up body parsers for the request body types you expect -// Must be specified prior to endpoints in 5. -app.use(bodyParser.json()); -app.use(bodyParser.text()); -app.use(bodyParser.urlencoded({ extended: false })); - -app.use(logger('dev')); -app.use(cookieParser()); -app.use(express.static(path.join(__dirname, 'public'))); - -// 3. (optionally) Serve the OpenAPI spec -const spec = path.join(__dirname, 'example.yaml'); -app.use('/spec', express.static(spec)); - -// 4. Install the OpenApiValidator onto your express app -new OpenApiValidator({ - apiSpec: './example.yaml', - validateResponses: true, // <-- to validate responses - // securityHandlers: { ... }, // <-- if using security - // unknownFormats: ['my-format'] // <-- to provide custom formats -}) - .install(app) - .then(app => { - // 5. Define routes using Express - app.get('/v1/pets', function(req, res, next) { - res.json([{ id: 1, name: 'max' }, { id: 2, name: 'mini' }]); - }); - - app.post('/v1/pets', function(req, res, next) { - res.json({ name: 'sparky' }); - }); - - app.get('/v1/pets/:id', function(req, res, next) { - res.json({ id: req.params.id, name: 'sparky' }); - }); - - // 5a. Define route(s) to upload file(s) - app.post('/v1/pets/:id/photos', function(req, res, next) { - // files are found in req.files - // non-file multipart params can be found as such: req.body['my-param'] - - res.json({ - files_metadata: req.files.map(f => ({ - originalname: f.originalname, - encoding: f.encoding, - mimetype: f.mimetype, - // Buffer of file conents - buffer: f.buffer, - })), - }); - }); - - // 6. Create an Express error handler - app.use((err, req, res, next) => { - // 7. Customize errors - res.status(err.status || 500).json({ - message: err.message, - errors: err.errors, - }); - }); - }); - -const server = http.createServer(app); -server.listen(3000); -console.log('Listening on port 3000');