Class: RspecApiDocumentation::Writers::OpenApiWriter

Inherits:
Writer
  • Object
show all
Defined in:
lib/rspec_api_documentation/writers/open_api_writer.rb

Direct Known Subclasses

OpenApiJsonWriter, OpenApiYamlWriter

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#swaggerObject



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/rspec_api_documentation/writers/open_api_writer.rb', line 223

def swagger
  @swagger ||= {
    "openapi" => "3.0.0",
    "info" => info,
    "servers" => servers,
    "paths" => {},
    "components" => {
      "securitySchemes" => {
        "bearerAuth" => {
          "type" => "http",
          "scheme" => "bearer"
        },
        "basicAuth" => {
          "type" => "http",
          "scheme" => "basic"
        }
      },
      "schemas" => {}
    }
  }
end

#typesObject



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/rspec_api_documentation/writers/open_api_writer.rb', line 206

def types
  @types ||= {
    "unauthorized" => {
      "properties" => {
        "code" => {
          "type" => "string",
          "example" => "invalid_client_credentials"
        },
        "message" => {
          "type" => "string",
          "example" => "Not found or invalid client credentials"
        }
      }
    }
  }
end

Instance Method Details

#get_hashObject



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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/rspec_api_documentation/writers/open_api_writer.rb', line 23

def get_hash
  index.examples.each do |rspec_example|
    api = JSONExample.new(rspec_example, configuration).as_json.deep_stringify_keys
    description = api["description"]
    route = api["route"].gsub(%r{\:version\/}, "")
    route = route.gsub(%r{\:([^\/]+)}, '{\1}')
    params = route.scan(%r{\{([^\/]+)\}}).map { |param| { "name" => param[0], "in" => "path", "required" => true, "schema" => { "type" => "string" } } }
    swagger["paths"][route] = swagger["paths"][route] || {}
    responses = {}
    req = api["requests"][0]
    method = req["request_method"].downcase
    result = JSON.parse(req["response_body"]) if req["response_body"]
    properties = {}
    result&.each { |k, v| properties[k] = get_properties(v) }

    responses[req["response_status"]] = {
      "description" => req["response_status_text"],
      "headers" => req["response_headers"].map { |name, _v| [name, { "schema" => { "type" => "string" } }] }.to_h,
      "content" => {
        "application/json" => {
          "schema" => {
            "type" => "object",
            "properties" => properties
          }
        }
      }
    }
    api["parameters"]&.each do |param|
      params.push("name" => param["name"],
                  "in" => "query",
                  "schema" => {
                    "type" => "string"
                  },
                  "description" => param["description"],
                  "required" => param["required"] || false)
    end

    req["request_query_parameters"]&.each do |name, value|
      params.push("name" => name,
                  "in" => "query",
                  "schema" => {
                    "type" => "string"
                  },
                  "example" => value)
    end
    if req["request_content_type"] == "application/x-www-form-urlencoded" && api["requests"][0]["request_body"]
      req["request_body"].scan(/([^\&\=]*)=([^\&]*)/).map do |body|
        params.push("name" => body[0],
                    "in" => "query",
                    "schema" => {
                      "type" => "string"
                    },
                    "example" => CGI.unescape(body[1]))
      end
    end
    swagger["paths"][route][method] = swagger["paths"][route][method] || {}
    swagger["paths"][route][method]["parameters"] = swagger["paths"][route][method]["parameters"] || []

    req["request_headers"]&.each do |name, value|
      if name == "Authorization"
        swagger["paths"][route][method]["security"] = if /Bearer (.*)/.match?(value)
                                                        responses["401"] = {
                                                          "description" => "Unauthorized Access",
                                                          "content" => {
                                                            "application/json" => {
                                                              "schema" => {
                                                                "$ref" => "#/components/schemas/unauthorized"
                                                              }
                                                            }
                                                          }
                                                        }
                                                        [{ "bearerAuth" => [] }]
                                                      else
                                                        [{ "basicAuth" => [] }]
                                                      end
      else
        params.unshift("name" => name,
                       "in" => "header",
                       "schema" => {
                         "type" => "string"
                       },
                       "example" => value,
                       "required" => true)
      end
    end
    params.each do |param|
      has = false
      swagger["paths"][route][method]["parameters"].each_with_index do |p, i|
        if p["name"] == param["name"]
          swagger["paths"][route][method]["parameters"][i]["example"] = swagger["paths"][route][method]["parameters"][i]["example"] || param["example"]
          has = true
        end
      end
      swagger["paths"][route][method]["parameters"].push(param) unless has
    end
    desc = swagger["paths"][route][method]["description"] || ""
    swagger["paths"][route][method]["description"] = desc + "- #{description}, <strong>Needed Parameters:</strong>\n  - #{ params.map{ |p| p['name'] }.join("\n  - ") } \n"
    swagger["paths"][route][method]["responses"] = responses
  end
  swagger["components"]["schemas"] = types

  swagger
end

#get_properties(v) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/rspec_api_documentation/writers/open_api_writer.rb', line 127

def get_properties(v)
  case v.class.name
  when "Hash"
    props = v.map { |key, value| [key, get_properties(value)] }.to_h
    x = {
      "type" => "object",
      "properties" => props
    }
    if v["type"]
      type = v["type"].tr("\/", "_")
      types[type] = x unless types.key?(type)
      if types.key?(type)
        types[type]["properties"] = hash_deep_assign(types[type]["properties"], x["properties"])
      else
        types[type] = x
      end
      return { "$ref" => "#/components/schemas/#{type}" }
    end
    x
  when "Array"
    {
      "type" => "array",
      "items" => get_properties(v[0])
    }
  when "TrueClass", "FalseClass"
    {
      "type" => "boolean",
      "example" => v
    }
  when "NilClass"
    {
      "type" => "integer",
      "nullable" => true
    }
  when "Integer", "Float"
    {
      "type" => "number",
      "example" => v
    }
  else
    {
      "type" => v.class.name.downcase,
      "example" => v
    }
  end
end

#hash_deep_assign(target, other) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/rspec_api_documentation/writers/open_api_writer.rb', line 174

def hash_deep_assign(target, other)
  return target unless target && other
  other.each do |key, value|
    target[key] = if target.key?(key) && other[key].is_a?(Hash)
                    hash_deep_assign(target[key], other[key])
                  elsif target.key?(key) && target[key].is_a?(Array) && other[key].is_a?(Array)
                    target[key].push(*other[key]).uniq
                  elsif key == "$ref"
                    if other["$ref"] && target["$ref"] && target["$ref"] != other["$ref"]
                      target = {
                        "oneOf" => [
                          { "$ref" => target["$ref"] },
                          { "$ref" => other["$ref"] }
                        ]
                      }
                    elsif target.key?("oneOf")
                      target["oneOf"].push("$ref" => other["$ref"]).uniq
                    else
                      target["$ref"] || other["$ref"]
                    end
                  elsif target.key?(key)
                    target[key] || other[key]
                  else
                    value
                  end
  end
  target = { "oneOf" => target["oneOf"] } if target.key?("oneOf")
  target = { "$ref" => target["$ref"] } if target.key?("$ref")
  target = get_properties(target["example"]) if target["example"] && target.key?("nullable")
  target
end

#infoObject



245
246
247
248
249
250
251
252
253
254
# File 'lib/rspec_api_documentation/writers/open_api_writer.rb', line 245

def info
  RspecApiDocumentation.configuration.open_api["host"] || {
    "version" => "1.0.0",
    "title" => "Open API",
    "description" => "Open API",
    "contact" => {
      "name" => "OpenAPI"
    }
  }
end

#serversObject



256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/rspec_api_documentation/writers/open_api_writer.rb', line 256

def servers
  RspecApiDocumentation.configuration.open_api["server"] || [
    {
      "url" => "http://localhost:{port}",
      "description" => "Development server",
      "variables" => {
        "port" => {
          "default" => "3000"
        }
      }
    }
  ]
end

#writeObject



13
14
15
16
17
18
19
20
21
# File 'lib/rspec_api_documentation/writers/open_api_writer.rb', line 13

def write
  File.open(configuration.docs_dir.join("open_api.json"), "w") do |f|
    f.write JSON.pretty_generate(get_hash)
  end

  File.open(configuration.docs_dir.join("open_api.yaml"), "w") do |f|
    f.write get_hash.to_yaml
  end
end