UNPKG

2.48 kBJavaScriptView Raw
1const jsYml = require('js-yaml');
2const fs = require('fs');
3const path = require('path');
4const merge = require('lodash.merge')
5
6class AddAutoMockIntegration {
7 invoke(options, content, serverless) {
8 try {
9 if (!options.autoMock) {
10 return content;
11 }
12
13 Object.entries(content.paths).forEach(([key, pathContent]) => {
14 Object.entries(pathContent).forEach(([method, methodContent]) => {
15 let mock = this.readTemplate(serverless);
16 const availableMethodResponses = ['200', '201', '202', '203', '204', '205', '206', '207', '208', '226']
17 let takenResponse = null
18
19 if (!methodContent.hasOwnProperty('x-amazon-apigateway-integration')) {
20 Object.entries(methodContent.responses).forEach(([response, responseContent]) => {
21 if (takenResponse === null && availableMethodResponses.includes(response)) {
22 takenResponse = response;
23 }
24 }
25 );
26
27 if (takenResponse === null) {
28 serverless.cli.log(
29 `AUTO-MOCK is unable to generate a mock for ${key}:${method} because at least one specified 2xx response code is required`,
30 'OpenApi Integration Plugin',
31 {color: 'red', bold: true}
32 )
33 } else {
34 serverless.cli.log(
35 `Add AUTO-MOCK for ${key}:${method} with response code ${takenResponse}`,
36 'OpenApi Integration Plugin'
37 )
38 }
39
40 const variableRegex = new RegExp('STATUS_CODE', 'g')
41 mock = JSON.parse(JSON.stringify(mock).replace(variableRegex, takenResponse));
42 Object.assign(methodContent, merge(methodContent, mock));
43 }
44 });
45 });
46
47 return content;
48 } catch (e) {
49 console.log(e);
50 }
51 return content
52 }
53
54 readTemplate(serverless) {
55 return jsYml.load(fs.readFileSync(__dirname + '/../../templates/mock/auto-mock.yml'));
56 }
57}
58
59module.exports = AddAutoMockIntegration