whoosh 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,153 @@
1
+ module Whoosh
2
+ # Coercion from request input (JSON values or query strings) and
3
+ # serialization to JSON-safe output. Each coercer returns the value or
4
+ # raises Types::Invalid with a human message.
5
+ module Types
6
+ class Invalid < StandardError; end
7
+
8
+ UUID = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i
9
+ EMAIL = /\A[^@\s]+@[^@\s]+\.[^@\s]+\z/
10
+ INTEGER = /\A[+-]?\d+\z/
11
+ DECIMAL = /\A[+-]?(\d+(\.\d*)?|\.\d+)\z/
12
+ TRUE_VALUES = [true, "true", "1", 1, "yes", "on"].freeze
13
+ FALSE_VALUES = [false, "false", "0", 0, "no", "off"].freeze
14
+
15
+ # Longest string accepted when a field doesn't set max_length.
16
+ DEFAULT_MAX_STRING = 10_000
17
+ INTEGER_RANGE = (-(2**63)..(2**63 - 1))
18
+
19
+ NAMES = %i[string text integer float decimal boolean date datetime time uuid email url
20
+ array object json].freeze
21
+
22
+ module_function
23
+
24
+ def coerce(type, value)
25
+ case type
26
+ when :string, :text then string(value)
27
+ when :integer then integer(value)
28
+ when :float then float(value)
29
+ when :decimal then decimal(value)
30
+ when :boolean then boolean(value)
31
+ when :date then date(value)
32
+ when :datetime, :time then datetime(value)
33
+ when :uuid then pattern(string(value).downcase, UUID, "must be a UUID")
34
+ when :email then pattern(string(value).strip.downcase, EMAIL, "must be an email address")
35
+ when :url then url(value)
36
+ when :json then value
37
+ else raise ArgumentError, "Unknown Whoosh type #{type.inspect}"
38
+ end
39
+ end
40
+
41
+ def string(value)
42
+ case value
43
+ when String then value
44
+ when Symbol, Numeric then value.to_s
45
+ else raise Invalid, "must be a string"
46
+ end
47
+ end
48
+
49
+ def integer(value)
50
+ int = case value
51
+ when Integer then value
52
+ when String then value.strip.match?(INTEGER) ? Integer(value.strip, 10) : nil
53
+ when Float then value == value.floor ? value.to_i : nil
54
+ end
55
+ raise Invalid, "must be a whole number" if int.nil?
56
+ raise Invalid, "is out of range" unless INTEGER_RANGE.cover?(int)
57
+
58
+ int
59
+ end
60
+
61
+ def float(value)
62
+ case value
63
+ when Float then value.finite? ? value : raise(Invalid, "must be a number")
64
+ when Integer then value.to_f
65
+ when String then value.strip.match?(DECIMAL) ? value.to_f : raise(Invalid, "must be a number")
66
+ else raise Invalid, "must be a number"
67
+ end
68
+ end
69
+
70
+ # Exact decimals for money. Accepts strings ("12.50") or numbers.
71
+ def decimal(value)
72
+ case value
73
+ when BigDecimal then value
74
+ when Integer then BigDecimal(value)
75
+ when Float then value.finite? ? BigDecimal(value.to_s) : raise(Invalid, "must be a number")
76
+ when String then value.strip.match?(DECIMAL) ? BigDecimal(value.strip) : raise(Invalid, "must be a number")
77
+ else raise Invalid, "must be a number"
78
+ end
79
+ end
80
+
81
+ def boolean(value)
82
+ v = value.is_a?(String) ? value.strip.downcase : value
83
+ return true if TRUE_VALUES.include?(v)
84
+ return false if FALSE_VALUES.include?(v)
85
+
86
+ raise Invalid, "must be true or false"
87
+ end
88
+
89
+ def date(value)
90
+ return value if value.is_a?(Date) && !value.is_a?(DateTime)
91
+ raise Invalid, "must be a date (YYYY-MM-DD)" unless value.is_a?(String) && value.match?(/\A\d{4}-\d{2}-\d{2}\z/)
92
+
93
+ Date.iso8601(value)
94
+ rescue Date::Error
95
+ raise Invalid, "must be a valid date"
96
+ end
97
+
98
+ def datetime(value)
99
+ return value if value.is_a?(Time)
100
+ raise Invalid, "must be an ISO 8601 timestamp" unless value.is_a?(String)
101
+
102
+ Time.iso8601(value)
103
+ rescue ArgumentError
104
+ raise Invalid, "must be an ISO 8601 timestamp"
105
+ end
106
+
107
+ def url(value)
108
+ str = string(value).strip
109
+ uri = URI.parse(str)
110
+ raise Invalid, "must be an http(s) URL" unless %w[http https].include?(uri.scheme) && uri.host
111
+
112
+ str
113
+ rescue URI::InvalidURIError
114
+ raise Invalid, "must be an http(s) URL"
115
+ end
116
+
117
+ def pattern(value, regex, message)
118
+ raise Invalid, message unless value.match?(regex)
119
+
120
+ value
121
+ end
122
+
123
+ # Output: turn Ruby values into JSON-safe ones.
124
+ def dump(type, value)
125
+ return nil if value.nil?
126
+
127
+ case type
128
+ when :decimal then value.is_a?(BigDecimal) ? value.to_s("F") : decimal(value).to_s("F")
129
+ when :date then value.respond_to?(:to_date) ? value.to_date.iso8601 : value.to_s
130
+ when :datetime, :time then value.respond_to?(:iso8601) ? value.iso8601(3) : value.to_s
131
+ when :integer then value.is_a?(Integer) ? value : integer(value)
132
+ when :float then value.to_f
133
+ when :boolean then !!value
134
+ when :string, :text, :uuid, :email, :url then value.to_s
135
+ when :json then plain(value)
136
+ else value
137
+ end
138
+ end
139
+
140
+ # Deep-convert a value into plain JSON types (for :json fields).
141
+ def plain(value)
142
+ case value
143
+ when Hash then value.each_with_object({}) { |(k, v), h| h[k.to_s] = plain(v) }
144
+ when Array then value.map { |v| plain(v) }
145
+ when String, Integer, Float, true, false, nil then value
146
+ when BigDecimal then value.to_s("F")
147
+ when Symbol then value.to_s
148
+ when Time, Date then value.iso8601
149
+ else value.respond_to?(:as_json) ? value.as_json : value.to_s
150
+ end
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,3 @@
1
+ module Whoosh
2
+ VERSION = "0.1.0"
3
+ end
data/lib/whoosh.rb ADDED
@@ -0,0 +1,72 @@
1
+ require "json"
2
+ require "securerandom"
3
+ require "bigdecimal"
4
+ require "date"
5
+ require "time"
6
+ require "openssl"
7
+ require "uri"
8
+ require "digest"
9
+
10
+ require "whoosh/version"
11
+ require "whoosh/errors"
12
+ require "whoosh/configuration"
13
+ require "whoosh/json"
14
+ require "whoosh/types"
15
+ require "whoosh/schema"
16
+ require "whoosh/router"
17
+ require "whoosh/request"
18
+ require "whoosh/stores/memory"
19
+ require "whoosh/stores/cache"
20
+ require "whoosh/rate_limiter"
21
+ require "whoosh/idempotency"
22
+ require "whoosh/pagination"
23
+ require "whoosh/endpoint"
24
+ require "whoosh/context"
25
+ require "whoosh/openapi"
26
+ require "whoosh/app"
27
+ require "whoosh/lazy_app"
28
+ require "whoosh/api"
29
+
30
+ # Whoosh: an opinionated, secure-by-default JSON API framework for Rack.
31
+ #
32
+ # class OrdersAPI < Whoosh::API
33
+ # version 1
34
+ #
35
+ # get "/orders/:id" do
36
+ # authorize { |user| user.staff? }
37
+ # params { required :id, :integer }
38
+ # returns OrderSchema
39
+ # handle { |p| Order.find(p[:id]) }
40
+ # end
41
+ # end
42
+ #
43
+ # # Rails: mount OrdersAPI => "/api"
44
+ # # config.ru: run OrdersAPI
45
+ module Whoosh
46
+ class << self
47
+ def config
48
+ @config ||= Configuration.new
49
+ end
50
+
51
+ def configure
52
+ yield config
53
+ config
54
+ end
55
+
56
+ # Combine several API classes into one Rack app.
57
+ # run Whoosh.app(OrdersAPI, CustomersAPI)
58
+ # Pass class names as strings in Rails so code reloading works:
59
+ # mount Whoosh.app("OrdersApi", "CustomersApi"), at: "/api"
60
+ def app(*apis, **options)
61
+ apis = apis.flatten
62
+ apis.any? { |a| a.is_a?(String) } ? LazyApp.new(apis, **options) : App.new(apis, **options)
63
+ end
64
+
65
+ # Tests use this to start from a clean slate.
66
+ def reset_config!
67
+ @config = Configuration.new
68
+ end
69
+ end
70
+ end
71
+
72
+ require "whoosh/railtie" if defined?(Rails::Railtie)
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: whoosh
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Johannes Dwi Cahyo Kristanto
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: bigdecimal
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '0'
26
+ description: |
27
+ Whoosh is a small JSON API framework built straight on the Rack spec.
28
+ Endpoints are deny-by-default: every one must declare who may call it,
29
+ what input it accepts and what output it returns, or the app refuses to
30
+ boot. It ships one error envelope, request IDs, body and page-size limits,
31
+ rate limiting, idempotency keys, cursor pagination, CORS and security
32
+ headers, and generates OpenAPI from the same schemas. Its only runtime
33
+ dependency is bigdecimal.
34
+ executables: []
35
+ extensions: []
36
+ extra_rdoc_files: []
37
+ files:
38
+ - CHANGELOG.md
39
+ - LICENSE
40
+ - README.md
41
+ - lib/generators/whoosh/install/install_generator.rb
42
+ - lib/generators/whoosh/install/templates/application_api.rb.tt
43
+ - lib/generators/whoosh/install/templates/initializer.rb.tt
44
+ - lib/generators/whoosh/install/templates/status_api.rb.tt
45
+ - lib/generators/whoosh/install/templates/status_schema.rb.tt
46
+ - lib/whoosh.rb
47
+ - lib/whoosh/api.rb
48
+ - lib/whoosh/app.rb
49
+ - lib/whoosh/configuration.rb
50
+ - lib/whoosh/context.rb
51
+ - lib/whoosh/endpoint.rb
52
+ - lib/whoosh/errors.rb
53
+ - lib/whoosh/idempotency.rb
54
+ - lib/whoosh/json.rb
55
+ - lib/whoosh/lazy_app.rb
56
+ - lib/whoosh/openapi.rb
57
+ - lib/whoosh/pagination.rb
58
+ - lib/whoosh/railtie.rb
59
+ - lib/whoosh/rate_limiter.rb
60
+ - lib/whoosh/request.rb
61
+ - lib/whoosh/router.rb
62
+ - lib/whoosh/schema.rb
63
+ - lib/whoosh/stores/cache.rb
64
+ - lib/whoosh/stores/memory.rb
65
+ - lib/whoosh/types.rb
66
+ - lib/whoosh/version.rb
67
+ homepage: https://github.com/johannesdwicahyo/whoosh
68
+ licenses:
69
+ - MIT
70
+ metadata:
71
+ source_code_uri: https://github.com/johannesdwicahyo/whoosh
72
+ changelog_uri: https://github.com/johannesdwicahyo/whoosh/blob/main/CHANGELOG.md
73
+ rubygems_mfa_required: 'true'
74
+ rdoc_options: []
75
+ require_paths:
76
+ - lib
77
+ required_ruby_version: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '3.2'
82
+ required_rubygems_version: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - ">="
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ requirements: []
88
+ rubygems_version: 4.0.13
89
+ specification_version: 4
90
+ summary: 'An opinionated, secure-by-default JSON API framework for Rack: standalone
91
+ or mounted in Rails, Sinatra, Hanami.'
92
+ test_files: []