From 9e660a37392b4af47d63caa79957b135dc462220 Mon Sep 17 00:00:00 2001 From: Carmine DiMascio Date: Mon, 21 Oct 2019 20:07:16 -0400 Subject: [PATCH] add type definitions (#72) * add type definitions * add types --- package-lock.json | 15 +- package.json | 3 +- src/framework/openapi.context.ts | 10 +- src/framework/types.ts | 19 +- src/framework/util.ts | 10 +- src/index.ts | 42 +++- src/middlewares/ajv/index.ts | 19 +- src/middlewares/openapi.metadata.ts | 9 +- src/middlewares/openapi.multipart.ts | 33 +-- src/middlewares/openapi.request.validator.ts | 11 +- src/middlewares/openapi.response.validator.ts | 15 +- src/middlewares/util.ts | 29 ++- test/additional.props.spec.ts | 2 +- test/common/myapp.ts | 84 +++++++ test/common/test.yaml | 226 ++++++++++++++++++ tsconfig.json | 10 +- 16 files changed, 466 insertions(+), 71 deletions(-) create mode 100644 test/common/myapp.ts create mode 100644 test/common/test.yaml diff --git a/package-lock.json b/package-lock.json index f40c2c23..e49dfa46 100644 --- a/package-lock.json +++ b/package-lock.json @@ -204,6 +204,15 @@ "@types/express": "*" } }, + "@types/multer": { + "version": "1.3.10", + "resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.3.10.tgz", + "integrity": "sha512-3hECfz+W0ix/LvPanp87mjO3kOyDnJYTpY9y7gdBxXnYXqEcj21pD0lW7KEUFFr8CHrDF5Mhh7o241KLEXDRoQ==", + "dev": true, + "requires": { + "@types/express": "*" + } + }, "@types/node": { "version": "11.13.18", "resolved": "https://registry.npmjs.org/@types/node/-/node-11.13.18.tgz", @@ -5178,9 +5187,9 @@ "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=" }, "typescript": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.5.3.tgz", - "integrity": "sha512-ACzBtm/PhXBDId6a6sDJfroT2pOWt/oOnk4/dElG5G33ZL776N3Y6/6bKZJBFpd+b05F3Ct9qDjMeJmRWtE2/g==", + "version": "3.6.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.6.4.tgz", + "integrity": "sha512-unoCll1+l+YK4i4F8f22TaNVPRHcD9PA3yCuZ8g5e0qGqlVlJ/8FSateOLLSagn+Yg5+ZwuPkL8LFUc0Jcvksg==", "dev": true }, "uglify-js": { diff --git a/package.json b/package.json index 38e365aa..781e0bc1 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "@types/express": "^4.17.0", "@types/mocha": "^5.2.7", "@types/morgan": "^1.7.36", + "@types/multer": "^1.3.10", "@types/node": "^11.13.18", "@types/supertest": "^2.0.8", "body-parser": "^1.19.0", @@ -55,6 +56,6 @@ "supertest": "^4.0.2", "ts-node": "^8.3.0", "tsc": "^1.20150623.0", - "typescript": "^3.5.3" + "typescript": "^3.6.4" } } diff --git a/src/framework/openapi.context.ts b/src/framework/openapi.context.ts index 0b7aea14..741f7d92 100644 --- a/src/framework/openapi.context.ts +++ b/src/framework/openapi.context.ts @@ -1,13 +1,15 @@ import { OpenApiSpecLoader } from './openapi.spec.loader'; import { OpenAPIFrameworkArgs } from './index'; +import { OpenAPIV3 } from './types'; export class OpenApiContext { // TODO cleanup structure (group related functionality) - expressRouteMap = {}; - openApiRouteMap = {}; - routes = []; - apiDoc; + public readonly expressRouteMap = {}; + public readonly openApiRouteMap = {}; + public readonly routes = []; + public readonly apiDoc: OpenAPIV3.Document; private basePaths: Set; + constructor(opts: OpenAPIFrameworkArgs) { const openApiRouteDiscovery = new OpenApiSpecLoader(opts); const { apiDoc, basePaths, routes } = openApiRouteDiscovery.load(); diff --git a/src/framework/types.ts b/src/framework/types.ts index fe8c8551..109ba695 100644 --- a/src/framework/types.ts +++ b/src/framework/types.ts @@ -1,4 +1,4 @@ -import { Request } from 'express'; +import { Request, Response, NextFunction } from 'express'; import { Logger } from 'ts-log'; import BasePath from './base.path'; export { @@ -381,6 +381,12 @@ export interface OpenApiRequest extends Request { openapi; } +export type OpenApiRequestHandler = ( + req: OpenApiRequest, + res: Response, + next: NextFunction, +) => any; + export interface IJsonSchema { id?: string; $schema?: string; @@ -423,6 +429,17 @@ export interface IJsonSchema { not?: IJsonSchema; } +export interface ValidationError { + message?: string; + status: number; + errors: ValidationErrorItem[]; +} + +export interface ValidationErrorItem { + path: string; + message: string; + error_code?: string; +} /* istanbul ignore next */ export class ConsoleDebugAdapterLogger implements Logger { /** diff --git a/src/framework/util.ts b/src/framework/util.ts index 45816f22..403de5ca 100644 --- a/src/framework/util.ts +++ b/src/framework/util.ts @@ -4,22 +4,18 @@ import * as fs from 'fs'; import * as jsYaml from 'js-yaml'; import * as path from 'path'; -export function assertRegExpAndSecurity(framework, tuple) { +export function assertRegExpAndSecurity(framework, tuple): void { if (!Array.isArray(tuple)) { throw new Error( `${framework.name}args.pathSecurity expects an array of tuples`, ); } else if (!(tuple[0] instanceof RegExp)) { throw new Error( - `${ - framework.name - }args.pathSecurity tuples expect the first argument to be a RegExp`, + `${framework.name}args.pathSecurity tuples expect the first argument to be a RegExp`, ); } else if (!Array.isArray(tuple[1])) { throw new Error( - `${ - framework.name - }args.pathSecurity tuples expect the second argument to be a security Array`, + `${framework.name}args.pathSecurity tuples expect the second argument to be a security Array`, ); } } diff --git a/src/index.ts b/src/index.ts index b5a20d1f..5bd14647 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,8 +1,18 @@ import ono from 'ono'; import * as _ from 'lodash'; -import { Application, Request } from 'express'; +import { + Application, + Request, + Response, + NextFunction, + RequestHandler, +} from 'express'; import { OpenApiContext } from './framework/openapi.context'; -import { OpenAPIV3, OpenApiRequest } from './framework/types'; +import { + OpenAPIV3, + OpenApiRequest, + OpenApiRequestHandler, +} from './framework/types'; import * as middlewares from './middlewares'; export type SecurityHandlers = { @@ -52,13 +62,22 @@ export class OpenApiValidator { // install param on routes with paths for (const p of _.uniq(pathParams)) { - app.param(p, (req: OpenApiRequest, res, next, value, name) => { - if (req.openapi.pathParams) { - // override path params - req.params[name] = req.openapi.pathParams[name] || req.params[name]; - } - next(); - }); + app.param( + p, + ( + req: OpenApiRequest, + res: Response, + next: NextFunction, + value: any, + name: string, + ) => { + if (req.openapi.pathParams) { + // override path params + req.params[name] = req.openapi.pathParams[name] || req.params[name]; + } + next(); + }, + ); } const { coerceTypes, unknownFormats } = this.options; @@ -73,9 +92,8 @@ export class OpenApiValidator { }, ); - const requestValidatorMw = (req, res, next) => { - return requestValidator.validate(req, res, next); - }; + const requestValidatorMw: OpenApiRequestHandler = (req, res, next) => + requestValidator.validate(req, res, next); const responseValidator = new middlewares.ResponseValidator( this.context.apiDoc, diff --git a/src/middlewares/ajv/index.ts b/src/middlewares/ajv/index.ts index f7bc2602..b7ba3eaf 100644 --- a/src/middlewares/ajv/index.ts +++ b/src/middlewares/ajv/index.ts @@ -1,16 +1,29 @@ import * as Ajv from 'ajv'; import * as draftSchema from 'ajv/lib/refs/json-schema-draft-04.json'; import { formats } from './formats'; +import { OpenAPIV3 } from '../../framework/types'; const TYPE_JSON = 'application/json'; -export function createRequestAjv(openApiSpec, options: any = {}) { +export function createRequestAjv( + openApiSpec: OpenAPIV3.Document, + options: any = {}, +): Ajv.Ajv { return createAjv(openApiSpec, options); } -export function createResponseAjv(openApiSpec, options: any = {}) { + +export function createResponseAjv( + openApiSpec: OpenAPIV3.Document, + options: any = {}, +): Ajv.Ajv { return createAjv(openApiSpec, options, false); } -function createAjv(openApiSpec, options: any = {}, request: boolean = true) { + +function createAjv( + openApiSpec: OpenAPIV3.Document, + options: any = {}, + request = true, +): Ajv.Ajv { const ajv = new Ajv({ ...options, schemaId: 'auto', diff --git a/src/middlewares/openapi.metadata.ts b/src/middlewares/openapi.metadata.ts index 5f29418d..2b34dc2d 100644 --- a/src/middlewares/openapi.metadata.ts +++ b/src/middlewares/openapi.metadata.ts @@ -1,9 +1,12 @@ import * as pathToRegexp from 'path-to-regexp'; import * as _ from 'lodash'; import { OpenApiContext } from '../framework/openapi.context'; +import { OpenApiRequest, OpenApiRequestHandler } from '../framework/types'; -export function applyOpenApiMetadata(openApiContext: OpenApiContext) { - return (req, res, next) => { +export function applyOpenApiMetadata( + openApiContext: OpenApiContext, +): OpenApiRequestHandler { + return (req, res, next): any => { const matched = lookupRoute(req); if (matched) { @@ -20,7 +23,7 @@ export function applyOpenApiMetadata(openApiContext: OpenApiContext) { -next(); }; - function lookupRoute(req) { + function lookupRoute(req: OpenApiRequest) { const path = req.path; const method = req.method; const routeEntries = Object.entries(openApiContext.expressRouteMap); diff --git a/src/middlewares/openapi.multipart.ts b/src/middlewares/openapi.multipart.ts index 974d8242..a68a5fe8 100644 --- a/src/middlewares/openapi.multipart.ts +++ b/src/middlewares/openapi.multipart.ts @@ -1,8 +1,13 @@ import { OpenApiContext } from '../framework/openapi.context'; import { validationError } from './util'; -import * as multer from 'multer'; +import { Request } from 'express'; +import { OpenApiRequest, OpenApiRequestHandler } from '../framework/types'; +const multer = require('multer'); -export function multipart(openApiContext: OpenApiContext, multerOpts: {} = {}) { +export function multipart( + OpenApiContext: OpenApiContext, + multerOpts: {} = {}, +): OpenApiRequestHandler { const mult = multer(multerOpts); return (req, res, next) => { if (isMultipart(req) && isValidContentType(req)) { @@ -13,20 +18,22 @@ export function multipart(openApiContext: OpenApiContext, multerOpts: {} = {}) { // TODO: // If a form parameter 'file' is defined to take file value, but the user provides a string value instead // req.files will be empty and req.body.file will be populated with a string - // This will incorrectly PASS validation. + // This will incorrectly PASS validation. // Instead, we should return a 400 with an invalid type e.g. file expects a file, but found string. - // - // In order to support this, we likely need to inspect the schema directly to find the type. + // + // In order to support this, we likely need to inspect the schema directly to find the type. // For example, if param with type: 'string', format: 'binary' is defined, we expect to see it in // req.files. If it's not present we should throw a 400 - // + // // This is a bit complex because the schema may be defined inline (easy) or via a $ref (complex) in which // case we must follow the $ref to check the type. if (req.files) { // add files to body - req.files.forEach(f => { - req.body[f.fieldname] = ''; - }); + (req.files).forEach( + (f: Express.Multer.File) => { + req.body[f.fieldname] = ''; + }, + ); } next(); } @@ -37,12 +44,12 @@ export function multipart(openApiContext: OpenApiContext, multerOpts: {} = {}) { }; } -function isValidContentType(req) { +function isValidContentType(req: Request): boolean { const contentType = req.headers['content-type']; return !contentType || contentType.includes('multipart/form-data'); } -function isMultipart(req) { +function isMultipart(req: OpenApiRequest): boolean { return ( req.openapi && req.openapi.schema && @@ -52,10 +59,9 @@ function isMultipart(req) { ); } -function error(req, err) { +function error(req: OpenApiRequest, err: Error) { if (err instanceof multer.MulterError) { // TODO is special handling for MulterErrors needed - console.error(err); return validationError(500, req.path, err.message); } else { // HACK @@ -66,7 +72,6 @@ function error(req, err) { if (missingField) { return validationError(400, req.path, 'multipart file(s) required'); } else { - console.error(err); return validationError(500, req.path, err.message); } } diff --git a/src/middlewares/openapi.request.validator.ts b/src/middlewares/openapi.request.validator.ts index 125535a2..1dcb3050 100644 --- a/src/middlewares/openapi.request.validator.ts +++ b/src/middlewares/openapi.request.validator.ts @@ -5,21 +5,24 @@ import { ajvErrorsToValidatorError, } from './util'; import ono from 'ono'; +import { NextFunction, Response } from 'express'; +import { OpenAPIV3, OpenApiRequest } from '../framework/types'; +import { Ajv } from 'ajv'; const TYPE_JSON = 'application/json'; export class RequestValidator { private _middlewareCache; - private _apiDocs; - private ajv; + private _apiDocs: OpenAPIV3.Document; + private ajv: Ajv; - constructor(apiDocs, options = {}) { + constructor(apiDocs: OpenAPIV3.Document, options = {}) { this._middlewareCache = {}; this._apiDocs = apiDocs; this.ajv = createRequestAjv(apiDocs, options); } - validate(req, res, next) { + public validate(req: OpenApiRequest, res: Response, next: NextFunction): void { if (!req.openapi) { // this path was not found in open api and // this path is not defined under an openapi base path diff --git a/src/middlewares/openapi.response.validator.ts b/src/middlewares/openapi.response.validator.ts index bb8cc287..5a60c32c 100644 --- a/src/middlewares/openapi.response.validator.ts +++ b/src/middlewares/openapi.response.validator.ts @@ -7,15 +7,16 @@ import { ajvErrorsToValidatorError, validationError, } from './util'; +import { OpenAPIV3 } from '../framework/types'; const TYPE_JSON = 'application/json'; export class ResponseValidator { - private ajv; - private spec; + private ajv: Ajv.Ajv; + private spec: OpenAPIV3.Document; private validatorsCache = {}; - constructor(openApiSpec, options: any = {}) { + constructor(openApiSpec: OpenAPIV3.Document, options: any = {}) { this.spec = openApiSpec; this.ajv = createResponseAjv(openApiSpec, options); (mung).onError = (err, req, res, next) => { @@ -23,7 +24,7 @@ export class ResponseValidator { }; } - validate() { + public validate() { return mung.json((body, req: any, res) => { if (req.openapi) { const responses = req.openapi.schema && req.openapi.schema.responses; @@ -36,7 +37,8 @@ export class ResponseValidator { }); } - _getOrBuildValidator(req, responses) { + // TODO public for test only - fix me + public _getOrBuildValidator(req, responses) { if (!req) { // use !req is only possible in unit tests return this.buildValidators(responses); @@ -53,6 +55,7 @@ export class ResponseValidator { return validators; } + // TODO public for test only - fix me _validate({ validators, body, statusCode, path }) { // find the validator for the 'status code' e.g 200, 2XX or 'default' let validator; @@ -124,7 +127,7 @@ export class ResponseValidator { const validators = {}; for (const [name, schema] of Object.entries(schemas)) { - validators[name] = this.ajv.compile(schema); + validators[name] = this.ajv.compile(schema); } return validators; } diff --git a/src/middlewares/util.ts b/src/middlewares/util.ts index 90a33c31..3ee2ee79 100644 --- a/src/middlewares/util.ts +++ b/src/middlewares/util.ts @@ -1,6 +1,9 @@ import ono from 'ono'; +import * as Ajv from 'ajv'; +import { Request } from 'express'; +import { ValidationError } from '../framework/types'; -export function extractContentType(req) { +export function extractContentType(req: Request): string { let contentType = req.headers['content-type'] || 'not_provided'; let end = contentType.indexOf(';'); end = end === -1 ? contentType.length : end; @@ -15,7 +18,7 @@ const _validationError = ( path: string, message: string, errors?: any, // TODO rename - normalize...something else -) => ({ +): ValidationError => ({ status, errors: [ { @@ -26,23 +29,31 @@ const _validationError = ( ], }); -export function validationError(status: number, path: string, message: string) { +export function validationError( + status: number, + path: string, + message: string, +): ValidationError { const err = _validationError(status, path, message); return ono(err, message); } -export function ajvErrorsToValidatorError(status: number, errors) { +export function ajvErrorsToValidatorError( + status: number, + errors: Ajv.ErrorObject[], +): ValidationError { return { status, errors: errors.map(e => { + const params: any = e.params; const required = - e.params && - e.params.missingProperty && - e.dataPath + '.' + e.params.missingProperty; + params && + params.missingProperty && + e.dataPath + '.' + params.missingProperty; const additionalProperty = e.params && - e.params.additionalProperty && - e.dataPath + '.' + e.params.additionalProperty; + params.additionalProperty && + e.dataPath + '.' + params.additionalProperty; const path = required || additionalProperty || e.dataPath || e.schemaPath; return { path, diff --git a/test/additional.props.spec.ts b/test/additional.props.spec.ts index 284a97f5..2cf1e6ee 100644 --- a/test/additional.props.spec.ts +++ b/test/additional.props.spec.ts @@ -1,7 +1,7 @@ +import * as request from 'supertest'; import * as path from 'path'; import * as express from 'express'; import { expect } from 'chai'; -import * as request from 'supertest'; import { createApp } from './common/app'; const packageJson = require('../package.json'); diff --git a/test/common/myapp.ts b/test/common/myapp.ts new file mode 100644 index 00000000..e9fe198e --- /dev/null +++ b/test/common/myapp.ts @@ -0,0 +1,84 @@ +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 OpenApiValidator = require('../../src').OpenApiValidator; +const app = express(); + +app.use(bodyParser.urlencoded()); +app.use(bodyParser.text()); +app.use(bodyParser.json()); +app.use(logger('dev')); +app.use(express.json()); +app.use(express.urlencoded({ extended: false })); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); +const spec = path.join(__dirname, 'openapi.yaml'); +app.use('/spec', express.static(spec)); + +// 1. Install the OpenApiValidator on your express app +new OpenApiValidator({ + apiSpec: './test/common/test.yaml', + // securityHandlers: { + // ApiKeyAuth: (req, scopes, schema) => true, + // }, +}).install(app); + +// 2. Add routes +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' }); +}); + +// 2a. Add a route upload file(s) +app.post('/v1/pets/:id/photos', function(req, res, next) { + // DO something with the file + // files are found in req.files + // non file multipar params are in req.body['my-param'] + console.log(req.files); + + res.json({ + files_metadata: req.files.map(f => ({ + originalname: f.originalname, + encoding: f.encoding, + mimetype: f.mimetype, + // Buffer of file conents + // buffer: f.buffer, + })), + }); +}); + +// 3. Create a custom error handler +app.use((err, req, res, next) => { + // format error + console.error(err, err.stack); + if (!err.status && !err.errors) { + res.status(500).json({ + errors: [ + { + message: err.message, + }, + ], + }); + } else { + res.status(err.status).json({ + message: err.message, + errors: err.errors, + }); + } +}); + +const server = http.createServer(app); +server.listen(3000); +console.log('Listening on port 3000'); + +module.exports = app; diff --git a/test/common/test.yaml b/test/common/test.yaml new file mode 100644 index 00000000..46bc66d4 --- /dev/null +++ b/test/common/test.yaml @@ -0,0 +1,226 @@ +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: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: http://petstore.swagger.io/v1 +paths: + /pets: + get: + 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: maximum number of results to return + required: true + schema: + type: integer + format: int32 + minimum: 5 + - name: test + in: query + description: maximum number of results to return + required: true + schema: + type: string + enum: + - one + - two + responses: + '200': + description: pet response + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + default: + description: unexpected error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + post: + description: Creates a new pet in the store. Duplicates are allowed + operationId: addPet + security: + - ApiKeyAuth: [] + requestBody: + description: Pet to add to the store + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NewPet' + responses: + '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/{id}: + get: + 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: id + in: path + description: ID of pet to fetch + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: pet response + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + default: + description: unexpected error + content: + application/json: + schema: + $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: + application/json: + schema: + $ref: '#/components/schemas/Error' + + /pets/{id}/photos: + post: + description: upload a photo of the pet + operationId: uploadPetPhoto + parameters: + - name: id + in: path + description: ID of pet to fetch + required: true + schema: + type: integer + format: int64 + requestBody: + content: + multipart/form-data: + schema: + # $ref: '#/components/schemas/NewPhoto' + type: object + required: + - file + properties: + file: + description: The photo + type: string + format: binary + required: true + responses: + 201: + description: Created + content: + application/json: + schema: + type: object + properties: + success: + type: boolean + +components: + schemas: + NewPet: + # additionalProperties: true + # additionalProperties: + # type: string + required: + - name + properties: + name: + type: string + tag: + type: string + is_cat: + type: boolean + + Pet: + allOf: + - $ref: '#/components/schemas/NewPet' + - required: + - id + properties: + id: + type: integer + format: int64 + + NewPhoto: + type: object + required: + - file + properties: + file: + description: The photo + type: string + format: binary + + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string + + securitySchemes: + ApiKeyAuth: + type: apiKey + in: header + name: X-API-Key \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index 3a1c4894..5f3f84c7 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,14 +1,18 @@ { "compilerOptions": { "declaration": true, - "target": "es2015", + "target": "es2017", "lib": ["es6", "dom"], "module": "commonjs", "outDir": "dist", "sourceMap": true, "resolveJsonModule": true }, - + "exclude": ["node_modules"], - "include": ["typings.d.ts", "src/**/*.ts", "src/middlewares/modded.express.mung.ts"] + "include": [ + "typings.d.ts", + "src/**/*.ts", + "src/middlewares/modded.express.mung.ts" + ] }