Class: Synthra::Export::OpenAPI

Inherits:
Object
  • Object
show all
Defined in:
lib/synthra/export/openapi.rb

Overview

OpenAPI/Swagger Export

Generates OpenAPI 3.0 specifications from Synthra schemas. Includes complete API definitions with endpoints for data generation.

Examples:

Generate OpenAPI spec

exporter = Synthra::Export::OpenAPI.new(registry)
spec = exporter.export

CLI usage

$ synthra export --all -d schemas -f openapi -o api.yaml

Constant Summary collapse

TYPE_MAP =

Type mapping from Synthra to OpenAPI

{
  # Strings
  "text" => { "type" => "string" },
  "name" => { "type" => "string" },
  "email" => { "type" => "string", "format" => "email" },
  "url" => { "type" => "string", "format" => "uri" },
  "uuid" => { "type" => "string", "format" => "uuid" },
  "date" => { "type" => "string", "format" => "date" },
  "date_between" => { "type" => "string", "format" => "date" },
  "past_date" => { "type" => "string", "format" => "date" },
  "future_date" => { "type" => "string", "format" => "date" },
  "mobile_device_release_date" => { "type" => "string", "format" => "date" },
  "now" => { "type" => "string", "format" => "date" },
  "timestamp" => { "type" => "string", "format" => "date-time" },
  "datetime" => { "type" => "string", "format" => "date-time" },
  "phone" => { "type" => "string" },
  "password" => { "type" => "string", "format" => "password" },
  "ip" => { "type" => "string", "format" => "ipv4" },
  "ipv6" => { "type" => "string", "format" => "ipv6" },

  # Numbers (integers)
  "number" => { "type" => "integer", "format" => "int64" },
  "integer" => { "type" => "integer", "format" => "int64" },
  "age" => { "type" => "integer" },
  "airport_elevation" => { "type" => "integer" },
  "discount" => { "type" => "integer" },
  "formula" => { "type" => "integer" },
  "row_number" => { "type" => "integer" },
  "sequence" => { "type" => "integer" },
  "id_sequence" => { "type" => "integer" },

  # Numbers (floats)
  "float" => { "type" => "number", "format" => "double" },
  "money" => { "type" => "number", "format" => "double" },
  "decimal" => { "type" => "number" },
  "latitude" => { "type" => "number", "format" => "double" },
  "longitude" => { "type" => "number", "format" => "double" },
  "airport_latitude" => { "type" => "number", "format" => "double" },
  "airport_longitude" => { "type" => "number", "format" => "double" },
  "product_price" => { "type" => "number", "format" => "double" },
  "tax_rate" => { "type" => "number", "format" => "double" },
  "transaction_amount" => { "type" => "number", "format" => "double" },

  # Boolean
  "boolean" => { "type" => "boolean" },

  # Structural
  "object" => { "type" => "object" },
  "map_by_field" => { "type" => "object" },
  "array" => { "type" => "array" },
  "json_array" => { "type" => "array" },

  # Binary
  "binary" => { "type" => "string", "format" => "binary" },
  "base64" => { "type" => "string", "format" => "byte" }
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(registry, **options) ⇒ OpenAPI

Create a new OpenAPI exporter

Parameters:

  • registry (Registry)

    schema registry

  • options (Hash)

    export options

Options Hash (**options):

  • :title (String)

    API title

  • :version (String)

    API version

  • :description (String)

    API description

  • :server_url (String)

    Base server URL

  • :format (Symbol)

    Output format (:yaml or :json)



91
92
93
94
95
96
97
98
99
100
# File 'lib/synthra/export/openapi.rb', line 91

def initialize(registry, **options)
  @registry = registry
  @options = {
    title: "Synthra Data Generation API",
    version: "1.0.0",
    description: "API for generating fake data from schemas",
    server_url: "http://localhost:3000",
    format: :yaml
  }.merge(options)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



79
80
81
# File 'lib/synthra/export/openapi.rb', line 79

def options
  @options
end

#registryObject (readonly)

Returns the value of attribute registry.



79
80
81
# File 'lib/synthra/export/openapi.rb', line 79

def registry
  @registry
end

Instance Method Details

#batch_generation_parametersObject (private)



348
349
350
351
352
353
354
355
356
357
# File 'lib/synthra/export/openapi.rb', line 348

def batch_generation_parameters
  generation_parameters + [
    {
      "name" => "count",
      "in" => "query",
      "description" => "Number of records to generate",
      "schema" => { "type" => "integer", "default" => 10, "minimum" => 1, "maximum" => 10000 }
    }
  ]
end

#build_common_parametersObject (private)



481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/synthra/export/openapi.rb', line 481

def build_common_parameters
  {
    "seedParam" => {
      "name" => "seed",
      "in" => "query",
      "description" => "Random seed for deterministic generation",
      "schema" => { "type" => "integer" }
    },
    "modeParam" => {
      "name" => "mode",
      "in" => "query",
      "description" => "Generation mode",
      "schema" => {
        "type" => "string",
        "enum" => %w[random edge invalid hostile mixed]
      }
    },
    "countParam" => {
      "name" => "count",
      "in" => "query",
      "description" => "Number of records to generate",
      "schema" => { "type" => "integer", "default" => 10 }
    }
  }
end

#build_componentsObject (private)



359
360
361
362
363
364
# File 'lib/synthra/export/openapi.rb', line 359

def build_components
  {
    "schemas" => build_schemas,
    "parameters" => build_common_parameters
  }
end

#build_infoObject (private)



140
141
142
143
144
145
146
147
148
149
150
# File 'lib/synthra/export/openapi.rb', line 140

def build_info
  {
    "title" => @options[:title],
    "version" => @options[:version],
    "description" => @options[:description],
    "contact" => {
      "name" => "Synthra",
      "url" => "https://github.com/talaatmagdyx/synthra"
    }
  }
end

#build_pathsObject (private)



170
171
172
173
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/synthra/export/openapi.rb', line 170

def build_paths
  paths = {}
  
  # Schema listing endpoint
  paths["/api/schemas"] = {
    "get" => {
      "tags" => ["Schemas"],
      "summary" => "List all available schemas",
      "operationId" => "listSchemas",
      "responses" => {
        "200" => {
          "description" => "List of schema names",
          "content" => {
            "application/json" => {
              "schema" => {
                "type" => "object",
                "properties" => {
                  "schemas" => {
                    "type" => "array",
                    "items" => { "type" => "string" }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  
  # Per-schema endpoints
  @registry.names.sort.each do |name|
    snake_name = to_snake_case(name)
    
    # Generate single
    paths["/api/#{snake_name}"] = {
      "get" => {
        "tags" => [name],
        "summary" => "Generate a single #{name}",
        "operationId" => "generate#{name}",
        "parameters" => generation_parameters,
        "responses" => {
          "200" => {
            "description" => "Generated #{name}",
            "content" => {
              "application/json" => {
                "schema" => { "$ref" => "#/components/schemas/#{name}" }
              }
            }
          }
        }
      }
    }
    
    # Generate many
    paths["/api/#{snake_name}/batch"] = {
      "get" => {
        "tags" => [name],
        "summary" => "Generate multiple #{name} records",
        "operationId" => "generateMany#{name}s",
        "parameters" => batch_generation_parameters,
        "responses" => {
          "200" => {
            "description" => "Generated #{name} records",
            "content" => {
              "application/json" => {
                "schema" => {
                  "type" => "object",
                  "properties" => {
                    "data" => {
                      "type" => "array",
                      "items" => { "$ref" => "#/components/schemas/#{name}" }
                    },
                    "meta" => {
                      "type" => "object",
                      "properties" => {
                        "count" => { "type" => "integer" },
                        "seed" => { "type" => "integer" },
                        "mode" => { "type" => "string" }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      "post" => {
        "tags" => [name],
        "summary" => "Generate #{name} records with overrides",
        "operationId" => "generateMany#{name}sWithOverrides",
        "requestBody" => {
          "content" => {
            "application/json" => {
              "schema" => { "$ref" => "#/components/schemas/GenerationRequest" }
            }
          }
        },
        "responses" => {
          "200" => {
            "description" => "Generated #{name} records",
            "content" => {
              "application/json" => {
                "schema" => {
                  "type" => "array",
                  "items" => { "$ref" => "#/components/schemas/#{name}" }
                }
              }
            }
          }
        }
      }
    }
    
    # Stream endpoint
    paths["/api/#{snake_name}/stream"] = {
      "get" => {
        "tags" => [name],
        "summary" => "Stream #{name} records (NDJSON)",
        "operationId" => "stream#{name}s",
        "parameters" => batch_generation_parameters,
        "responses" => {
          "200" => {
            "description" => "Streamed #{name} records",
            "content" => {
              "application/x-ndjson" => {
                "schema" => { "$ref" => "#/components/schemas/#{name}" }
              }
            }
          }
        }
      }
    }
    
    # Schema info endpoint
    paths["/api/#{snake_name}/schema"] = {
      "get" => {
        "tags" => [name],
        "summary" => "Get #{name} schema definition",
        "operationId" => "get#{name}Schema",
        "responses" => {
          "200" => {
            "description" => "Schema definition",
            "content" => {
              "application/json" => {
                "schema" => { "$ref" => "#/components/schemas/SchemaDefinition" }
              }
            }
          }
        }
      }
    }
  end
  
  paths
end

#build_schemasObject (private)



366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/synthra/export/openapi.rb', line 366

def build_schemas
  schemas = {}
  
  # Schema definitions
  @registry.names.each do |name|
    schema = @registry.schema(name)
    schemas[name] = schema_to_openapi(schema)
  end
  
  # Common schemas
  schemas["GenerationRequest"] = {
    "type" => "object",
    "properties" => {
      "count" => { "type" => "integer", "default" => 10 },
      "seed" => { "type" => "integer" },
      "mode" => { "type" => "string", "enum" => %w[random edge invalid hostile mixed] },
      "overrides" => { "type" => "object", "additionalProperties" => true }
    }
  }
  
  schemas["SchemaDefinition"] = {
    "type" => "object",
    "properties" => {
      "name" => { "type" => "string" },
      "fields" => {
        "type" => "array",
        "items" => {
          "type" => "object",
          "properties" => {
            "name" => { "type" => "string" },
            "type" => { "type" => "string" },
            "optional" => { "type" => "boolean" },
            "nullable" => { "type" => "boolean" }
          }
        }
      },
      "behaviors" => {
        "type" => "array",
        "items" => { "type" => "object" }
      }
    }
  }
  
  schemas["Error"] = {
    "type" => "object",
    "properties" => {
      "error" => { "type" => "string" },
      "message" => { "type" => "string" },
      "code" => { "type" => "integer" }
    }
  }
  
  schemas
end

#build_serversObject (private)



152
153
154
155
156
157
158
159
# File 'lib/synthra/export/openapi.rb', line 152

def build_servers
  [
    {
      "url" => @options[:server_url],
      "description" => "Data Generation Server"
    }
  ]
end

#build_specObject (private)



129
130
131
132
133
134
135
136
137
138
# File 'lib/synthra/export/openapi.rb', line 129

def build_spec
  {
    "openapi" => "3.0.3",
    "info" => build_info,
    "servers" => build_servers,
    "tags" => build_tags,
    "paths" => build_paths,
    "components" => build_components
  }
end

#build_tagsObject (private)



161
162
163
164
165
166
167
168
# File 'lib/synthra/export/openapi.rb', line 161

def build_tags
  @registry.names.sort.map do |name|
    {
      "name" => name,
      "description" => "Operations for #{name} schema"
    }
  end
end

#exportString

Export registry to OpenAPI specification

Returns:

  • (String)

    OpenAPI spec in YAML or JSON format



106
107
108
109
110
111
112
113
114
115
# File 'lib/synthra/export/openapi.rb', line 106

def export
  spec = build_spec
  
  case @options[:format]
  when :json
    JSON.pretty_generate(spec)
  else
    spec.to_yaml
  end
end

#export_as(format) ⇒ String

Export to specific format

Parameters:

  • format (Symbol)

    :yaml or :json

Returns:

  • (String)

    formatted spec



122
123
124
125
# File 'lib/synthra/export/openapi.rb', line 122

def export_as(format)
  spec = build_spec
  format == :json ? JSON.pretty_generate(spec) : spec.to_yaml
end

#field_to_openapi(field) ⇒ Object (private)



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/synthra/export/openapi.rb', line 439

def field_to_openapi(field)
  type_name = field.type_name
  
  # Handle arrays
  if type_name == "array"
    element = field.type_args[:element]
    items = if @registry.schema?(element.to_s)
              { "$ref" => "#/components/schemas/#{element}" }
            else
              TYPE_MAP[element.to_s] || { "type" => "string" }
            end
    
    result = { "type" => "array", "items" => items }
    
    if (size = field.type_args[:size])
      result["minItems"] = size.min if size.respond_to?(:min)
      result["maxItems"] = size.max if size.respond_to?(:max)
    end
    
    return result
  end
  
  # Handle enums
  if type_name == "enum"
    values = field.type_args[:values]&.map { |v| v.respond_to?(:value) ? v.value : v.to_s }
    return { "type" => "string", "enum" => values || [] }
  end
  
  # Handle const
  if type_name == "const"
    return { "const" => field.type_args[:value] }
  end
  
  # Handle references
  if @registry.schema?(type_name)
    return { "$ref" => "#/components/schemas/#{type_name}" }
  end
  
  # Standard type mapping
  TYPE_MAP[type_name]&.dup || { "type" => "string" }
end

#generation_parametersObject (private)



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/synthra/export/openapi.rb', line 328

def generation_parameters
  [
    {
      "name" => "seed",
      "in" => "query",
      "description" => "Random seed for deterministic generation",
      "schema" => { "type" => "integer" }
    },
    {
      "name" => "mode",
      "in" => "query",
      "description" => "Generation mode",
      "schema" => {
        "type" => "string",
        "enum" => %w[random edge invalid hostile mixed]
      }
    }
  ]
end

#schema_to_openapi(schema) ⇒ Object (private)



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/synthra/export/openapi.rb', line 421

def schema_to_openapi(schema)
  properties = {}
  required = []
  
  schema.fields.each do |field|
    properties[field.name] = field_to_openapi(field)
    required << field.name unless field.optional?
  end
  
  result = {
    "type" => "object",
    "properties" => properties
  }
  
  result["required"] = required if required.any?
  result
end

#to_snake_case(str) ⇒ Object (private)



507
508
509
510
511
# File 'lib/synthra/export/openapi.rb', line 507

def to_snake_case(str)
  str.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
     .gsub(/([a-z\d])([A-Z])/, '\1_\2')
     .downcase
end