Skip to content

Option to export plain functions instead of classes with static methods #1191

Open
@philer-jambit

Description

@philer-jambit

Currently the generated API client consists of *Service classes which have a bunch of static methods to call the individual end points. This serves as a sort of name spacing, which is arguably already an anti pattern in JS/TS.

Instead it would be much preferable if the exports were plain functions. Instead of:

export class FooService {
    public static getFoo(...args: Args) {
        return __request(...args)
    }
}

that would just be:

export const getFoo = (...args: Args) => __request(...args)

If you are worried about name duplication you can import from the relevant files directly, such as

import * as fooService from '.../apiclient/services/fooService'

That said, the operationId from openapi.json is already meant to be unique, so there really should never be a case where naming collisions are possible.

Advantages of this approach include:

  • less code / more idiomatic (both in the generated code and the code that uses it)
  • allows tree shaking of unused end points – This is a big one. Consider using only one or two end points from an API that has dozens or even hundreds of end points that all fall into the same service – you may argue about the design choices there but APIs are not always defined by those who use them.
  • easy to mock individual imports in testing e.g. with jest

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions