apicraft-rails 0.5.0.beta1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/README.md +257 -0
- data/apicraft-rails.gemspec +41 -0
- data/bin/console +15 -0
- data/bin/setup +8 -0
- data/lib/apicraft/concerns/cacheable.rb +30 -0
- data/lib/apicraft/concerns.rb +8 -0
- data/lib/apicraft/config.rb +76 -0
- data/lib/apicraft/constants.rb +28 -0
- data/lib/apicraft/errors.rb +11 -0
- data/lib/apicraft/loader.rb +50 -0
- data/lib/apicraft/middlewares/introspector.rb +42 -0
- data/lib/apicraft/middlewares/mocker.rb +69 -0
- data/lib/apicraft/middlewares.rb +9 -0
- data/lib/apicraft/mocker/all_of.rb +27 -0
- data/lib/apicraft/mocker/any_of.rb +31 -0
- data/lib/apicraft/mocker/array.rb +33 -0
- data/lib/apicraft/mocker/base.rb +16 -0
- data/lib/apicraft/mocker/boolean.rb +12 -0
- data/lib/apicraft/mocker/integer.rb +12 -0
- data/lib/apicraft/mocker/number.rb +43 -0
- data/lib/apicraft/mocker/object.rb +35 -0
- data/lib/apicraft/mocker/one_of.rb +14 -0
- data/lib/apicraft/mocker/string.rb +44 -0
- data/lib/apicraft/mocker.rb +41 -0
- data/lib/apicraft/openapi/contract.rb +50 -0
- data/lib/apicraft/openapi/operation.rb +36 -0
- data/lib/apicraft/openapi/response.rb +47 -0
- data/lib/apicraft/openapi.rb +10 -0
- data/lib/apicraft/railtie.rb +11 -0
- data/lib/apicraft/version.rb +6 -0
- data/lib/apicraft/web/actions.rb +60 -0
- data/lib/apicraft/web/app.rb +65 -0
- data/lib/apicraft/web/router.rb +62 -0
- data/lib/apicraft/web.rb +10 -0
- data/lib/apicraft-rails.rb +37 -0
- data/web/views/index.html +15 -0
- data/web/views/redoc.erb +85 -0
- data/web/views/swaggerdoc.erb +38 -0
- metadata +187 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 847b284dc12a51e2364740eef912f4238c771a7e9d143fa7ea63090afca69e03
|
4
|
+
data.tar.gz: 1a2c2c667280415035ca7af8a95de9dbadc2859ee932a65c4890b30f37208821
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 588307957dd26f89f9f661ab36f55ea33d47fd601e4f563481e32a29a526734c8daa8e2c51bd2741ace545a52079549587f7cc720f9c1f84f7187533cf4dd294
|
7
|
+
data.tar.gz: 4a65d260b4f9124733cb1aeb1d069598f0f87ad6e4a6322c0bfa2ba842fdbcca2de626e23fb6dfbcae0340eb8ddb51a4400867e544a278c4fa2dd12c237bfe4b
|
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,84 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
6
|
+
|
7
|
+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
8
|
+
|
9
|
+
## Our Standards
|
10
|
+
|
11
|
+
Examples of behavior that contributes to a positive environment for our community include:
|
12
|
+
|
13
|
+
* Demonstrating empathy and kindness toward other people
|
14
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
15
|
+
* Giving and gracefully accepting constructive feedback
|
16
|
+
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
17
|
+
* Focusing on what is best not just for us as individuals, but for the overall community
|
18
|
+
|
19
|
+
Examples of unacceptable behavior include:
|
20
|
+
|
21
|
+
* The use of sexualized language or imagery, and sexual attention or
|
22
|
+
advances of any kind
|
23
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
24
|
+
* Public or private harassment
|
25
|
+
* Publishing others' private information, such as a physical or email
|
26
|
+
address, without their explicit permission
|
27
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
28
|
+
professional setting
|
29
|
+
|
30
|
+
## Enforcement Responsibilities
|
31
|
+
|
32
|
+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
33
|
+
|
34
|
+
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
35
|
+
|
36
|
+
## Scope
|
37
|
+
|
38
|
+
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
39
|
+
|
40
|
+
## Enforcement
|
41
|
+
|
42
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at abhisheksarka@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
|
43
|
+
|
44
|
+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
45
|
+
|
46
|
+
## Enforcement Guidelines
|
47
|
+
|
48
|
+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
49
|
+
|
50
|
+
### 1. Correction
|
51
|
+
|
52
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
53
|
+
|
54
|
+
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
55
|
+
|
56
|
+
### 2. Warning
|
57
|
+
|
58
|
+
**Community Impact**: A violation through a single incident or series of actions.
|
59
|
+
|
60
|
+
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
61
|
+
|
62
|
+
### 3. Temporary Ban
|
63
|
+
|
64
|
+
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
65
|
+
|
66
|
+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
67
|
+
|
68
|
+
### 4. Permanent Ban
|
69
|
+
|
70
|
+
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
71
|
+
|
72
|
+
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
73
|
+
|
74
|
+
## Attribution
|
75
|
+
|
76
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
|
77
|
+
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
78
|
+
|
79
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
80
|
+
|
81
|
+
[homepage]: https://www.contributor-covenant.org
|
82
|
+
|
83
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
84
|
+
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
|
data/README.md
ADDED
@@ -0,0 +1,257 @@
|
|
1
|
+
# APICraft Rails (Beta)
|
2
|
+
[![Build](https://github.com/apicraft-dev/apicraft-rails/actions/workflows/build.yml/badge.svg)](https://github.com/apicraft-dev/apicraft-rails/actions/workflows/build.yml)
|
3
|
+
|
4
|
+
🚀 Accelerates your development by 2-3x with an API Design First approach. Seamlessly integrates with your Rails application server — no fancy tooling or expenses required.
|
5
|
+
|
6
|
+
![APICraft Rails Logo](assets/apicraft_rails.png)
|
7
|
+
|
8
|
+
## ✨ Features
|
9
|
+
- 🧑💻️ **Dynamic Mock Data Generation** - Detects the specifications and instantly mounts working routes with mock responses. No extra configuration required.
|
10
|
+
|
11
|
+
- ⚙️ **Customizable Mock Responses** - Tailor mock responses to simulate different scenarios and edge cases, helping your team prepare for real-world conditions right from the start.
|
12
|
+
|
13
|
+
- 🔍 **API Introspections** - Introspect API schemas without needing to dig into the docs everytime.
|
14
|
+
|
15
|
+
- 📺 **Documentation Out of the Box** - Documentation using `SwaggerDoc` and `Redoc` both.
|
16
|
+
|
17
|
+
- 🗂 **Easy Contracts Management** - Management of `openapi` specifications from within `app/contracts` directory. No new syntax, just plain old `openapi` standard with `.json` or `.yaml` formats
|
18
|
+
|
19
|
+
- 🔜 **Request Validations** - Automatic request validations (coming soon)
|
20
|
+
|
21
|
+
|
22
|
+
## 🪄 Works Like Magic
|
23
|
+
|
24
|
+
Once you’ve installed the gem, getting started is a breeze. Simply create your OpenAPI contracts within the `app/contracts` directory of your Rails application. You’re free to organize this directory in a way that aligns with your project's standards and preferences. That’s it—your APIs will be up and running with mock responses, ready for development without any additional setup. It's as effortless as it sounds!
|
25
|
+
|
26
|
+
## 🕊 API Design First Philosophy
|
27
|
+
|
28
|
+
![APICraft Rails Logo](assets/api_first_workflow.jpg)
|
29
|
+
|
30
|
+
The API Design First philosophy is at the heart of APICraft Rails, and it’s a game-changer for development speed and efficiency:
|
31
|
+
|
32
|
+
- 🔄 **Parallel Development:** By designing your APIs upfront, both frontend and backend teams can work simultaneously using mock APIs, eliminating bottlenecks and reducing wait times.
|
33
|
+
|
34
|
+
- 📜 **Clear Contracts:** OpenAPI contracts serve as a single source of truth, ensuring that all teams are aligned on how the API should behave, reducing misunderstandings and rework.
|
35
|
+
|
36
|
+
- ⚙️ **Early Testing:** Mock APIs allow QA to begin testing earlier in the development cycle, catching issues before they become costly to fix.
|
37
|
+
|
38
|
+
- 🔍 **Faster Feedback Loop:** Immediate feedback on API design helps you iterate quickly, refining your API based on real usage scenarios, ultimately leading to a more robust product.
|
39
|
+
|
40
|
+
- 🚀 **Reduced Integration Time:** With consistent API contracts in place, integrating various components becomes smoother and faster, cutting down on the time required to bring everything together.
|
41
|
+
|
42
|
+
By adopting an API Design First approach with APICraft Rails, you can accelerate your development process by 2-3x, delivering high-quality APIs faster and with fewer headaches.
|
43
|
+
|
44
|
+
|
45
|
+
## Installation
|
46
|
+
|
47
|
+
Add this line to your application's Gemfile:
|
48
|
+
|
49
|
+
```ruby
|
50
|
+
gem 'apicraft-rails', '~> 0.5.0.beta1'
|
51
|
+
```
|
52
|
+
|
53
|
+
And then execute:
|
54
|
+
|
55
|
+
$ bundle install
|
56
|
+
|
57
|
+
After the installation in your rails project, you can start adding contracts in the `app/contracts` directory. This can have any internal directory structure based on your API versions, standards, etc.
|
58
|
+
|
59
|
+
Add the following into your Rails application, via the `config/application.rb`
|
60
|
+
|
61
|
+
```ruby
|
62
|
+
# config/application.rb
|
63
|
+
module App
|
64
|
+
class Application < Rails::Application
|
65
|
+
# Rest of the configuration...
|
66
|
+
|
67
|
+
config.middleware.use Apicraft::Middlewares::Mocker
|
68
|
+
config.middleware.use Apicraft::Middlewares::Introspector
|
69
|
+
|
70
|
+
Apicraft.configure do |config|
|
71
|
+
config.contracts_path = Rails.root.join("app/contracts")
|
72
|
+
end
|
73
|
+
end
|
74
|
+
end
|
75
|
+
```
|
76
|
+
|
77
|
+
Now every API in the specification has a functional version. For any path (from the contracts), APICraft serves a mock response when `Apicraft-Mock: true` is passed in the headers otherwise, it forwards the request to your application as usual.
|
78
|
+
|
79
|
+
## Usage
|
80
|
+
|
81
|
+
Add your specification files to the `app/contracts` directory in your Rails project. You can also configure this directory to be something else.
|
82
|
+
```
|
83
|
+
my_rails_app/
|
84
|
+
├── app/
|
85
|
+
│ ├── controllers/
|
86
|
+
│ │ ├── application_controller.rb
|
87
|
+
│ │ └── users_controller.rb
|
88
|
+
│ ├── contracts/
|
89
|
+
│ │ ├── users_contract.yaml
|
90
|
+
│ │ └── orders_contract.yaml
|
91
|
+
│ ├── models/
|
92
|
+
│ │ ├── user.rb
|
93
|
+
│ │ └── order.rb
|
94
|
+
```
|
95
|
+
### 🥷 Working with Mock APIs
|
96
|
+
**APICraft** dynamically generates mock APIs by interpreting contract specifications on the fly. You can request the mock response by passing `Apicraft-Mock: true` in the headers.
|
97
|
+
|
98
|
+
`https://yoursite.com/api/orders`
|
99
|
+
```
|
100
|
+
headers: {
|
101
|
+
Apicraft-Mock: true
|
102
|
+
}
|
103
|
+
```
|
104
|
+
```json
|
105
|
+
[
|
106
|
+
{
|
107
|
+
"id": 66,
|
108
|
+
"name": "tempora",
|
109
|
+
"description": "error"
|
110
|
+
},
|
111
|
+
{
|
112
|
+
"id": 41,
|
113
|
+
"name": "et",
|
114
|
+
"description": "id"
|
115
|
+
}
|
116
|
+
]
|
117
|
+
```
|
118
|
+
|
119
|
+
The above is an example of a 200 response. If you have more responses documented you can force that behaviour using `Apicraft-Response-Code` header in the mock request.
|
120
|
+
|
121
|
+
`https://yoursite.com/api/orders`
|
122
|
+
```
|
123
|
+
headers: {
|
124
|
+
Apicraft-Response-Code: 400
|
125
|
+
Apicraft-Mock: true
|
126
|
+
}
|
127
|
+
```
|
128
|
+
```json
|
129
|
+
{
|
130
|
+
"code": 400,
|
131
|
+
"message": "Something's not right"
|
132
|
+
}
|
133
|
+
```
|
134
|
+
|
135
|
+
### 👀 API Introspection
|
136
|
+
All APIs are can be introspected. You can do so by passing the `Apicraft-Introspection` header.
|
137
|
+
|
138
|
+
```
|
139
|
+
headers: {
|
140
|
+
Apicraft-Introspection: true
|
141
|
+
}
|
142
|
+
```
|
143
|
+
|
144
|
+
Example: `https://yoursite.com/api/orders`
|
145
|
+
```json
|
146
|
+
{
|
147
|
+
"summary": "Retrieve a list of orders",
|
148
|
+
"description": "Returns a list of orders in either JSON or XML format.",
|
149
|
+
"operationId": "getOrders",
|
150
|
+
"parameters": [
|
151
|
+
{
|
152
|
+
"name": "format",
|
153
|
+
"in": "query",
|
154
|
+
"description": "The response format (json or xml)",
|
155
|
+
"required": false,
|
156
|
+
"schema": {
|
157
|
+
"type": "string",
|
158
|
+
"enum": [
|
159
|
+
"json",
|
160
|
+
"xml"
|
161
|
+
]
|
162
|
+
}
|
163
|
+
}
|
164
|
+
],
|
165
|
+
"responses": {
|
166
|
+
...
|
167
|
+
}
|
168
|
+
}
|
169
|
+
```
|
170
|
+
### 👀 API Documentation
|
171
|
+
|
172
|
+
Mount the documentation views in your route file.
|
173
|
+
|
174
|
+
```ruby
|
175
|
+
# config/routes.rb
|
176
|
+
|
177
|
+
Rails.application.routes.draw do
|
178
|
+
# Rest of the routes...
|
179
|
+
mount Apicraft::Web::App, at: "/apicraft"
|
180
|
+
end
|
181
|
+
```
|
182
|
+
|
183
|
+
You can browse API Documentation at
|
184
|
+
- `/apicraft/swaggerdoc`
|
185
|
+
- `/apicraft/redoc`
|
186
|
+
|
187
|
+
Enable authentication for the `/apicraft` namespace.
|
188
|
+
|
189
|
+
```ruby
|
190
|
+
# config/application.rb
|
191
|
+
module App
|
192
|
+
class Application < Rails::Application
|
193
|
+
# Rest of the configuration...
|
194
|
+
Apicraft::Web::App.use do |user, password|
|
195
|
+
[user, password] == ["admin", "password"]
|
196
|
+
end
|
197
|
+
end
|
198
|
+
end
|
199
|
+
```
|
200
|
+
|
201
|
+
## Configuration
|
202
|
+
|
203
|
+
List of available configurations.
|
204
|
+
|
205
|
+
```ruby
|
206
|
+
Apicraft.configure do |config|
|
207
|
+
config.contracts_path = Rails.root.join("app/contracts")
|
208
|
+
|
209
|
+
# Enables or disables the mocking features
|
210
|
+
# Defaults to true
|
211
|
+
config.mocks = true
|
212
|
+
|
213
|
+
# Enables or disables the introspection features
|
214
|
+
# Defaults to true
|
215
|
+
config.introspection = true
|
216
|
+
|
217
|
+
# allows you to enforce stricter validation of $ref
|
218
|
+
# references in your OpenAPI specifications.
|
219
|
+
# When this option is enabled, the parser will raise
|
220
|
+
# an error if any $ref references in your OpenAPI
|
221
|
+
# document are invalid, ensuring that all references
|
222
|
+
# are correctly defined and resolved.
|
223
|
+
# Defaults to true
|
224
|
+
config.strict_reference_validation = true
|
225
|
+
|
226
|
+
config.headers = {
|
227
|
+
# The name of the header used to control
|
228
|
+
# the response code of the mock
|
229
|
+
# Defaults to Apicraft-Response-Code
|
230
|
+
response_code: "Apicraft-Response-Code",
|
231
|
+
|
232
|
+
# The name of the header to introspect the API.
|
233
|
+
# Defaults to Apicraft-Introspect
|
234
|
+
introspect: "Apicraft-Introspect"
|
235
|
+
|
236
|
+
# The name of the header to mock the API.
|
237
|
+
# Defaults to Apicraft-Mock
|
238
|
+
mock: "Apicraft-Mock"
|
239
|
+
}
|
240
|
+
end
|
241
|
+
|
242
|
+
Apicraft::Web::App.use do |user, password|
|
243
|
+
[user, password] == ["admin", "password"]
|
244
|
+
end
|
245
|
+
```
|
246
|
+
|
247
|
+
## Contributing
|
248
|
+
|
249
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/apicraft-dev/apicraft-rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/apicraft-dev/apicraft-rails/blob/main/CODE_OF_CONDUCT.md).
|
250
|
+
|
251
|
+
## License
|
252
|
+
|
253
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
254
|
+
|
255
|
+
## Code of Conduct
|
256
|
+
|
257
|
+
Everyone interacting in the Apicraft project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/apicraft/blob/main/CODE_OF_CONDUCT.md).
|
@@ -0,0 +1,41 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "lib/apicraft/version"
|
4
|
+
|
5
|
+
Gem::Specification.new do |spec|
|
6
|
+
spec.name = "apicraft-rails"
|
7
|
+
spec.version = Apicraft::VERSION
|
8
|
+
spec.authors = ["Abhishek Sarkar"]
|
9
|
+
spec.email = ["abhisheksarka@gmail.com"]
|
10
|
+
|
11
|
+
spec.summary = "APICraft Rails - Simplified API Design First Development"
|
12
|
+
spec.description = "🚀 Accelerates your development by 2-3x with an API Design First approach. Seamlessly integrates with your Rails application server — no fancy tooling or expenses required."
|
13
|
+
spec.homepage = "https://github.com/apicraft-dev/apicraft-rails"
|
14
|
+
spec.license = "MIT"
|
15
|
+
spec.required_ruby_version = ">= 2.7"
|
16
|
+
|
17
|
+
spec.metadata["allowed_push_host"] = "https://rubygems.org"
|
18
|
+
|
19
|
+
spec.metadata["homepage_uri"] = spec.homepage
|
20
|
+
spec.metadata["source_code_uri"] = "https://github.com/apicraft-dev/apicraft-rails"
|
21
|
+
spec.metadata["changelog_uri"] = "https://github.com/apicraft-dev/apicraft-rails/blob/main/CHANGELOG.md"
|
22
|
+
|
23
|
+
# Specify which files should be added to the gem when it is released.
|
24
|
+
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
25
|
+
spec.files = Dir.glob("{lib,bin,web}/**/*") + Dir.glob("*.{gemspec,md}")
|
26
|
+
spec.bindir = "exe"
|
27
|
+
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|
28
|
+
spec.require_paths = ["lib"]
|
29
|
+
|
30
|
+
# Uncomment to register a new dependency of your gem
|
31
|
+
spec.add_dependency "activesupport"
|
32
|
+
spec.add_dependency "erb"
|
33
|
+
spec.add_dependency "faker"
|
34
|
+
spec.add_dependency "mime-types"
|
35
|
+
spec.add_dependency "openapi_parser"
|
36
|
+
spec.add_dependency "rack"
|
37
|
+
spec.add_dependency "railties"
|
38
|
+
|
39
|
+
# For more information and examples about making a new gem, checkout our
|
40
|
+
# guide at: https://bundler.io/guides/creating_gem.html
|
41
|
+
end
|
data/bin/console
ADDED
@@ -0,0 +1,15 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
require "bundler/setup"
|
5
|
+
require "apicraft-rails"
|
6
|
+
|
7
|
+
# You can add fixtures and/or initialization code here to make experimenting
|
8
|
+
# with your gem easier. You can also use a different console, if you like.
|
9
|
+
|
10
|
+
# (If you use this, don't forget to add pry to your Gemfile!)
|
11
|
+
# require "pry"
|
12
|
+
# Pry.start
|
13
|
+
|
14
|
+
require "irb"
|
15
|
+
IRB.start(__FILE__)
|
data/bin/setup
ADDED
@@ -0,0 +1,30 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Apicraft
|
4
|
+
module Concerns
|
5
|
+
# Simple cache structure to not
|
6
|
+
# fetch the same data multiple times
|
7
|
+
# from the contracts
|
8
|
+
module Cacheable
|
9
|
+
@cache = {
|
10
|
+
key: {
|
11
|
+
loaded: true,
|
12
|
+
content: {}
|
13
|
+
}
|
14
|
+
}.with_indifferent_access
|
15
|
+
|
16
|
+
def self.cache
|
17
|
+
@cache
|
18
|
+
end
|
19
|
+
|
20
|
+
def with_cache(key)
|
21
|
+
data = Cacheable.cache[key]
|
22
|
+
return data[:content] if data.present?
|
23
|
+
|
24
|
+
c = yield
|
25
|
+
Cacheable.cache[key] = { content: c } if c.present?
|
26
|
+
c
|
27
|
+
end
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
@@ -0,0 +1,76 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Apicraft
|
4
|
+
# Configuration class for Apicraft.
|
5
|
+
#
|
6
|
+
# This class provides a simple way to configure Apicraft's behavior.
|
7
|
+
# It uses a hash-based configuration system, where default values can be
|
8
|
+
# overridden by user-provided options.
|
9
|
+
class Config
|
10
|
+
DEFAULTS = {
|
11
|
+
contracts_path: nil,
|
12
|
+
headers: {
|
13
|
+
response_code: "Apicraft-Response-Code",
|
14
|
+
introspect: "Apicraft-Introspect",
|
15
|
+
mock: "Apicraft-Mock",
|
16
|
+
content_type: "Content-Type"
|
17
|
+
},
|
18
|
+
mocks: true,
|
19
|
+
introspection: true,
|
20
|
+
strict_reference_validation: true,
|
21
|
+
request_validations: true
|
22
|
+
}.with_indifferent_access
|
23
|
+
|
24
|
+
def initialize(opts = {})
|
25
|
+
@opts = DEFAULTS.merge(
|
26
|
+
opts
|
27
|
+
).with_indifferent_access
|
28
|
+
end
|
29
|
+
|
30
|
+
def headers
|
31
|
+
@opts[:headers]
|
32
|
+
end
|
33
|
+
|
34
|
+
def strict_reference_validation
|
35
|
+
@opts[:strict_reference_validation]
|
36
|
+
end
|
37
|
+
|
38
|
+
def contracts_path
|
39
|
+
@opts[:contracts_path]
|
40
|
+
end
|
41
|
+
|
42
|
+
def mocks
|
43
|
+
@opts[:mocks]
|
44
|
+
end
|
45
|
+
|
46
|
+
def introspection
|
47
|
+
@opts[:introspection]
|
48
|
+
end
|
49
|
+
|
50
|
+
def contracts_path=(contracts_path)
|
51
|
+
@opts[:contracts_path] = contracts_path
|
52
|
+
end
|
53
|
+
|
54
|
+
def mocks=(enabled)
|
55
|
+
@opts[:mocks] = enabled
|
56
|
+
end
|
57
|
+
|
58
|
+
def introspection=(enabled)
|
59
|
+
@opts[:introspection] = enabled
|
60
|
+
end
|
61
|
+
|
62
|
+
def strict_reference_validation=(enabled)
|
63
|
+
@opts[:strict_reference_validation] = enabled
|
64
|
+
end
|
65
|
+
|
66
|
+
def request_validations=(enabled)
|
67
|
+
@opts[:request_validations] = enabled
|
68
|
+
end
|
69
|
+
|
70
|
+
def headers=(headers)
|
71
|
+
@opts[:headers] = @opts[:headers].merge(
|
72
|
+
headers.with_indifferent_access
|
73
|
+
)
|
74
|
+
end
|
75
|
+
end
|
76
|
+
end
|
@@ -0,0 +1,28 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Apicraft
|
4
|
+
# All constants for Apicraft
|
5
|
+
module Constants
|
6
|
+
HTTP_METHODS = %i[
|
7
|
+
get
|
8
|
+
post
|
9
|
+
put
|
10
|
+
patch
|
11
|
+
delete
|
12
|
+
head
|
13
|
+
options
|
14
|
+
trace
|
15
|
+
].freeze
|
16
|
+
|
17
|
+
MIME_TYPE_CONVERTORS = {
|
18
|
+
"application/json": :to_json,
|
19
|
+
"application/xml": :to_xml,
|
20
|
+
"application/yaml": :to_yaml,
|
21
|
+
"application/x-yaml": :to_yaml,
|
22
|
+
"text/csv": :to_csv,
|
23
|
+
"text/plain": :to_s,
|
24
|
+
"text/html": :to_html,
|
25
|
+
"application/msgpack": :to_msgpack
|
26
|
+
}.with_indifferent_access
|
27
|
+
end
|
28
|
+
end
|
@@ -0,0 +1,11 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Apicraft
|
4
|
+
class Errors
|
5
|
+
class RouteNotFound < StandardError; end
|
6
|
+
class InvalidContractsPath < StandardError; end
|
7
|
+
class InvalidContract < StandardError; end
|
8
|
+
class InvalidOperation < StandardError; end
|
9
|
+
class InvalidResponse < StandardError; end
|
10
|
+
end
|
11
|
+
end
|
@@ -0,0 +1,50 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Apicraft
|
4
|
+
# Recursively loads and processes YAML files from the
|
5
|
+
# application's contract folder during the application boot.
|
6
|
+
# This class is responsible for loading and initializing the
|
7
|
+
# contracts defined in the YAML files.
|
8
|
+
class Loader
|
9
|
+
def self.load!
|
10
|
+
contracts_path = Apicraft.config.contracts_path
|
11
|
+
return if contracts_path.blank?
|
12
|
+
|
13
|
+
raise Errors::InvalidContractsPath unless Dir.exist?(contracts_path)
|
14
|
+
|
15
|
+
Find.find(contracts_path) do |path|
|
16
|
+
next unless File.file?(path) && %w[.yaml .yml .json].include?(File.extname(path))
|
17
|
+
|
18
|
+
load_file!(path)
|
19
|
+
|
20
|
+
route = path.sub(contracts_path.to_s, "")
|
21
|
+
Web::Router.add(route, path)
|
22
|
+
end
|
23
|
+
end
|
24
|
+
|
25
|
+
def self.config
|
26
|
+
Apicraft.config
|
27
|
+
end
|
28
|
+
|
29
|
+
def self.load_file!(file)
|
30
|
+
ext = File.extname(file)
|
31
|
+
|
32
|
+
parsed = if ext == ".json"
|
33
|
+
JSON.parse(File.read(file))
|
34
|
+
else
|
35
|
+
YAML.load_file(file)
|
36
|
+
end
|
37
|
+
|
38
|
+
OpenAPIParser.parse(
|
39
|
+
parsed,
|
40
|
+
{
|
41
|
+
strict_reference_validation: config.strict_reference_validation
|
42
|
+
}
|
43
|
+
)
|
44
|
+
|
45
|
+
Openapi::Contract.create!(
|
46
|
+
OpenAPIParser.parse(parsed)
|
47
|
+
)
|
48
|
+
end
|
49
|
+
end
|
50
|
+
end
|
@@ -0,0 +1,42 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Apicraft
|
4
|
+
module Middlewares
|
5
|
+
# Apicraft Middleware to handle API Introspection.
|
6
|
+
class Introspector
|
7
|
+
def initialize(app)
|
8
|
+
@app = app
|
9
|
+
end
|
10
|
+
|
11
|
+
def call(env)
|
12
|
+
return @app.call(env) unless config.introspection
|
13
|
+
|
14
|
+
request = ActionDispatch::Request.new(env)
|
15
|
+
return @app.call(env) unless introspect?(request)
|
16
|
+
|
17
|
+
schema = Apicraft::Openapi::Contract.find_by_operation(
|
18
|
+
request.method, request.path_info
|
19
|
+
)&.operation(
|
20
|
+
request.method, request.path_info
|
21
|
+
)&.raw_schema
|
22
|
+
return @app.call(env) if schema.blank?
|
23
|
+
|
24
|
+
[
|
25
|
+
200,
|
26
|
+
{ 'Content-Type': "application/json" },
|
27
|
+
[schema.to_json]
|
28
|
+
]
|
29
|
+
end
|
30
|
+
|
31
|
+
private
|
32
|
+
|
33
|
+
def config
|
34
|
+
@config ||= Apicraft.config
|
35
|
+
end
|
36
|
+
|
37
|
+
def introspect?(request)
|
38
|
+
request.headers[config.headers[:introspect]].present?
|
39
|
+
end
|
40
|
+
end
|
41
|
+
end
|
42
|
+
end
|