forked from Reckon-Limited/serverless_swagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
104 lines (79 loc) · 2.55 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import _ = require('lodash');
import fs = require('fs');
import yaml = require('js-yaml');
import { Serverless, Command } from './serverless';
import { generate, map, bindLog, Definition } from './generator';
class ServerlessSwaggerPlugin {
private provider: string;
private serverless: Serverless;
private commands: {[key: string]: Command};
private hooks: {[key: string]: Function};
private swagger: any
constructor(serverless: Serverless, options: any) {
this.serverless = serverless;
this.provider = 'aws';
this.swagger = this.loadSwagger();
bindLog(this.log)
this.commands = {
"swagger": {
usage: 'Generate aws lamda functions defenition from swagger file',
lifecycleEvents: ['run']
}
};
this.hooks = {
'deploy:compileFunctions': this.run,
'swagger:run': this.generate,
}
}
generate = () => {
this.log('generate');
let definitions = generate(this.swagger.paths, this.namespace, this.outputPath);
this.writeSlsFunctions(definitions)
}
run = () => {
this.log('Mapping Function Definitions');
let definitions = map(this.swagger.paths, this.serverless.service.functions);
this.serverless.service.functions = definitions
console.log(JSON.stringify(definitions));
}
log = (msg: string) => {
this.serverless.cli.log(msg);
}
loadSwagger() {
if (this.hasSwaggerFile()) {
return yaml.safeLoad(fs.readFileSync(this.swaggerFile, 'utf8'));
} else {
return {}
}
}
get swaggerFile() {
let swagger_file = _.get(this.serverless, 'service.custom.swagger_file') || 'swagger.yml'
return `${this.serverless.config.servicePath}/${swagger_file}`;
}
get serverlessFile() {
return `${this.serverless.config.servicePath}/serverless.yml`;
}
get namespace() {
return this.serverless.processedInput.options.output || ''
}
get outputPath() {
if (this.serverless.processedInput.options.output) {
return `${this.serverless.config.servicePath}/${this.serverless.processedInput.options.output}`
} else {
return this.serverless.config.servicePath
}
}
hasSwaggerFile() {
return fs.existsSync(this.swaggerFile);
}
writeSlsFunctions(definitions: {[fn:string]: Definition}) {
let config = this.loadSls()
config.functions = config.functions || {};
_.merge(config.functions, definitions);
fs.writeFileSync('serverless.yml', yaml.safeDump(config));
}
loadSls() {
return yaml.safeLoad(fs.readFileSync(this.serverlessFile, 'utf8'));
}
}
export = ServerlessSwaggerPlugin;