UNPKG

16 kBMarkdownView Raw
1<p align="center">
2 <a href="https://npmjs.com/package/serverless-openapi-integration-helper">
3 <img src="https://flat.badgen.net/npm/v/serverless-openapi-integration-helper?icon=npm&label=npm@latest"></a>
4<a href="https://www.npmjs.com/package/serverless-openapi-integration-helper">
5 <img src="https://flat.badgen.net/npm/dt/serverless-openapi-integration-helper?icon=npm"></a>
6 <a href="https://packagephobia.now.sh/result?p=serverless-openapi-integration-helper">
7 <img src="https://flat.badgen.net/packagephobia/install/serverless-openapi-integration-helper"></a>
8 <a href="https://www.npmjs.com/package/serverless-openapi-integration-helper">
9 <img src="https://flat.badgen.net/npm/license/serverless-openapi-integration-helper"></a>
10 <br/>
11</p>
12
13_Feedback is appreciated! If you have an idea for how this plugin/library can be improved (or even just a complaint/criticism) then please open an issue._
14
15# Serverless Plugin: AWS Api Gateway integration helper
16
171. [Overview](#overview)
181. [Installation & Setup](#installation--setup)
191. [Plugin configuration](#plugin-configuration)
201. [Usage](#usage)
211. [Command](#commands)
221. [CORS Generator](#cors-generator)
231. [AUTO-MOCK Generator](#auto-mock-generator)
241. [VALIDATION Generator](#validation-generator)
251. [Configuration Reference](#configuration-reference)
261. [Known Issues](#known-issues)
27 1. [Stage Deployment](#stage-deployment)
28 1. [Variable Resolving](#variable-resolving)
291. [Example](#example)
301. [Approach to a functional test of schema validation](#approach-to-a-functional-test-of-schema-validation)
31
32# Overview
33The plugin provides the functionality to merge [OpenApiSpecification files](https://swagger.io/specification/) (formerly known as swagger) with one or multiple YML files containing the the x-amazon-apigateway extensions.
34There are several use-cases to keep both information separated, e.g. it is needed to deploy different api gateway integrations depending on a stage environment.
35
36When dealing with functional tests you do not want to cover your production environment, but only a mocking response.
37
38**The plugin supports YML based OpenApi3 specification files only**
39
40## Features
41- deploy stage dependent x-amazon-apigateway integrations
42- separate infrastructure (aws) from openapi specification
43- use mock integrations for functional testing
44- auto-generating CORS methods, headers and api gateway mocking response
45- hook into package & deploy lifeCycle and generate combined openApi files on the fly during deployment
46- auto-inject generated openApi file into the Body property of specified API Gateway
47- **[NEW]:** generate mocking responses without specifying x-amazon-apigateway-integration blocks
48- **[NEW]:** generate request-validation blocks
49
50See the **examples** folder for a full working [example](https://github.com/yndlingsfar/serverless-openapi-integration-helper/tree/main/examples)
51
52# Installation & Setup
53
54Run `npm install` in your Serverless project.
55
56`$ npm install --save-dev serverless-openapi-integration-helper`
57
58Add the plugin to your serverless.yml file
59
60```yml
61plugins:
62 - serverless-openapi-integration-helper
63```
64# Plugin configuration
65You can configure the plugin under the key **openApiIntegration**. See
66See [Configuration Reference](#configuration-reference) for a list of available options
67
68The mapping array must be used to configure where the files containing the **x-amazon-apigateway-integration** blocks are located.
69
70```yml
71openApiIntegration:
72 package: true #New feature! Hook into the package & deploy process
73 inputFile: schema.yml
74 mapping:
75 - stage: [dev, prod] #multiple stages
76 path: integrations
77 - stage: test #single stage
78 path: mocks/customer.yml
79```
80
81In the above example all YML files inside the schemas directory will be processed if deploying the dev stage
82```shell
83serverless deploy --stage=dev
84```
85
86To use a different x-amazon-apigateway to perform functional tests (with a mocking response) the file mock/customer.yml is processed if deploying the test stage
87```shell
88serverless deploy --stage=test
89```
90
91# Usage
92With an existing OpenApi Specification file you can easily setup a fully working api gateway.
93
94First create the input file containing the [OpenApiSpecification](https://swagger.io/specification/)
95```yml
96# ./schema.yml
97openapi: 3.0.0
98info:
99 description: User Registration
100 version: 1.0.0
101 title: UserRegistration
102paths:
103 /api/v1/user:
104 post:
105 summary: adds a user
106 requestBody:
107 content:
108 application/json:
109 schema:
110 $ref: '#/components/schemas/Customer'
111 responses:
112 '201':
113 description: user created
114components:
115 schemas:
116 Customer:
117 type: object
118 required:
119 - email_address
120 - password
121 properties:
122 email_address:
123 type: string
124 example: test@example.com
125 password:
126 type: string
127 format: password
128 example: someStrongPassword#
129```
130
131Then create a file containing a **gateway mock integration**
132```yml
133# mocks/customer.yml
134paths:
135 /api/v1/user:
136 post:
137 x-amazon-apigateway-integration:
138 httpMethod: "POST"
139 type: "mock"
140 passthroughBehavior: "when_no_match"
141 requestTemplates:
142 application/json: |
143 {
144 "statusCode" : 204
145 }
146 responses:
147 "2\\d{2}":
148 statusCode: "201"
149```
150
151**create one more file containing the production integration**
152
153```yml
154#integrations/customer.yml
155paths:
156 /api/v1/user:
157 post:
158 x-amazon-apigateway-integration:
159 httpMethod: "POST"
160 uri: https://www.example.com/users
161 type: "http"
162 passthroughBehavior: "when_no_match"
163 responses:
164 "2\\d{2}":
165 statusCode: "201"
166```
167
168Now you can easily create a combined amazon gateway compatible openapi specification file that is automatically injected in your serverless resources
169
170```shell
171#Create OpenApi File containing mocking responses (usable in functional tests) and deploy to ApiGateway
172serverless deploy --stage==test
173```
174
175```shell
176#Create OpenApi File containing the production integration and deploy to ApiGateway
177serverless deploy --stage=prod
178```
179
180The generated output is automatically injected in the **resources.Resources.YOUR_API_GATEWAY.Properties.Body** property
181```yml
182resources:
183 Resources:
184 ApiGatewayRestApi:
185 Type: AWS::ApiGateway::RestApi
186 Properties:
187 ApiKeySourceType: HEADER
188 Body: ~ #autogenerated by plugin
189 Description: "Some Description"
190 FailOnWarnings: false
191 Name: ${opt:stage, self:provider.stage}-some-name
192 EndpointConfiguration:
193 Types:
194 - REGIONAL
195 ApiGatewayDeployment:
196 Type: AWS::ApiGateway::Deployment
197 Properties:
198 RestApiId:
199 Ref: ApiGatewayRestApi
200 StageName: ${opt:stage, self:provider.stage}
201```
202
203# Commands
204
205The generate command can be used independently with
206```yml
207serverless integration merge --stage=dev
208```
209Of course then the API Gateway Body property has to be specified manually
210
211```yml
212resources:
213 Resources:
214 ApiGatewayRestApi:
215 Type: AWS::ApiGateway::RestApi
216 Properties:
217 ApiKeySourceType: HEADER
218 Body: ${file(openapi-integration/api.yml)}
219```
220
221# CORS generator
222
223The plugin can generate full CORS support out of the box.
224```yml
225openApiIntegration:
226 cors: true
227 ...
228```
229
230If enabled, the plugin generates all required OPTIONS methods as well as the required header informations and adds a mocking response to API Gateway.
231You can customize the CORS templates by placing your own files inside a directory **openapi-integration** (in your project root). The following files can be overwritten:
232
233| Filename | Description |
234| ------------- |:-------------:|
235| headers.yml | All headers required for CORS support |
236| integration.yml | Contains the x-amazon-apigateway-integration block |
237| path.yml| OpenApi specification for the OPTIONS method |
238| response-parameters.yml| The response Parameters of the x-amazon-apigateway-integration responses |
239
240See the [EXAMPLES](https://github.com/yndlingsfar/serverless-openapi-integration-helper/tree/main/examples) directory for detailed instructions.
241
242# Auto Mock Generator
243If enabled, the plugin generates mocking responses for all methods that do not have an x-amazon-apigateway-integration block defined.
244It takes the first 2xx response defined in the openApi specification and generates a simple mocking response on the fly
245```yml
246openApiIntegration:
247 autoMock: true
248 ...
249```
250
251When using the autoMock feature, you do not need to specify inputPath mappings, since all endpoints are mocked automatically
252
253```yml
254openApiIntegration:
255 package: true
256 inputFile: schema.yml
257 mapping: ~
258```
259
260# VALIDATION generator
261
262The plugin can generate full CORS support out of the box.
263```yml
264openApiIntegration:
265 validation: true
266 ...
267```
268
269If enabled, the plugin generates the x-amazon-apigateway-request-validators blocks and adds a basic request validation to all methods.
270You can customize the VALIDATION template by placing your own files inside a directory **openapi-integration** (in your project root). The following files can be overwritten:
271
272| Filename | Description |
273| ------------- |:-------------:|
274| request-validator.yml | The x-amazon-apigateway-request-validators block |
275
276See the [EXAMPLES](https://github.com/yndlingsfar/serverless-openapi-integration-helper/tree/main/examples) directory for detailed instructions.
277
278# Configuration Reference
279
280configure the plugin under the key **openApiIntegration**
281
282```yml
283openApiIntegration:
284 inputFile: schema.yml #required
285 package: true #optionl defaults to false
286 inputDirectory: ./ #optional, defaults to ./
287 cors: true #optional, defaults to false
288 autoMock: true #optional, defaults to false
289 validation: true #optional, defaults to false
290 mapping: #optional, can be completely blank if autoMock option is enabled
291 - stage: [dev, prod] #multiple stages
292 path: integrations
293 - stage: test #single stage
294 path: mocks/customer.yml
295 outputFile: api.yml #optional, defaults to api.yml
296 outputDirectory: openapi-integration #optional, defaults to ./openapi-integration
297```
298
299# Known Issues
300
301## Stage deployment
302When using serverless framework only to deploy your aws resources **without having any lambda functions or triggers**, the AWS Gateway deploymemt does not behave as expected.
303Any deployment to an existing stage will be ignored, since CloudFormation does not redeploy a stage if the DeploymentIdentifier has not changed.
304
305The plugin [serverless-random-gateway-deployment-id](https://www.npmjs.com/package/serverless-random-gateway-deployment-id) solves this problem by adding a random id to the deployment-name and all references to it on every deploy
306
307See the **examples** folder for a full working [example](https://github.com/yndlingsfar/serverless-openapi-integration-helper/tree/main/examples)
308
309## Variable Resolving
310Serverless variables inside the openapi integration files are not resolved correctly when using the package & deploy hooks. This problem can be solved by using the api gateway STAGE VARIABLES.
311
312See the **examples** folder for a full working [example](https://github.com/yndlingsfar/serverless-openapi-integration-helper/tree/main/examples)
313
314# Example
315```yml
316service:
317 name: user-registration
318
319provider:
320 name: aws
321 stage: dev
322 region: eu-central-1
323
324plugins:
325 - serverless-openapi-integration-helper
326
327openApiIntegration:
328 inputFile: schema.yml
329 package: true
330 mapping:
331 - path: integrations
332 stage: [dev, prod]
333 - path: mocks/customer.yml
334 stage: test
335
336functions:
337
338resources:
339 Resources:
340 ApiGatewayRestApi:
341 Type: AWS::ApiGateway::RestApi
342 Properties:
343 ApiKeySourceType: HEADER
344 Body: ~
345 Description: "Some Description"
346 FailOnWarnings: false
347 Name: ${opt:stage, self:provider.stage}-some-name
348 EndpointConfiguration:
349 Types:
350 - REGIONAL
351 ApiGatewayDeployment:
352 Type: AWS::ApiGateway::Deployment
353 Properties:
354 RestApiId:
355 Ref: ApiGatewayRestApi
356 StageName: ${opt:stage, self:provider.stage}
357```
358
359```
360serverless deploy --stage=test
361```
362
363```
364serverless deploy --stage=prod
365```
366
367# Approach to a functional test of schema validation
368The plugin works well in combination with the [serverless-plugin-test-helper](https://www.npmjs.com/package/serverless-plugin-test-helper) to automate tests against the deployed api gateway
369
370## Install The plugin test helper package
371
372```shell
373npm install --save-dev serverless-plugin-test-helper
374```
375
376add the plugin as a plugin dependency in your serverless configuration file and configure the plugin according to the [Readme](https://www.npmjs.com/package/serverless-plugin-test-helper)
377```yml
378#./serveless.yml
379plugins:
380 - serverless-plugin-test-helper
381 - serverless-openapi-integration-helper
382
383[...]
384
385resources:
386 Outputs:
387 GatewayUrl: # This is the key that will be used in the generated outputs file
388 Description: This is a helper for functional tests
389 Value: !Join
390 - ''
391 - - 'https://'
392 - !Ref ApiGatewayRestApi
393 - '.execute-api.'
394 - ${opt:region, self:provider.region}
395 - '.amazonaws.com/'
396 - ${opt:stage, self:provider.stage}
397
398 Resources:
399 ApiGatewayRestApi:
400 Type: AWS::ApiGateway::RestApi
401 Properties:
402 ApiKeySourceType: HEADER
403 Body: ~
404 Description: User Registration (${opt:stage, self:provider.stage})
405 FailOnWarnings: false
406 Name: ${opt:stage, self:provider.stage}-gateway
407 EndpointConfiguration:
408 Types:
409 - REGIONAL
410 ApiGatewayDeployment:
411 Type: AWS::ApiGateway::Deployment
412 Properties:
413 RestApiId:
414 Ref: ApiGatewayRestApi
415 StageName: ${opt:stage, self:provider.stage}
416```
417
418## Testing the schema validation
419Add a functional test (e.g. with jest)
420
421```javascript
422//tests/registration.js
423import {getOutput} from 'serverless-plugin-test-helper';
424import axios from 'axios';
425
426axios.defaults.adapter = require('axios/lib/adapters/http'); //Todo
427
428const URL = getOutput('GatewayUrl');
429test('request validation on registration', async () => {
430 expect.assertions(1);
431 const {status} = await axios.post(URL + '/api/v1/user',
432 {
433 "email_address": "test@example.com",
434 "password": "someStrongPassword#"
435 },
436 {
437 headers: {
438 'Content-Type': 'application/json',
439 }
440 });
441 expect(status).toEqual(201);
442});
443
444test('request validation on registration (invalid request)', async () => {
445 expect.assertions(1);
446 try {
447 await axios.post(URL + '/api/v1/user',
448 {
449 "email": "test@example.com"
450 },
451 {
452 headers: {
453 'Content-Type': 'application/json',
454 }
455 });
456 } catch (e) {
457 expect(e.response).toMatchObject({
458 statusText: 'Bad Request',
459 status: 400
460 });
461 }
462});
463```
464Then perform the functional test
465```shell
466serverless deploy --stage=test
467npm test
468serverless remove --stage=test
469```
470
471The command will
472- merge the openapi specification file with the MOCK integration configured before
473- deploy to API Gateway in an isolated TEST infrastructure environment (your other environments will not be affected since we are deploying to a separated gateway)
474- perform the test and verify that schema validation is correct
475- remove all TEST resources if test succeeded
476
477See the **examples** folder for a full working [example](https://github.com/yndlingsfar/serverless-openapi-integration-helper/tree/main/examples)