GithubHelp home page GithubHelp logo

teobler / swr-request-generator Goto Github PK

View Code? Open in Web Editor NEW
41.0 2.0 9.0 748 KB

A tool for generating TypeScript code and interface from swagger by using SWR and axios as client.

Home Page: https://www.npmjs.com/package/@openapi-integration/swr-request-generator

License: MIT License

JavaScript 7.81% TypeScript 91.08% CSS 0.82% HTML 0.30%
swr swagger-codegen swagger-api api-integration code-generator typescript-generator

swr-request-generator's Introduction

swr-request-generator's People

Contributors

lorissikora avatar reeli avatar teobler 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

Watchers

 avatar  avatar

swr-request-generator's Issues

Example does not demonstrate use

I'd like to quote the READEME.md

how to use this file can be found in src/APP.tsx.

The use of the library/file is non-obviously included. At least, it is not in any of the dependencies of the file:

// https://raw.githubusercontent.com/teobler/swr-request-generator/main/example/src/App.tsx
import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {

The description implies one the following generated files is imported in the example project, but the current code does not include this.

  • example/src/request/api.ts
  • example/src/request/client.ts
  • example/src/request/useGetRequest.ts
  • example/src/request/useMutationRequest.ts

I would expect the example to demonstrate the use of the generated files.

[BUG] Reusable enums cause error

When defining an enum within the components/schemas section of the openapi schema, it results in a crash. One would do this as to reuse the enum or simply return an array of enum values inside a property. The reason for this crash is the following:

Given is the following schema:

openapi: 3.0.3
components:
  schemas:
    Example:
      type: object
      properties:
        nestedEnum:
          type: string
          enum:
            - A
            - B
            - C
    Fruit:
      type: string
      enum:
        - Apple
        - Orange
        - Pear

We have a nestedEnum which is defined within an additional schema, while the Fruit enum itself is a top-level schema. This will produce the following resolved definitions:

{
  'ExampleNestedEnum#EnumTypeSuffix': [ 'A', 'B', 'C' ],
  Example: { 'nestedEnum?': 'ExampleNestedEnum#EnumTypeSuffix' },
  'FruitFruit#EnumTypeSuffix': [ 'Apple', 'Orange', 'Pear' ],
  Fruit: 'FruitFruit#EnumTypeSuffix'
}

The problem here, I believe, is that Fruit is a schema and as such causes not only the FruitFruit#EnumTypeSuffix to be created, but also itself gets inserted as a regular schema into the resolved definitions. This is done by the DefinitionsResolver regardless of the type of schema. This later on causes an error when the resolver fails to do so. In addition to this, there seems to be a naming issue in this circumstance, as seen by the name FruitFruit#EnumTypeSuffix which results in an enum named FruitFruit.

I have formulated my proposed changes in a PR #8

Not everything is generated when using multiple endpoints

Hi,

Our backend generates two openapi.json files that we need to generate all the hooks necessary. When adding both of these to the clients array property only the data from the first json file gets converted to generated hooks, the data from the second file is nowhere to be found. If I use just one endpoint in the clients field I can generate it for both seperatly.

If anything is unclear please let me know. Thank you!

Generator cannot (?) handle wrapped data from API

Sometimes, API data is wrapped in an object, e.g. data, because errors and meta information would be on the same level. The Open API schema could look like this:

  '/user/profile-information':
    get:
      tags:
        - user
      summary: Returns information about the current authentication status and user
      operationId: userProfileInformation
      responses:
        '200':
          description: 'Success'
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/AuthenticationData'

And the AuthenticationData schema could look like this:

    AuthenticationData:
      type: object
      properties:
        csrfToken:
          type: string
        user:
          $ref: '#/components/schemas/User'
        ssoUrl:
          type: string
        impersonationDetails:
          $ref: '#/components/schemas/ImpersonationDetails'
      required:
        - csrfToken
        - user
        - ssoUrl
        - impersonationDetails

(etc.)

This is valid OpenAPI configuration, however the generator cannot handle this and will fail to generate the interfaces.

How could this be implemented in the package?

Add support for yaml

Would be really useful to supporto also yaml files for openapi specification, other than json

Notify error for missing OperationId

If in the OpenApi endpoint the operationId is missing, the related hook is called with the generic name "useRequest".
So, if multiple endpoints don't have an operationId, the result is corrupted because is trying to export multiple functions with the same name.
An error indicating the problem would be useful to understand what underlying problem is causing the error

[Proposal] remove rollup

this lib is just a script run in cli or npm script, rollup is too heave to this lib, using tsc is sufficient for our needs

[Feature request] Add support for the "default" response type

I'm currently generating an OpenAPI specification with the help of Apache CXF OpenAPI. This returns by default the following response object:

"responses" : {
          "default" : {
            "description" : "default response",
            "content" : {
              "application/json; charset=UTF-8" : {
                "schema" : {
                  "$ref" : "#/components/schemas/MyCustomDTO"
                }
              }
            }
          }
        }

I noticed that the generator only looks for the "200" response type, would it be possible to also add the "default" response type as a return type?

And another thing I noticed, is that the content./ wildcard is not working, I'm currently using a "application/json; charset=UTF-8" content type due to some special characters, but the wildcard is not catching this content type AFAIK.

AxiosResponse Inside AxiosResponse

This is maybe an error on my side.
But for some reason the result type of trigger is an AxiosResponse inside an AxiosResponse.

export function UserAuthForm({ className, ...props }: UserAuthFormProps) {
    const { trigger, isMutating } = useLoginForAccessTokenAuthPostRequest();
 
    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            username: "",
            password: "",
        },
    });

    async function onSubmit(values: z.infer<typeof formSchema>) {
        try {
            // According to the types this is a AxiosResponse<AxiosResponse<Token, any>, any> | undefined
            // But it is actually a AxiosResponse<Token, any> | undefined
            const result = await trigger({ body: { username: values.username, password: values.password } });

            if (!result) {
                throw new Error("No response");
            }
            console.dir(result);
            console.dir(result.data);
            // This does not work because the types are wrong
            const { access_token } = result.data.data;

This is my openAPI.json if you want to try
openAPI.txt

[Question] Example or guidance to modify headers with mutations?

Hi, thank you for this library! It's mostly working great for me so far in a Next.js project.

I'm looking to move some WIP code to v1, as it has some bug fixes we need and improvements that look really good.

My question is how best to deal with the move of mutations to hooks, given that our use case requires a custom and varying auth header (a captcha token which expires after 2 mins).

Before, we could pass in a custom Axios right before making a call. I'm struggling to work out how to do that "late" / right before the call with the new version because React hooks can't be called in a callback fn where I was invoking the request before โ€“ only at the top level of the functional component.

Do you have any ideas? If it should be simple, do you think it would be possible to add an example that includes something like this?

[Bug] Snake case query parameters are incorrectly camelCase'd in `use*Request()` params

I see a similar issue was fixed in v1.0.0 and this resolved a bug we were seeing.

However I've just stumbled on a similar one in v1.2.1 when a query param is snake_case. This one seems to actually break the TS compilation rather than only leading to misleading interface signatures.

A snippet of input JSON which leads to the problem (inside a request's parameters list):

                    {
                        "name": "location_id",
                        "in": "query",
                        "required": false,
                        "schema": {
                            "type": "integer"
                        }
                    },

And here's what we get:

Screenshot 2023-03-02 at 11 56 34

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.