1 | const jsYml = require('js-yaml');
|
2 | const fs = require('fs');
|
3 | const path = require('path');
|
4 | const merge = require('lodash.merge')
|
5 |
|
6 | class AddCorsResponseParameters {
|
7 | invoke(options, content, serverless) {
|
8 | try {
|
9 | if (!options.cors) {
|
10 | return content;
|
11 | }
|
12 |
|
13 | const cors = this.readTemplate(serverless);
|
14 | Object.entries(content.paths).forEach(([key, pathContent]) => {
|
15 | Object.entries(pathContent).forEach(([method, methodContent]) => {
|
16 | if ((methodContent.hasOwnProperty('x-amazon-apigateway-integration'))) {
|
17 | Object.entries(methodContent['x-amazon-apigateway-integration'].responses).forEach(([responses, responseContent]) => {
|
18 | if (!responseContent.hasOwnProperty('responseParameters')) {
|
19 | let params = {responseParameters: cors};
|
20 | Object.assign(responseContent, merge(responseContent, params));
|
21 | } else {
|
22 | Object.assign(responseContent.responseParameters, merge(responseContent.responseParameters, cors));
|
23 | }
|
24 | });
|
25 | }
|
26 | });
|
27 | });
|
28 |
|
29 | return content;
|
30 | } catch (e) {
|
31 | console.log(e);
|
32 | }
|
33 | return content
|
34 | }
|
35 |
|
36 | readTemplate(serverless) {
|
37 | const templatePath = path.resolve(process.cwd(), 'openapi-integration/response-parameters.yml')
|
38 | try {
|
39 | if (fs.existsSync(templatePath)) {
|
40 | serverless.cli.log(
|
41 | `Process custom CORS response-parameters template`,
|
42 | 'OpenApi Integration Plugin'
|
43 | );
|
44 | return jsYml.load(fs.readFileSync(templatePath))
|
45 | }
|
46 | } catch (err) {
|
47 | console.error(err)
|
48 | }
|
49 |
|
50 | serverless.cli.log(
|
51 | `Process default CORS response-parameters template`,
|
52 | 'OpenApi Integration Plugin'
|
53 | );
|
54 | return jsYml.load(fs.readFileSync(__dirname + '/../../templates/cors/response-parameters.yml'));
|
55 | }
|
56 | }
|
57 |
|
58 | module.exports = AddCorsResponseParameters
|