openapistack / openapi-client-axios

JavaScript client library for consuming OpenAPI-enabled APIs with axios
https://openapistack.co
MIT License
558 stars 67 forks source link

baseURL not seems to be parsed from definition #61

Open patarapolw opened 3 years ago

patarapolw commented 3 years ago

Currently, I need this code. (Backend is fastify-swagger.)

import OpenAPIClientAxios from 'openapi-client-axios'

import { Client } from '../types/openapi'

export const apiURL =
  process.env.baseURL || `http://localhost:${process.env.SERVER_PORT}`

export const apiDefintionURL = `${apiURL}/api/doc/json`

export const apiClient = new OpenAPIClientAxios({
  definition: apiDefintionURL,
})

// eslint-disable-next-line import/no-mutable-exports
export let api: Client

export async function initAPI() {
  api = await apiClient.init<Client>()
  api.defaults.baseURL = apiURL
  return api
}

I did take a look at source as well; and operation.servers[0] or targetServer seems to be required, regardless of definition...

mrsolarius commented 3 years ago

I have the same issue. I hop that will be added automatically into the client. Here is what I need to do to use it :

    const api = new OpenAPIClientAxios({definition: 'https://ll.thespacedevs.com/2.0.0/swagger?format=openapi'});
    await api.init()
    const client = await api.getClient()
    client.defaults.baseURL = 'https://ll.thespacedevs.com/2.0.0/'
    const launch = await client.launch_list().catch(reason => {console.error(reason)})
    console.log(launch)

I expected that getClient() automatically add baseURL

anttiviljami commented 2 years ago

I'm confused here. What is the expected behaviour?

npdev453 commented 2 years ago

According OA spec https://swagger.io/docs/specification/api-host-and-base-path/ If you want to tell client to use other path (not from the other that frontend was loaded) Schema should contain servers options, and this library uses that rule and take a first server (or from withServer option) from servers if it provided.

Not always schema placed on the base_path of API, sometimes it could be another domain, or more deeply path, so there hard to found a universal rule for all.

@patarapolw in fastify-swagger you can describe that property for schema: (or find a way to generate dynamically) https://github.com/fastify/fastify-swagger/blob/master/examples/dynamic-openapi.js#L12