UNPKG

1.68 kBJavaScriptView Raw
1const jsYml = require('js-yaml');
2const fs = require('fs');
3const path = require('path');
4const merge = require('lodash.merge')
5
6class AddCorsIntegrations {
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 ((method.toLowerCase() === 'options') && (!methodContent.hasOwnProperty('x-amazon-apigateway-integration'))) {
17 Object.assign(methodContent, merge(methodContent, cors));
18 }
19 });
20 });
21
22 return content;
23 } catch (e) {
24 console.log(e);
25 }
26 return content
27 }
28
29 readTemplate(serverless) {
30 const templatePath = path.resolve(process.cwd(), 'openapi-integration/integration.yml')
31 try {
32 if (fs.existsSync(templatePath)) {
33 serverless.cli.log(
34 `Process custom CORS integration template`,
35 'OpenApi Integration Plugin'
36 );
37 return jsYml.load(fs.readFileSync(templatePath))
38 }
39 } catch (err) {
40 console.error(err)
41 }
42
43 serverless.cli.log(
44 `Process default CORS integration template`,
45 'OpenApi Integration Plugin'
46 );
47 return jsYml.load(fs.readFileSync(__dirname + '/../../templates/cors/integration.yml'));
48 }
49}
50
51module.exports = AddCorsIntegrations