acacode / acacode/swagger-typescript-api

[Feature request] Discriminated unions on status for error or success responses

Offen
#227 3 Kommentare 6 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
enhancement
Vorherrschende Sprache
TypeScript
Sterne
4.1k
Forks
436
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

How would the swagger-typescript-api team feel about having the `status` from the response as a typescript union discriminant where rest of the props would be defined based on its value?

For example, if the `swagger.json` file contains this for a given api call -

```json
"responses": {
"200": {
"description": "Resource is successfully created.",
"schema": { "$ref": "#/definitions/ResourceSuccessResponse" }
},
"400": {
"description": "Create resource request has invalid fields.",
"schema": { "$ref": "#/definitions/ErrorResponse" }
},
"401": {
"description": "Create resource request has invalid user credentials.",
"schema": { "$ref": "#/definitions/ErrorResponse" }
},
"409": {
"description": "Resource name already exists.",
"schema": { "$ref": "#/definitions/ErrorResponse" }
}
}
```

hypothetically the response could be of this format -

```ts
type HttpResponseType = {
status: Status,
data: ResponseData
}

type ResourceCreationResponse =
| HttpResponseType<200, ResourceSuccess>
| HttpResponseType<400, ErrorResponse>
| HttpResponseType<401, ErrorResponse>
| HttpResponseType<409, ErrorResponse>

type ResourceSuccess = {
resource: string
}

type ErrorResponse = {
code: number
message: string
}

declare const a: MyApiCallResponseType;

if(a.status === 200) {
console.log(a.data) // `a.data` is of type ResourceSuccess now
}
```

This could also be an option if not the default.

I would be willing to make a PR for this if this seems like a good idea. It definitely makes the resulting types stronger in my experience with slight flexibility cost.

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.