Git Product home page Git Product logo

swiftgger's Introduction

Profile background

Hi there 👋

My name is Marcin and I'm a software developer since almost two decades. I'm working mostly on enterprise applications (C#/Typescript), however in my free time I'm creating applications for iOS and macOS in my favorite language: Swift. I live in Wrocław/Poland with my lovely wife and daughter.

You can find me also on:

Website https://mczachurski.dev

Website https://mastodon.social/@mczachurski

Writefreely https://writefreely.social/mczachurski

Website https://pixelfed.social/@mczachurski

Github statistics

Anurag's github stats

Pinned repositories

ReadMe Card ReadMe Card ReadMe Card ReadMe Card

Languages

Top Langs

(Almost) Live statistics 😄

willianrod's wakatime stats

swiftgger's People

Contributors

eneko avatar mczachurski avatar mohpor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

swiftgger's Issues

Dictionary object

Hello, can you add
Снимок экрана 2021-06-25 в 12 50 31
Dictionary to APIResponse or how I need use dictionary in response?

Incorrect example value under Request Body

Hello!
I am experiencing problems with incorrect values I used to demonstrate params for request body. See attached image.
Screenshot 2021-06-07 at 14 57 54

And see the code snippet and json below:

struct TestObject {
var test: String
var authClientIds: [UUID]
}

`
let openAPIBuilder = OpenAPIBuilder(
title: "Tasker server API",
version: "1.0.0",
description: "This is a sample server for task server application."
)
.add([
APIObject(object: TestObject(test: "Test-ID", authClientIds: [UUID(), UUID()])),
])
.add(APIController(name: "Users", description: "Controller where we can manage users", actions: [
APIAction(method: .post,
route: "/users",
summary: "Test",
description: "Test",
request:
APIRequest(object: TestObject.self, description: "Test description"),
responses: [
APIResponse(code: "200",
description: "Ok",
object: TestObject.self)
],
authorization: false)
])
)

let openAPIDocument = openAPIBuilder.built()

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let jsonData = try! encoder.encode(openAPIDocument)
let jsonString = String(bytes: jsonData, encoding: .utf8)
print(jsonString!)
return jsonString!
`
json.txt

What I am doing wrong?
I expect to get the following under Example Value:

{
"authClientIds": ["26E490CF-31C5-4A12-A212-74BF7A896CC6", "39E490CF-31C5-4A12-A212-74BF7A896CC6"]
"test": "test-str"
}

Could you please take a look at this issue?

Parameter error: "😱 Could not render this component, see the console."

Hi,
For the api

http://localhost:8080/myapi/?offset=2&limit=10

On Package.swift I declare:

 .package(url: "https://github.com/mczachurski/Swiftgger.git", from: "1.2.2")

The peace of code for Swiftgger:

struct MyObject {
    let id: Int
    let name: String
}

var lActions:[APIAction] = []

let lMyApi = APIAction(
    method: .get, route: "/myapi",
    summary: "Some summary",
    description: "some description",
    parameters: [
        APIParameter(name: "offset", parameterLocation: .query,  description: "offset description", required: false),
        APIParameter(name: "limit", parameterLocation: .query, description: "limit description", required: false)
    ],
    responses: [
        APIResponse(code: "200", description: "OK", array: MyObject.self, contentType: "json")
    ],
    authorization: true)

lActions.append(lMyApi)

let lOpenAPI = OpenAPIBuilder(
    title: "MyAPI",
    version: "1.0.0",
    description: "MyAPI description"
    )

lOpenAPI.add(lAPIController)
        .add([
           APIObject(object: MyObject(id: 100, name: "name of the object"))
        ])

When I call http://localhost:8080/swagger.json Swiftgger generate:

{
  "paths": {
    "/myapi": {
      "get": {
        "parameters": [
          {
            "deprecated": false,
            "allowEmptyValue": false,
            "in": "query",
            "name": "offset",
            "description": "offset description",
            "required": false
          },
          {
            "deprecated": false,
            "allowEmptyValue": false,
            "in": "query",
            "name": "limit",
            "description": "limit description",
            "required": false
          }
        ],
        "tags": [
          "MyApi"
        ],
        "deprecated": false,
        "responses": {
          "200": {
            "content": {
              "json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/MyObject"
                  }
                }
              }
            },
            "description": "OK"
          }
        },
        "description": "some description",
        "summary": "Some summary"
      }
    }
  },
  "servers": [
    
  ],
  "openapi": "3.0.1",
  "info": {
    "title": "MyAPI",
    "version": "1.0.0",
    "description": "MyAPI description"
  },
  "tags": [
    {
      "name": "MyApi",
      "description": "Test APIs"
    }
  ],
  "components": {
    "schemas": {
      "MyObject": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "example": "name of the object"
          },
          "id": {
            "type": "int",
            "example": "100"
          }
        },
        "required": [
          "id",
          "name"
        ]
      }
    },
    "securitySchemes": {
      
    }
  }
}

To run Swagger UI locally I use Docker with this Dockerfile:

FROM node

RUN npm update npm &&\
    npm install http-server replace

RUN mkdir -p /tmp/swagger
ADD https://github.com/swagger-api/swagger-ui/archive/master.tar.gz /tmp/swagger/swaggerui.tar.gz
RUN tar --strip-components 1 -C /tmp/swagger -xzf /tmp/swagger/swaggerui.tar.gz

RUN mkdir -p /swaggerui/dist/swagger-ui &&\
    mv /tmp/swagger/dist/* /swaggerui/dist/swagger-ui &&\
    rm -rf /tmp/swagger

ENV API_URL http://petstore.swagger.io/v2/swagger.json

RUN echo "'use strict';\
var path = require('path');\
var createServer = require('http-server').createServer;\
var dist = path.join('swaggerui', 'dist');\
var replace = require('replace');\
replace({regex: 'http.*swagger.json', replacement : process.env.API_URL, paths: ['/swaggerui/dist/swagger-ui/index.html'], recursive:false, silent:true,});\
var swaggerUI = createServer({ root: dist, cors: true });\
swaggerUI.listen(8888);" > /swaggerui/index.js

EXPOSE 8888

And launch Swagger UI with the command line:

docker run --detach --rm --name swaggerui -p 8888:8888 -e "API_URL=http://localhost:8080/swagger.json" swaggerui:latest

On the browser I can see this:
image

And on the console I have this:
image

The parameters are not defined correctly but I do not see what needs to be done to correct this.

Update APIResponse type

Maybe need to change APIResponse type - case dictionary from dictionary(Any.Type) to dictionary(Any.Type : Any.Type)
Снимок экрана 2021-08-02 в 12 27 38
If I use one type for response it’s okay, but if I need use [String.self : ClientResponse.self] I have problem.
Снимок экрана 2021-08-02 в 12 29 29

Compile error: "Reference to member 'value' cannot be resolved without a contextual type"

The library cannot be compiled with Swift 4.1 because of the error in OpenAPIExample.swift, line 47:

try container.encode(value, forKey: .value) // ERROR: Reference to member 'value' cannot be resolved without a contextual type

That's because the value property is of type Optional<Any>. Prior to Swift 4.1 Optional conformed to the Encodable protocol unconditionally at compile time, but attempting to encode its payload if the payload is not itself Encodable would crash at runtime.

Swift 4.1 introduced conditional conformances, and now this error is caught at compile time, which results in the inability to compile Swiftgger.

My suggestion would be to make the OpenAPIExample class generic:

-public class OpenAPIExample: Encodable
+public class OpenAPIExample<Value: Encodable>: Encodable {

     public private(set) var ref: String?
     public private(set) var summary: String?
     public private(set) var description: String?
-    public private(set) var value: Any?
+    public private(set) var value: Value?
     public private(set) var externalValue: String?

However, I haven't tried this and not sure if it'll work with the rest of the project.

I'm looking forward to be able to use Swiftgger in my Vapor project 😊

Issue with nested array of encodable objects

Hello!
Could you please to take a look at the following issue:
I have found that a collection of encodable objects is missing under Example Values. See image below:
Screenshot 2021-06-17 at 09 33 45

And here is a code snippet to reproduce the issue:

struct NestedObject: Encodable {
    var version: String
    var value: String
}

struct TestObject: Encodable {
    var nested: NestedObject
    var nestedObjects: [NestedObject]
    var nestedValues: [String]
}

        let nested1 = NestedObject(version: "1.0", value: "Nested Object 1")
        let nested2 = NestedObject(version: "2.0", value: "Nested Object 2")
        let nested3 = NestedObject(version: "3.0", value: "Nested Object 3")
        let test = TestObject(nested:nested1, nestedObjects: [nested2, nested3],
                              nestedValues: ["Str1", "Str2"])
        
        let openAPIBuilder = OpenAPIBuilder(
            title: "Tasker server API",
            version: "1.0.0",
            description: "This is a sample server for task server application."
        )
        .add([
            APIObject(object: test)
        ])
        .add(APIController(name: "Test",
                           description: "Controller where we can manage test",
                           actions: [
                                APIAction(method: .get,
                                          route: "/test",
                                          summary: "Summary",
                                          description: "Description",
                                          responses: [
                                            APIResponse(code: "200",
                                                        description: "Ok",
                                                        type: .object(TestObject.self))
                                          ],
                                          authorization: false)
                           ])
        )

        let openAPIDocument = openAPIBuilder.built()

        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted

        let jsonData = try! encoder.encode(openAPIDocument)
        let jsonString = String(bytes: jsonData, encoding: .utf8)
        print(jsonString!)
        return jsonString!

Custom Schema name

Hi,

First off, wonderful package!

I'm trying to add my models to schemas for the swagger specs. We are using enums to encapsulate models and functionalities, therefore, my model names are not exactly clear when added as APIObject.

For example this might be a model of mine:

enum Models {
  enum Transactions {
    enum Response {
    final class List: Content {
       ....
    }
  }
 }
}

now, as you can see, when I add a transaction list item, all I get in Schemas section is: List which is not at all clear to user.
Is there something I'm missing?

My suggestion (Swift being crazy when it comes to reflection, and use-cases being very different), it might be a good idea to let developers choose the type's name when adding the APIObject.

Thanks

Swiftgger upgrade issue

Hello!
I think that it might be helpful for someone if you will add explanation for the following issue to 'readme' file:

Swiftgger >=1.4.0 contains incompatible tools version and root depends on Swiftgger >=1.5.0, version solving failed

This error happens when the main project uses the latest version of Swiftgger and swift version lower then 5.3 (5.2 for example)
Thanks

Issue with plain text in 'Example Value' field

Hello!

Right now some of our handlers return plain strings instead of JSON. For example,

private func getAppHealthHandler(_ req: Request) throws -> String {
        "All good!"
    }

So I would like to ask you to make it possible to show raw string under "Example Value".
Because it shows empty brackets at the moment. See attached image.
Screenshot 2021-06-11 at 16 30 47
See the code snippet:

let openAPIBuilder = OpenAPIBuilder(
    title: "Tasker server API",
    version: "1.0.0",
    description: "This is a sample server for task server application."
)
.add([
    APIObject(object: "Text Response")
])
.add(APIController(name: "Test", description: "Controller where we can manage test", actions: [
    APIAction(method: .get,
              route: "/test",
              summary: "Summary",
              description: "Description",
              responses: [
                APIResponse(code: "200",
                            description: "Ok",
                            object: String.self,
                            contentType: "text/plain")
              ],
              authorization: false)
    ])
)

let openAPIDocument = openAPIBuilder.built()

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let jsonData = try! encoder.encode(openAPIDocument)
let jsonString = String(bytes: jsonData, encoding: .utf8)
print(jsonString!)
return jsonString!

Also we do not need 'String' in Models section.

Thanks you!

Authorization header

Hi! I need help from Authorization header, please.

My APIParameter -
APIParameter(name: "Authorization", parameterLocation: .header, description: "Bearer xxxxxx", required: true, dataType: .string)

I do not understand whether I'm doing everything? But I can't get access using real Token

Thanks in advance!

APIObject Decimal and [[[T]]]

Objects with Decimal attributes or nested Array (tested Array<Array<Array<Double>>>) fail to serialize in the schema and fall back to another schema link.

[[[Double]]] is typical for GeoJSON requests so it can't be split up into objects.

Decimal should be shown as a Number, not an object.

Classes and Struct to APIObject

Hello again!)
I hope this is my last question))

When I initialize the Struct and add it as APIObject (object: userResponse)
The description in the description of the circuit is all displayed perfectly!

It is - struct UserResponse
Снимок экрана 2020-11-27 в 11 17 08

But when I do the same with the class I get a completely different result.
It is - final class User
Снимок экрана 2020-11-27 в 11 18 05

What am I doing wrong?

Nested Objects

Nested objects are treated like simple strings when you generate OpenAPI definitions. Is it not supported or am I doing something wrong? I can't find any examples with the nested objects.

CamelCase to snake_case

Hello, how can I convert the structure model from camelCase to snake_case model in Object -
Снимок экрана 2021-05-22 в 09 43 40
My response from service
Снимок экрана 2021-05-22 в 09 44 51

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.