sumomo 0.6.0 → 0.6.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 50c766004cfe7ab6506c86fd593da0ad14ce4d32
4
- data.tar.gz: d4c1e97e89b10d383c5bb0738ab7dec19036ce30
3
+ metadata.gz: 33a1ba0180e0332decba1ba24db31155e9be19df
4
+ data.tar.gz: 225e02aca2d17a355f845eea32f70016deb50ce1
5
5
  SHA512:
6
- metadata.gz: 0f2fac8ee478c2afd773edc2aaeee457934ae63fcdaeae65db95449933da981c5b7fa74fa720aeb812f7f27e3ab6281b05a0546eee7108f4874ad5b30dee1b88
7
- data.tar.gz: f04eb3b716f1ebe9e04afc1226b4766542a0b805dcc661c3639148246483e3f5d7aaaa076f23bfbc697242eff5f191c7b0a81482e1535a40670879f5d9705ce4
6
+ metadata.gz: bfab4dcab755411ad37d1341f925bca4f84cef9b629300ecc1de7371cf7257fc55ae81881500a08cced1a515d1f8b4e4a7091e597798cdb36384a063dd7ac267
7
+ data.tar.gz: d8adb92b5e2d9d51ea5d85d5f3a873f64008ee530d510086adbf99464adc6b83bab443879b05e942b230be7bd747731898201b2f2469eaa8cf06ba0f2f75f61f
data/README.md CHANGED
@@ -71,6 +71,34 @@ end
71
71
  Sumomo::wait_for_stack(name: "mystack", region: "ap-northeast-1")
72
72
  ```
73
73
 
74
+ ## Features
75
+
76
+ You can make apis with this now
77
+
78
+ ```ruby
79
+
80
+ api = make_api "test2.shinonome.astrobunny.net",
81
+ name: "TestGenAPI",
82
+ cert: certificate,
83
+ dns: cloudflare_dns(key: key, email: email) do
84
+
85
+ GET "/page/:pageid", :pageid, <<-SCRIPT
86
+ respond_with ({message: pageid, params: params});
87
+ SCRIPT
88
+
89
+ GET "/best_girl", <<-SCRIPT
90
+ respond_with ({best_girl_is: "Ruby"});
91
+ SCRIPT
92
+
93
+ GET "/*", <<-SCRIPT
94
+ respond_with ({message: "Hello!"});
95
+ SCRIPT
96
+
97
+ end
98
+
99
+ output "APIURL", api
100
+ ```
101
+
74
102
  ## Development
75
103
 
76
104
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
data/lib/sumomo/api.rb CHANGED
@@ -1,235 +1,239 @@
1
1
 
2
2
  module Sumomo
3
- module Stack
4
-
5
-
6
- class APIGenerator
7
- def initialize(&block)
8
- @methods = {}
9
- instance_eval(&block)
10
- end
11
-
12
- def method_missing(name, *args, &block)
13
- "#{name}".split("_").each do |meth|
14
- valid_methods = ["GET", "PUT", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS"]
15
- if valid_methods.include?("#{meth}")
16
- path = args[0]
17
- @methods[path] = {} if !@methods.has_key?(path)
18
-
19
- @methods[path][meth] = { script: args.last, params: args.select{|arg| arg.is_a?(Symbol) && /\A[a-zA-Z\-0-9_]+\Z/.match("#{arg}") } }
20
- else
21
- super
22
- end
23
- end
24
- end
25
-
26
- def generate
27
- result = ""
28
- @methods.each do |path, resource|
29
- resource.each do |method, method_info|
30
-
31
- parameter_list = method_info[:params].join(", ")
32
- parameter_call_list = method_info[:params].map{|parm| "params['#{parm}']"}.join(", ")
33
-
34
- result += <<-SCRIPT
35
-
36
- router.#{method.downcase}('#{path}', prepare(function (event, callback) {
37
-
38
- var retval = {};
39
-
40
- var params = merge(event.queryStringParameters || {}, event.pathParameters || {});
41
-
42
- retval = function (#{parameter_list}) {
43
- #{method_info[:script]}
44
- }( #{ parameter_call_list } );
45
-
46
- var response = {
47
- statusCode: 200,
48
- headers: {
49
- "Content-Type" : "application/json; charset=utf-8"
50
- },
51
- body: JSON.stringify(retval, null, 2)
52
- };
53
-
54
- callback(null, response);
55
- }))
56
-
57
- SCRIPT
58
- end
59
- end
60
- result
61
- end
62
- end
63
-
64
- def make_api(domain_name, name:, script:nil, dns:nil, cert:nil, &block)
65
-
66
- api = make "AWS::ApiGateway::RestApi", name: name do
67
- Name name
68
- end
69
-
70
- script ||= <<-SCRIPT
71
-
72
- 'use strict';
73
- console.log('Loading API');
74
-
75
- var os = require('os');
76
- var http = require('http');
77
- var url = require('url');
78
- var merge = require('utils-merge');
79
- var Router = require('router')
80
-
81
- var router = Router();
82
-
83
- function prepare(handler)
84
- {
85
- return function(request, callback)
86
- {
87
- try
88
- {
89
- request._native_req.pathParameters = request.params
90
- handler(request._native_req, callback);
91
- }
92
- catch (e)
93
- {
94
- console.log(e);
95
- callback(e, {
96
- statusCode: 500,
97
- body: JSON.stringify({message: "Internal Server Error"}, null, 2)
98
- });
99
- }
100
- }
101
- }
102
-
103
- // {{ ROUTES }}
104
-
105
- exports.handler = function(event, context, callback) {
106
-
107
- var request = {
108
- _native_req: event,
109
- url: "https://something" + event.path,
110
- method: event.httpMethod,
111
- params: {}
112
- }
113
-
114
- console.log(request);
115
-
116
- router(request, callback, function(err) {
117
- callback(null, {
118
- statusCode: 404,
119
- body: JSON.stringify({message: "File not found"}, null, 2)
120
- })
121
- });
122
- };
123
- SCRIPT
124
-
125
- apigen = APIGenerator.new(&block);
126
- script.sub!("// {{ ROUTES }}", apigen.generate);
127
-
128
- module_dir = File.join(Gem.datadir("sumomo"), "api_modules")
129
-
130
- files = Dir[File.join(module_dir, "**/*")].select{|x| File.file?(x)}.map do |x|
131
- { name: x.sub(/^#{module_dir}\//, ""), code: File.read(x) }
132
- end
133
-
134
- files += [ {name:"index.js", code:script} ]
135
-
136
- fun = make_lambda(name: "#{name}Lambda#{@version_number}", files:files)
137
-
138
- resource = make "AWS::ApiGateway::Resource", name: "#{name}Resource" do
139
- ParentId api.RootResourceId
140
- PathPart "{proxy+}"
141
- RestApiId api
142
- end
143
-
144
- meth = make "AWS::ApiGateway::Method", name: "#{name}MethodOther" do
145
- RestApiId api
146
- ResourceId resource
147
- HttpMethod "ANY"
148
- AuthorizationType "NONE"
149
- Integration ({
150
- Type: "AWS_PROXY",
151
- IntegrationHttpMethod: "POST",
152
- Uri: call("Fn::Join", "", ["arn:aws:apigateway:" ,ref("AWS::Region") ,":lambda:path", "/2015-03-31/functions/", fun.Arn, "/invocations"])
153
- })
154
- end
155
-
156
- meth2 = make "AWS::ApiGateway::Method", name: "#{name}MethodRoot" do
157
- RestApiId api
158
- ResourceId api.RootResourceId
159
- HttpMethod "ANY"
160
- AuthorizationType "NONE"
161
- Integration ({
162
- Type: "AWS_PROXY",
163
- IntegrationHttpMethod: "POST",
164
- Uri: call("Fn::Join", "", ["arn:aws:apigateway:" ,ref("AWS::Region") ,":lambda:path", "/2015-03-31/functions/", fun.Arn, "/invocations"])
165
- })
166
- end
167
-
168
- make "AWS::Lambda::Permission", name: "#{name}LambdaPermission" do
169
- FunctionName fun.Arn
170
- Action "lambda:InvokeFunction"
171
- Principal "apigateway.amazonaws.com"
172
- end
173
-
174
- deployment = make "AWS::ApiGateway::Deployment", name: "#{name}Deployment#{@version_number}" do
175
- depends_on meth
176
- depends_on meth2
177
- RestApiId api
178
- end
179
-
180
- stage = make "AWS::ApiGateway::Stage", name: "#{name}Stage" do
181
- RestApiId api
182
- DeploymentId deployment
183
- StageName "test"
184
- end
185
-
186
- root_name = /(?<root_name>[^.]+\.[^.]+)$/.match(domain_name)[:root_name]
187
-
188
- cert ||= make "Custom::USEastCertificate", name: "#{name}Certificate" do
189
- DomainName domain_name
190
- end
191
-
192
- domain = make "Custom::APIDomainName", name: "#{name}DomainName" do
193
- DomainName domain_name
194
- CertificateArn cert
195
- end
196
-
197
- make "AWS::ApiGateway::BasePathMapping", name: "#{name}BasePathMapping" do
198
- BasePath "(none)"
199
- DomainName domain
200
- RestApiId api
201
- Stage stage
202
- end
203
-
204
- if dns[:type] == :cloudflare
205
- make "Custom::CloudflareDNSEntry", name: "#{name}CloudFlareEntry" do
206
- Key dns[:key]
207
- Email dns[:email]
208
- Domain root_name
209
- Entry domain_name.sub(/#{root_name}$/, "").chomp(".")
210
- CNAME call("Fn::Join", "", [api, ".execute-api.", ref("AWS::Region"), ".amazonaws.com"])
211
- end
212
- domain_name
213
- elsif dns[:type] == :route53
214
- make "AWS::Route53::RecordSet", name: "#{name}Route53Entry" do
215
- HostedZoneId dns[:hosted_zone]
216
- Name domain_name
217
- Type "CNAME"
218
- end
219
- domain_name
220
- else
221
- call("Fn::Join", "", [api, ".execute-api.", ref("AWS::Region"), ".amazonaws.com"])
222
- end
223
-
224
- end
225
-
226
- def cloudflare_dns(key:, email:)
227
- {type: :cloudflare, key: key, email: email}
228
- end
229
-
230
- def route53_dns(hosted_zone:)
231
- {type: :route53, hosted_zone: hosted_zone}
232
- end
233
-
234
- end
3
+ module Stack
4
+
5
+
6
+ class APIGenerator
7
+ def initialize(&block)
8
+ @methods = {}
9
+ instance_eval(&block)
10
+ end
11
+
12
+ def method_missing(name, *args, &block)
13
+ "#{name}".split("_").each do |meth|
14
+ valid_methods = ["GET", "PUT", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS"]
15
+ if valid_methods.include?("#{meth}")
16
+ path = args[0]
17
+ @methods[path] = {} if !@methods.has_key?(path)
18
+
19
+ @methods[path][meth] = { script: args.last, params: args.select{|arg| arg.is_a?(Symbol) && /\A[a-zA-Z\-0-9_]+\Z/.match("#{arg}") } }
20
+ else
21
+ super
22
+ end
23
+ end
24
+ end
25
+
26
+ def generate
27
+ result = ""
28
+ @methods.each do |path, resource|
29
+ resource.each do |method, method_info|
30
+
31
+ parameter_list = method_info[:params].join(", ")
32
+ parameter_call_list = method_info[:params].map{|parm| "params['#{parm}']"}.join(", ")
33
+
34
+ result += <<-SCRIPT
35
+
36
+ router.#{method.downcase}('#{path}', prepare(function (event, callback) {
37
+
38
+ var retval = {};
39
+
40
+ var params = merge(event.queryStringParameters || {}, event.pathParameters || {});
41
+
42
+ function respond_with(response_object, response_status)
43
+ {
44
+ var response = {
45
+ statusCode: response_status || 200,
46
+ headers: {
47
+ "Content-Type" : "application/json; charset=utf-8"
48
+ },
49
+ body: JSON.stringify(response_object)
50
+ };
51
+
52
+ callback(null, response);
53
+ }
54
+
55
+ var retval = function (#{parameter_list}) {
56
+ #{method_info[:script]}
57
+ }( #{ parameter_call_list } );
58
+
59
+ }));
60
+
61
+ SCRIPT
62
+ end
63
+ end
64
+ result
65
+ end
66
+ end
67
+
68
+ def make_api(domain_name, name:, script:nil, dns:nil, cert:nil, &block)
69
+
70
+ api = make "AWS::ApiGateway::RestApi", name: name do
71
+ Name name
72
+ end
73
+
74
+ script ||= <<-SCRIPT
75
+
76
+ 'use strict';
77
+ console.log('Loading API');
78
+
79
+ var os = require('os');
80
+ var http = require('http');
81
+ var url = require('url');
82
+ var merge = require('utils-merge');
83
+ var Router = require('router')
84
+
85
+ var router = Router();
86
+
87
+ function prepare(handler)
88
+ {
89
+ return function(request, callback)
90
+ {
91
+ try
92
+ {
93
+ request._native_req.pathParameters = request.params
94
+ handler(request._native_req, callback);
95
+ }
96
+ catch (e)
97
+ {
98
+ console.log(e);
99
+ callback(e, {
100
+ statusCode: 500,
101
+ body: JSON.stringify({message: "Internal Server Error"}, null, 2)
102
+ });
103
+ }
104
+ }
105
+ }
106
+
107
+ // {{ ROUTES }}
108
+
109
+ exports.handler = function(event, context, callback) {
110
+
111
+ var request = {
112
+ _native_req: event,
113
+ url: "https://something" + event.path,
114
+ method: event.httpMethod,
115
+ params: {}
116
+ }
117
+
118
+ console.log(request);
119
+
120
+ router(request, callback, function(err) {
121
+ callback(null, {
122
+ statusCode: 404,
123
+ body: JSON.stringify({message: "File not found"}, null, 2)
124
+ })
125
+ });
126
+ };
127
+ SCRIPT
128
+
129
+ apigen = APIGenerator.new(&block);
130
+ script.sub!("// {{ ROUTES }}", apigen.generate);
131
+
132
+ module_dir = File.join(Gem.datadir("sumomo"), "api_modules")
133
+
134
+ files = Dir[File.join(module_dir, "**/*")].select{|x| File.file?(x)}.map do |x|
135
+ { name: x.sub(/^#{module_dir}\//, ""), code: File.read(x) }
136
+ end
137
+
138
+ files += [ {name:"index.js", code:script} ]
139
+
140
+ fun = make_lambda(name: "#{name}Lambda#{@version_number}", files:files)
141
+
142
+ resource = make "AWS::ApiGateway::Resource", name: "#{name}Resource" do
143
+ ParentId api.RootResourceId
144
+ PathPart "{proxy+}"
145
+ RestApiId api
146
+ end
147
+
148
+ meth = make "AWS::ApiGateway::Method", name: "#{name}MethodOther" do
149
+ RestApiId api
150
+ ResourceId resource
151
+ HttpMethod "ANY"
152
+ AuthorizationType "NONE"
153
+ Integration ({
154
+ Type: "AWS_PROXY",
155
+ IntegrationHttpMethod: "POST",
156
+ Uri: call("Fn::Join", "", ["arn:aws:apigateway:" ,ref("AWS::Region") ,":lambda:path", "/2015-03-31/functions/", fun.Arn, "/invocations"])
157
+ })
158
+ end
159
+
160
+ meth2 = make "AWS::ApiGateway::Method", name: "#{name}MethodRoot" do
161
+ RestApiId api
162
+ ResourceId api.RootResourceId
163
+ HttpMethod "ANY"
164
+ AuthorizationType "NONE"
165
+ Integration ({
166
+ Type: "AWS_PROXY",
167
+ IntegrationHttpMethod: "POST",
168
+ Uri: call("Fn::Join", "", ["arn:aws:apigateway:" ,ref("AWS::Region") ,":lambda:path", "/2015-03-31/functions/", fun.Arn, "/invocations"])
169
+ })
170
+ end
171
+
172
+ make "AWS::Lambda::Permission", name: "#{name}LambdaPermission" do
173
+ FunctionName fun.Arn
174
+ Action "lambda:InvokeFunction"
175
+ Principal "apigateway.amazonaws.com"
176
+ end
177
+
178
+ deployment = make "AWS::ApiGateway::Deployment", name: "#{name}Deployment#{@version_number}" do
179
+ depends_on meth
180
+ depends_on meth2
181
+ RestApiId api
182
+ end
183
+
184
+ stage = make "AWS::ApiGateway::Stage", name: "#{name}Stage" do
185
+ RestApiId api
186
+ DeploymentId deployment
187
+ StageName "test"
188
+ end
189
+
190
+ root_name = /(?<root_name>[^.]+\.[^.]+)$/.match(domain_name)[:root_name]
191
+
192
+ cert ||= make "Custom::USEastCertificate", name: "#{name}Certificate" do
193
+ DomainName domain_name
194
+ end
195
+
196
+ domain = make "Custom::APIDomainName", name: "#{name}DomainName" do
197
+ DomainName domain_name
198
+ CertificateArn cert
199
+ end
200
+
201
+ make "AWS::ApiGateway::BasePathMapping", name: "#{name}BasePathMapping" do
202
+ BasePath "(none)"
203
+ DomainName domain
204
+ RestApiId api
205
+ Stage stage
206
+ end
207
+
208
+ if dns[:type] == :cloudflare
209
+ make "Custom::CloudflareDNSEntry", name: "#{name}CloudFlareEntry" do
210
+ Key dns[:key]
211
+ Email dns[:email]
212
+ Domain root_name
213
+ Entry domain_name.sub(/#{root_name}$/, "").chomp(".")
214
+ CNAME call("Fn::Join", "", [api, ".execute-api.", ref("AWS::Region"), ".amazonaws.com"])
215
+ end
216
+ domain_name
217
+ elsif dns[:type] == :route53
218
+ make "AWS::Route53::RecordSet", name: "#{name}Route53Entry" do
219
+ HostedZoneId dns[:hosted_zone]
220
+ Name domain_name
221
+ Type "CNAME"
222
+ end
223
+ domain_name
224
+ else
225
+ call("Fn::Join", "", [api, ".execute-api.", ref("AWS::Region"), ".amazonaws.com"])
226
+ end
227
+
228
+ end
229
+
230
+ def cloudflare_dns(key:, email:)
231
+ {type: :cloudflare, key: key, email: email}
232
+ end
233
+
234
+ def route53_dns(hosted_zone:)
235
+ {type: :route53, hosted_zone: hosted_zone}
236
+ end
237
+
238
+ end
235
239
  end
@@ -1,3 +1,3 @@
1
1
  module Sumomo
2
- VERSION = "0.6.0"
2
+ VERSION = "0.6.1"
3
3
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: sumomo
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.0
4
+ version: 0.6.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - David Siaw
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2017-07-09 00:00:00.000000000 Z
11
+ date: 2017-07-10 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: bundler