openapistack / openapi-client-axios

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

Should I automatically see types when using JS? #78

Closed goldbergyoni closed 2 years ago

goldbergyoni commented 3 years ago

Great initiate here, thank you.

Question - I'm using JS and followed the docs, but can't see any types suggestion in vscode. Here what I've done:

const mailerAPI = new OpenAPIClientAxios({
    definition: path.join(__dirname, '../openapi.json'),
  });
  await mailerAPI.init();
  mailerAPI.{expected to see methods here but nothing from openapi operations appear here}

Should I run typegen manually? What is the workflow for JS scenario (not TS) given that most IDE knows to conclude d.ts file definitions even when coding with JS?

TomFrost commented 3 years ago

Hi @goldbergyoni -- I'm not the maintainer but I figured I'd answer since I just did this myself.

You do need to run typegen yourself, and store the file somewhere it's accessible to your source code.

Then your snippet becomes this:

import { Client as MyApiClient } from './path/to/generated/typefile'

const clientGenerator = new OpenAPIClientAxios({
  definition: path.join(__dirname, '../openapi.json'),
});
const mailerAPI = await clientGenerator.getClient<MyApiClient>();
mailerAPI.{now you see methods here}

The constructor for the main class can't be typed with your custom types, unfortunately. Even if you pass it when you call init(), that custom typing won't be saved that way. The answer is to keep a reference to the instance it returns, which is associated with your custom types.

getClient() is the better way to go than init(), though, because it still calls init under the hood for an instance that hasn't been initialized yet, but the returned instance is a singleton -- so if you ever call it again, you're getting the same object back without re-initializing.

Hope this helps!

npdev453 commented 2 years ago

@goldbergyoni, you should give a help to your hinting tool how to resolve client type.

Example using jsDoc:

pet.types is pet.types.d.ts that was generated by typegen tool example.js

import { OpenAPIClientAxios } from './openapi-client-axios'

/** @type {() => import("./pet.types").Client } **/
const getMyOACA = () => {
    const clientInstance = new OpenAPIClientAxios();
    return clientInstance;
}

const client = getMyOACA();
client.updatePetById()

and hints will work

image