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 AddCorsMethods {
|
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, value]) => {
|
15 | if (!value.hasOwnProperty('options')) {
|
16 | let path = {options: cors};
|
17 | Object.assign(value, merge(value, path));
|
18 |
|
19 | } else {
|
20 | Object.assign(value, cors);
|
21 | }
|
22 | });
|
23 |
|
24 | return content;
|
25 | } catch (e) {
|
26 | console.log(e);
|
27 | }
|
28 | return content
|
29 | }
|
30 |
|
31 | readTemplate(serverless) {
|
32 | const templatePath = path.resolve(process.cwd(), 'openapi-integration/path.yml')
|
33 | try {
|
34 | if (fs.existsSync(templatePath)) {
|
35 | serverless.cli.log(
|
36 | `Process custom CORS path template`,
|
37 | 'OpenApi Integration Plugin'
|
38 | );
|
39 | return jsYml.load(fs.readFileSync(templatePath))
|
40 | }
|
41 | } catch (err) {
|
42 | console.error(err)
|
43 | }
|
44 |
|
45 | serverless.cli.log(
|
46 | `Process default CORS path template`,
|
47 | 'OpenApi Integration Plugin'
|
48 | );
|
49 | return jsYml.load(fs.readFileSync(__dirname + '/../../templates/cors/path.yml'));
|
50 | }
|
51 | }
|
52 |
|
53 | module.exports = AddCorsMethods
|