openapistack / openapi-client-axios

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

Typescript error when loading openapi.json as a JSON object #186

Closed dennywright closed 4 months ago

dennywright commented 4 months ago

Good Day Viljami, Thank you very much for the openapi-stack. This is an amazing set of modules. I'm really impressed with how easy it is to get an API up an running.

That said, I need to bundle a standalone client. I'm using using NextJS (webpack). I'm using these instructions:

https://openapistack.co/docs/openapi-client-axios/bundling/

import { Client } from '@/lib/types/openapi';
import { OpenAPIClientAxios, Document } from 'openapi-client-axios';
import definition from '@/lib/types/openapi.json';

const apiClient = new OpenAPIClientAxios({ definition });

apiClient.init<Client>();

export default apiClient;

I'm getting the following typescript error:

src/lib/openAPIClient.ts(5,44): error TS2322: Type '{ openapi: string; info: { title: string; version: string; }; servers: { url: string; description: string; }[]; paths: { "/api/deviceInformation": { get: { operationId: string; responses: { "200": { description: string; content: { ...; }; }; }; }; }; ... 9 more ...; "/api/status/links": { ...; }; }; components: { .....' is not assignable to type 'string | Document'.

OpenAPIClientAxios is expecting definition to be 'Document | string' not the openapi object. I've tried JSON.stringify on the object, but it's not working. The client isn't making requests. What am I doing wrong?

anttiviljami commented 4 months ago

The object you’re passing seems to be an openapi definition object, but the types don’t seem to match.

You may want to run the document against some validator to see if your json contains errors.

The type error seems to suggest that something about your openapi document is invalid.

You can always just cast the object with as Document if the document is mostly valid.

dennywright commented 4 months ago

Hmm. I'm writing my openapi.yaml to openapi.json using openapicmd. Both validate using openapicmd. And I get the same error when I try to cast as Document. It looks like OpenAPIClientAxios() converts the openapi definition to the Document with loadDocument(), but I can't quite grok how it works. Need to look at it in detail.

I was able to get it to compile the Typescript using the stripped version:

npx openapicmd read --strip openapi_client_axios --format json openapi.json > openapi-runtime.json

I was concerned that I wouldn't have the type info in the client but that is coming from openapi.d.ts. So I think this will work.

Thanks Denny