ngx-openapi-typescript 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# ngx-openapi-typescript
|
|
2
|
+
|
|
3
|
+
Type-safe Angular resource signals and HTTP client backed by [openapi-typescript](https://openapi-ts.dev/).
|
|
4
|
+
|
|
5
|
+
This library provides two main utilities:
|
|
6
|
+
|
|
7
|
+
- **`createOpenApiResource`** — a reactive factory built on Angular's `httpResource` that gives you compile-time type safety for every HTTP request and response shape defined in your OpenAPI schema.
|
|
8
|
+
- **`OpenApiHttpClient`** — a typed wrapper around Angular's `HttpClient` for imperative (non-reactive) HTTP calls.
|
|
9
|
+
|
|
10
|
+
Both are driven by the types generated by `openapi-typescript`, so typos in paths, wrong parameter names, or incorrect body shapes are caught at **compile time**, not at runtime.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install ngx-openapi-typescript openapi-typescript-helpers
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
This package is built for Angular `^21.2.0` and `^22.0.0` and expects these peer dependencies in your app:
|
|
19
|
+
|
|
20
|
+
- `@angular/common ^21.2.0 || ^22.0.0`
|
|
21
|
+
- `@angular/core ^21.2.0 || ^22.0.0`
|
|
22
|
+
- `openapi-typescript-helpers ^0.1.0`
|
|
23
|
+
|
|
24
|
+
If you want to generate types locally, also install the generator as a dev dependency:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npm install -D openapi-typescript
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Generating types
|
|
31
|
+
|
|
32
|
+
Generate type definitions by pointing `openapi-typescript` at your OpenAPI spec:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
npx openapi-typescript https://api.example.com/openapi.yaml -o src/api.types.ts
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
This creates a `paths` interface that both utilities consume.
|
|
39
|
+
|
|
40
|
+
## API
|
|
41
|
+
|
|
42
|
+
### `createOpenApiResource`
|
|
43
|
+
|
|
44
|
+
A factory for creating reactive Angular resource signals. Must be called inside an Angular injection context (component/service field initializer or constructor).
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import type { paths } from './api.types';
|
|
48
|
+
import { createOpenApiResource } from 'ngx-openapi-typescript';
|
|
49
|
+
|
|
50
|
+
@Component({ ... })
|
|
51
|
+
export class PetListComponent {
|
|
52
|
+
private readonly api = createOpenApiResource<paths>({
|
|
53
|
+
baseUrl: 'https://api.example.com',
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// Simple GET — no params required
|
|
57
|
+
protected readonly pets = this.api('/pets');
|
|
58
|
+
|
|
59
|
+
// Reactive GET with params — re-fetches when the signals read inside the lambda change
|
|
60
|
+
protected readonly petsLimited = this.api('/pets', () => ({
|
|
61
|
+
params: { query: { limit: 10 } },
|
|
62
|
+
}));
|
|
63
|
+
|
|
64
|
+
// Pass signal-driven path params — re-fetches when petId() changes
|
|
65
|
+
private readonly petId = signal(1);
|
|
66
|
+
protected readonly pet = this.api('/pets/{petId}', () => ({
|
|
67
|
+
params: { path: { petId: this.petId() } },
|
|
68
|
+
}));
|
|
69
|
+
|
|
70
|
+
// Return undefined to put the resource in Idle state (no request made)
|
|
71
|
+
private readonly enabled = signal(false);
|
|
72
|
+
protected readonly lazyPets = this.api('/pets', () =>
|
|
73
|
+
this.enabled() ? {} : undefined,
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
#### Method Override
|
|
79
|
+
|
|
80
|
+
The factory defaults to GET. You can pass a `method` option to use a different HTTP method,
|
|
81
|
+
but Angular recommends using `httpResource` only for reads. Prefer `OpenApiHttpClient` for mutations.
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
// Explicit method override (not recommended for production use)
|
|
85
|
+
protected readonly createResult = this.api('/pets', () => ({
|
|
86
|
+
body: { name: 'Buddy' },
|
|
87
|
+
}), { method: 'post' });
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### `OpenApiHttpClient`
|
|
91
|
+
|
|
92
|
+
A base class that wraps Angular's `HttpClient` with OpenAPI types. Ideal for imperative calls, mutations, or service-layer code.
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
import type { paths } from './api.types';
|
|
96
|
+
import { OpenApiHttpClient } from 'ngx-openapi-typescript';
|
|
97
|
+
import { Injectable } from '@angular/core';
|
|
98
|
+
|
|
99
|
+
@Injectable({ providedIn: 'root' })
|
|
100
|
+
export class PetApiClient extends OpenApiHttpClient<paths> {
|
|
101
|
+
constructor() {
|
|
102
|
+
super({ baseUrl: 'https://api.example.com' });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
// In a component/service
|
|
109
|
+
@Component({ ... })
|
|
110
|
+
export class PetDetailComponent {
|
|
111
|
+
private readonly api = inject(PetApiClient);
|
|
112
|
+
|
|
113
|
+
load(id: number) {
|
|
114
|
+
this.api
|
|
115
|
+
.get('/pets/{petId}', { params: { path: { petId: id } } })
|
|
116
|
+
.subscribe(pet => console.log(pet)); // pet is typed as Pet
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
create(name: string) {
|
|
120
|
+
this.api
|
|
121
|
+
.post('/pets', { body: { name } })
|
|
122
|
+
.subscribe(newPet => console.log(newPet));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
#### Custom HTTP client
|
|
128
|
+
|
|
129
|
+
By default, `OpenApiHttpClient` injects Angular's configured `HttpClient` and uses
|
|
130
|
+
its interceptors. If you need a second API client with a differently configured
|
|
131
|
+
`HttpClient`, pass that instance through the `httpClient` option. Both clients
|
|
132
|
+
retain the same generated endpoint, parameter, body, and response types.
|
|
133
|
+
|
|
134
|
+
For example, inside an Angular injection context:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import { HttpBackend, HttpClient } from '@angular/common/http';
|
|
138
|
+
import { inject } from '@angular/core';
|
|
139
|
+
import { OpenApiHttpClient } from 'ngx-openapi-typescript';
|
|
140
|
+
import type { paths } from './api.types';
|
|
141
|
+
|
|
142
|
+
// Uses Angular's default HttpClient; requires an injection context.
|
|
143
|
+
const api = new OpenApiHttpClient<paths>({
|
|
144
|
+
baseUrl: 'https://api.example.com',
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
// Uses a separate HttpClient instance.
|
|
148
|
+
const secondApi = new OpenApiHttpClient<paths>({
|
|
149
|
+
baseUrl: 'https://second-api.example.com',
|
|
150
|
+
httpClient: new HttpClient(inject(HttpBackend)),
|
|
151
|
+
});
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
When you supply an existing `HttpClient` instance, `OpenApiHttpClient` can also be
|
|
155
|
+
constructed outside an Angular injection context. The example above requires one
|
|
156
|
+
because it calls `inject(HttpBackend)`.
|
|
157
|
+
|
|
158
|
+
`createOpenApiResource` cannot accept a custom `HttpClient`, because Angular's
|
|
159
|
+
underlying `httpResource` does not offer this option. See
|
|
160
|
+
[Angular issue #62616](https://github.com/angular/angular/issues/62616).
|
|
161
|
+
|
|
162
|
+
## Development
|
|
163
|
+
|
|
164
|
+
```sh
|
|
165
|
+
# Build the library
|
|
166
|
+
ng build ngx-openapi-typescript
|
|
167
|
+
|
|
168
|
+
# Run tests
|
|
169
|
+
ng test ngx-openapi-typescript
|
|
170
|
+
|
|
171
|
+
# Start the demo app
|
|
172
|
+
ng serve demo
|
|
173
|
+
```
|
|
@@ -109,6 +109,10 @@ function buildOptions(r) {
|
|
|
109
109
|
* Wraps Angular's `HttpClient` and binds request/response types to an OpenAPI
|
|
110
110
|
* schema generated by `openapi-typescript`.
|
|
111
111
|
*
|
|
112
|
+
* By default, injects Angular's configured `HttpClient`, requiring an injection
|
|
113
|
+
* context. Supplying `config.httpClient` uses that instance without injection,
|
|
114
|
+
* so construction outside an injection context is supported.
|
|
115
|
+
*
|
|
112
116
|
* Designed to be subclassed per-API:
|
|
113
117
|
*
|
|
114
118
|
* @example
|
|
@@ -131,9 +135,10 @@ function buildOptions(r) {
|
|
|
131
135
|
* ```
|
|
132
136
|
*/
|
|
133
137
|
class OpenApiHttpClient {
|
|
134
|
-
http
|
|
138
|
+
http;
|
|
135
139
|
baseUrl;
|
|
136
140
|
constructor(config) {
|
|
141
|
+
this.http = config?.httpClient ?? inject(HttpClient);
|
|
137
142
|
this.baseUrl = config?.baseUrl ?? '';
|
|
138
143
|
}
|
|
139
144
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ngx-openapi-typescript.mjs","sources":["../../../projects/ngx-openapi-typescript/src/lib/url-utils.ts","../../../projects/ngx-openapi-typescript/src/lib/open-api-resource.ts","../../../projects/ngx-openapi-typescript/src/lib/open-api-http-client.ts","../../../projects/ngx-openapi-typescript/src/public-api.ts","../../../projects/ngx-openapi-typescript/src/ngx-openapi-typescript.ts"],"sourcesContent":["import { HttpParams } from '@angular/common/http';\n\n/** Builds a full URL by substituting path parameters into the path template */\nexport function buildUrl(\n baseUrl: string,\n path: string,\n pathParams?: Record<string, string | number | boolean>,\n): string {\n let url = baseUrl + path;\n if (pathParams) {\n for (const [key, value] of Object.entries(pathParams)) {\n url = url.replace(`{${key}}`, encodeURIComponent(String(value)));\n }\n }\n return url;\n}\n\n/** Converts a query parameter map to an `HttpParams` instance */\nexport function toHttpParams(\n query?: Record<\n string,\n string | number | boolean | ReadonlyArray<string | number | boolean> | null | undefined\n >,\n): HttpParams | undefined {\n if (!query) return undefined;\n let params = new HttpParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const v of value) {\n params = params.append(key, String(v));\n }\n } else {\n params = params.set(key, String(value));\n }\n }\n return params;\n}\n","import {\n HttpContext,\n HttpHeaders,\n HttpResourceOptions,\n HttpResourceRef,\n httpResource,\n} from '@angular/common/http';\nimport type { PathsWithMethod, SuccessResponseJSON } from 'openapi-typescript-helpers';\nimport type { HasRequiredKeys, HttpMethod, OpenApiOperationRequest, PathRecord } from './types';\nimport { buildUrl as _buildUrl, toHttpParams as _toHttpParams } from './url-utils';\n\n// Re-export helpers so consumers and tests can import them from this module.\nexport { buildUrl, toHttpParams } from './url-utils';\n\n/** Configuration for creating an OpenAPI resource factory */\nexport interface OpenApiResourceConfig {\n /** Base URL to prepend to all resource paths */\n baseUrl?: string;\n}\n\n/** Options for the resource call, extending Angular's HttpResourceOptions with an optional HTTP method */\nexport type OpenApiResourceCallOptions<TValue, TError = unknown> = HttpResourceOptions<\n TValue,\n TError\n> & { method?: HttpMethod };\n\n/** Extracts the operation type for a given path and method */\ntype OpOf<Paths, Path extends keyof Paths, Method extends string> = Paths[Path] extends {\n [K in Method]: infer Op;\n}\n ? Op\n : never;\n\n/** Coerces the request object to a plain shape for URL building */\nfunction toRequestShape(req: unknown): {\n params?: {\n path?: Record<string, string | number | boolean>;\n query?: Record<string, string | number | boolean | null | undefined>;\n };\n body?: unknown;\n headers?: HttpHeaders | Record<string, string | ReadonlyArray<string>>;\n context?: HttpContext;\n withCredentials?: boolean;\n} {\n return ((req ?? {}) as ReturnType<typeof toRequestShape>);\n}\n\n/** Extract which HTTP methods a given path supports */\ntype MethodsOfPath<Paths, Path extends keyof Paths> = {\n [M in HttpMethod]: Paths[Path] extends { [K in M]: unknown } ? M : never;\n}[HttpMethod];\n\n/**\n * Narrows to only those paths (for the given method) where the full request object\n * has no required keys — i.e. `requestFn` can be safely omitted.\n */\ntype PathsWithOptionalRequest<Paths extends PathRecord, Method extends HttpMethod> = {\n [P in PathsWithMethod<Paths, Method> & keyof Paths]: HasRequiredKeys<\n OpenApiOperationRequest<NonNullable<OpOf<Paths, P, Method>>>\n > extends true\n ? never\n : P;\n}[PathsWithMethod<Paths, Method> & keyof Paths];\n\n/** The callable type returned by `createOpenApiResource` */\nexport interface OpenApiResource<Paths extends PathRecord> {\n /**\n * Creates a reactive resource for an OpenAPI endpoint with an explicit HTTP method.\n *\n * The `method` option is restricted to the methods the given path supports.\n */\n <Path extends keyof Paths & string, Method extends MethodsOfPath<Paths, Path>>(\n path: Path,\n requestFn: () => OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, Method>>> | undefined,\n options: OpenApiResourceCallOptions<\n SuccessResponseJSON<NonNullable<OpOf<Paths, Path, Method>>>,\n unknown\n > & { method: Method },\n ): HttpResourceRef<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, Method>>> | undefined>;\n\n /**\n * Creates a reactive GET resource for an OpenAPI endpoint (default).\n *\n * The resource re-fetches automatically when the signals read inside `requestFn` change.\n * When `requestFn` returns `undefined` the resource is put into the Idle state.\n */\n <Path extends PathsWithMethod<Paths, 'get'> & keyof Paths>(\n path: Path,\n requestFn: () => OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'get'>>> | undefined,\n options?: HttpResourceOptions<\n SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>>,\n unknown\n >,\n ): HttpResourceRef<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>> | undefined>;\n\n /**\n * Creates a reactive resource for an OpenAPI endpoint with an explicit HTTP method,\n * omitting `requestFn`. Only available when the operation has no required parameters or body.\n */\n <Path extends keyof Paths & string, Method extends MethodsOfPath<Paths, Path>>(\n path: Path extends PathsWithOptionalRequest<Paths, Method> ? Path : never,\n options: OpenApiResourceCallOptions<\n SuccessResponseJSON<NonNullable<OpOf<Paths, Path, Method>>>,\n unknown\n > & { method: Method },\n ): HttpResourceRef<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, Method>>> | undefined>;\n\n /**\n * Creates a reactive GET resource for an OpenAPI endpoint, omitting `requestFn`.\n * Only available when the operation has no required parameters or body.\n * The resource fetches immediately and always stays active.\n */\n <Path extends PathsWithOptionalRequest<Paths, 'get'>>(\n path: Path,\n options?: HttpResourceOptions<\n SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>>,\n unknown\n >,\n ): HttpResourceRef<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>> | undefined>;\n}\n\n/**\n * Creates a type-safe callable factory for Angular `httpResource`s backed by an OpenAPI schema.\n *\n * Must be called inside an Angular injection context (e.g. component/service field initializer\n * or constructor), because the returned function uses `httpResource` internally.\n *\n * The returned function defaults to GET. Pass `{ method: 'post' }` (or other method) in the\n * options to use a different HTTP method. Note: Angular recommends using `httpResource` only\n * for reads; prefer `OpenApiHttpClient` for mutations.\n *\n * @example\n * ```ts\n * import type { paths } from './api.types'; // generated by openapi-typescript\n *\n * const api = createOpenApiResource<paths>({ baseUrl: 'https://api.example.com' });\n *\n * // Reactive GET resource (default)\n * const pets = api('/pets', () => ({ params: { query: { limit: 10 } } }));\n *\n * // GET with path params (signal-driven)\n * const petId = signal(1);\n * const pet = api('/pets/{petId}', () => ({ params: { path: { petId: petId() } } }));\n *\n * // Explicit method override (prefer OpenApiHttpClient for mutations)\n * const created = api('/pets', () => ({ body: { name: 'Buddy' } }), { method: 'post' });\n * ```\n */\nexport function createOpenApiResource<Paths extends PathRecord>(\n config?: OpenApiResourceConfig,\n): OpenApiResource<Paths> {\n const baseUrl = config?.baseUrl ?? '';\n\n return ((\n path: string,\n reqFnOrOpts?: (() => unknown) | OpenApiResourceCallOptions<unknown>,\n maybeOpts?: OpenApiResourceCallOptions<unknown>,\n ) => {\n const hasRequestFn = typeof reqFnOrOpts === 'function';\n const requestFn = hasRequestFn ? reqFnOrOpts : () => ({});\n const options = hasRequestFn ? maybeOpts : (reqFnOrOpts as OpenApiResourceCallOptions<unknown> | undefined);\n const method = (options?.method ?? 'get').toUpperCase();\n\n return httpResource(\n () => {\n const req = requestFn();\n if (req === undefined) return undefined;\n const r = toRequestShape(req);\n return {\n url: _buildUrl(baseUrl, path, r.params?.path),\n method,\n body: r.body,\n params: _toHttpParams(r.params?.query),\n headers: r.headers,\n context: r.context,\n withCredentials: r.withCredentials,\n };\n },\n options,\n );\n }) as OpenApiResource<Paths>;\n}\n","import { HttpClient, HttpContext, HttpHeaders, HttpParams } from '@angular/common/http';\nimport { inject } from '@angular/core';\nimport type { Observable } from 'rxjs';\nimport type {\n PathsWithMethod,\n RequestBodyJSON,\n SuccessResponseJSON,\n} from 'openapi-typescript-helpers';\nimport type {\n OpenApiOperationRequest,\n PathRecord,\n} from './types';\nimport { buildUrl, toHttpParams } from './url-utils';\n\n/** Configuration for `OpenApiHttpClient` */\nexport interface OpenApiHttpClientConfig {\n /** Base URL to prepend to all request paths */\n baseUrl?: string;\n}\n\n/** Extracts the operation type for a given path and method */\ntype OpOf<Paths, Path extends keyof Paths, Method extends string> = Paths[Path] extends {\n [K in Method]: infer Op;\n}\n ? Op\n : never;\n\n/** Coerces the options to a plain shape */\nfunction toShape(opts: unknown): {\n params?: {\n path?: Record<string, string | number | boolean>;\n query?: Record<string, string | number | boolean | null | undefined>;\n };\n body?: unknown;\n headers?: HttpHeaders | Record<string, string | ReadonlyArray<string>>;\n context?: HttpContext;\n withCredentials?: boolean;\n} {\n return ((opts ?? {}) as ReturnType<typeof toShape>);\n}\n\nfunction buildOptions(r: ReturnType<typeof toShape>): {\n responseType: 'json';\n observe: 'body';\n params?: HttpParams;\n headers?: HttpHeaders | Record<string, string | string[]>;\n context?: HttpContext;\n withCredentials?: boolean;\n} {\n return {\n responseType: 'json',\n observe: 'body',\n params: toHttpParams(r.params?.query),\n // Cast needed: our public API allows ReadonlyArray<string> (consistent with httpResource),\n // but Angular HttpClient methods require string[].\n headers: r.headers as HttpHeaders | Record<string, string | string[]> | undefined,\n context: r.context,\n withCredentials: r.withCredentials,\n };\n}\n\n/**\n * A type-safe HTTP client for OpenAPI-described APIs.\n *\n * Wraps Angular's `HttpClient` and binds request/response types to an OpenAPI\n * schema generated by `openapi-typescript`.\n *\n * Designed to be subclassed per-API:\n *\n * @example\n * ```ts\n * import type { paths } from './api.types'; // generated by openapi-typescript\n *\n * @Injectable({ providedIn: 'root' })\n * export class PetApiClient extends OpenApiHttpClient<paths> {\n * constructor() {\n * super({ baseUrl: 'https://api.example.com' });\n * }\n * }\n * ```\n *\n * Or used directly inside an injection context:\n *\n * @example\n * ```ts\n * const client = new OpenApiHttpClient<paths>({ baseUrl: 'https://api.example.com' });\n * ```\n */\nexport class OpenApiHttpClient<Paths extends PathRecord> {\n private readonly http = inject(HttpClient);\n private readonly baseUrl: string;\n\n constructor(config?: OpenApiHttpClientConfig) {\n this.baseUrl = config?.baseUrl ?? '';\n }\n\n /**\n * Performs a typed GET request.\n *\n * @example\n * ```ts\n * client.get('/pets', { params: { query: { limit: 10 } } }).subscribe(pets => console.log(pets));\n * ```\n */\n get<Path extends PathsWithMethod<Paths, 'get'> & keyof Paths>(\n path: Path,\n options?: OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'get'>>>,\n ): Observable<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>>> {\n const r = toShape(options);\n return this.http.get<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>>>(\n buildUrl(this.baseUrl, String(path), r.params?.path),\n buildOptions(r),\n );\n }\n\n /**\n * Performs a typed POST request.\n */\n post<Path extends PathsWithMethod<Paths, 'post'> & keyof Paths>(\n path: Path,\n options?: OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'post'>>>,\n ): Observable<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'post'>>>> {\n const r = toShape(options);\n return this.http.post<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'post'>>>>(\n buildUrl(this.baseUrl, String(path), r.params?.path),\n r.body as RequestBodyJSON<NonNullable<OpOf<Paths, Path, 'post'>>>,\n buildOptions(r),\n );\n }\n\n /**\n * Performs a typed PUT request.\n */\n put<Path extends PathsWithMethod<Paths, 'put'> & keyof Paths>(\n path: Path,\n options?: OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'put'>>>,\n ): Observable<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'put'>>>> {\n const r = toShape(options);\n return this.http.put<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'put'>>>>(\n buildUrl(this.baseUrl, String(path), r.params?.path),\n r.body as RequestBodyJSON<NonNullable<OpOf<Paths, Path, 'put'>>>,\n buildOptions(r),\n );\n }\n\n /**\n * Performs a typed PATCH request.\n */\n patch<Path extends PathsWithMethod<Paths, 'patch'> & keyof Paths>(\n path: Path,\n options?: OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'patch'>>>,\n ): Observable<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'patch'>>>> {\n const r = toShape(options);\n return this.http.patch<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'patch'>>>>(\n buildUrl(this.baseUrl, String(path), r.params?.path),\n r.body as RequestBodyJSON<NonNullable<OpOf<Paths, Path, 'patch'>>>,\n buildOptions(r),\n );\n }\n\n /**\n * Performs a typed DELETE request.\n */\n delete<Path extends PathsWithMethod<Paths, 'delete'> & keyof Paths>(\n path: Path,\n options?: OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'delete'>>>,\n ): Observable<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'delete'>>>> {\n const r = toShape(options);\n const httpOptions = buildOptions(r) as { body?: unknown } & ReturnType<typeof buildOptions>;\n\n if (r.body !== undefined) {\n httpOptions.body = r.body as RequestBodyJSON<NonNullable<OpOf<Paths, Path, 'delete'>>>;\n }\n\n return this.http.delete<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'delete'>>>>(\n buildUrl(this.baseUrl, String(path), r.params?.path),\n httpOptions,\n );\n }\n}\n","/*\n * Public API Surface of ngx-openapi-typescript\n */\n\nexport { createOpenApiResource } from './lib/open-api-resource';\nexport type {\n OpenApiResource, OpenApiResourceCallOptions, OpenApiResourceConfig\n} from './lib/open-api-resource';\n\nexport { OpenApiHttpClient } from './lib/open-api-http-client';\nexport type { OpenApiHttpClientConfig } from './lib/open-api-http-client';\n\nexport type {\n HasRequiredKeys,\n HttpMethod, OpenApiOperationRequest,\n OpenApiRequestOptions, OperationBody, OperationParamsObject, PathParameters, PathRecord, PathsWithMethod, QueryParameters, RequestBodyJSON, SuccessResponseJSON\n} from './lib/types';\n\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["_buildUrl","_toHttpParams"],"mappings":";;;AAEA;SACgB,QAAQ,CACtB,OAAe,EACf,IAAY,EACZ,UAAsD,EAAA;AAEtD,IAAA,IAAI,GAAG,GAAG,OAAO,GAAG,IAAI;IACxB,IAAI,UAAU,EAAE;AACd,QAAA,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE;AACrD,YAAA,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,IAAI,GAAG,CAAA,CAAA,CAAG,EAAE,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QAClE;IACF;AACA,IAAA,OAAO,GAAG;AACZ;AAEA;AACM,SAAU,YAAY,CAC1B,KAGC,EAAA;AAED,IAAA,IAAI,CAAC,KAAK;AAAE,QAAA,OAAO,SAAS;AAC5B,IAAA,IAAI,MAAM,GAAG,IAAI,UAAU,EAAE;AAC7B,IAAA,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AAChD,QAAA,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI;YAAE;AAC3C,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACxB,YAAA,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE;AACrB,gBAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;YACxC;QACF;aAAO;AACL,YAAA,MAAM,GAAG,MAAM,CAAC,G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":["../../../projects/ngx-openapi-typescript/src/lib/url-utils.ts","../../../projects/ngx-openapi-typescript/src/lib/open-api-resource.ts","../../../projects/ngx-openapi-typescript/src/lib/open-api-http-client.ts","../../../projects/ngx-openapi-typescript/src/public-api.ts","../../../projects/ngx-openapi-typescript/src/ngx-openapi-typescript.ts"],"sourcesContent":["import { HttpParams } from '@angular/common/http';\n\n/** Builds a full URL by substituting path parameters into the path template */\nexport function buildUrl(\n baseUrl: string,\n path: string,\n pathParams?: Record<string, string | number | boolean>,\n): string {\n let url = baseUrl + path;\n if (pathParams) {\n for (const [key, value] of Object.entries(pathParams)) {\n url = url.replace(`{${key}}`, encodeURIComponent(String(value)));\n }\n }\n return url;\n}\n\n/** Converts a query parameter map to an `HttpParams` instance */\nexport function toHttpParams(\n query?: Record<\n string,\n string | number | boolean | ReadonlyArray<string | number | boolean> | null | undefined\n >,\n): HttpParams | undefined {\n if (!query) return undefined;\n let params = new HttpParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const v of value) {\n params = params.append(key, String(v));\n }\n } else {\n params = params.set(key, String(value));\n }\n }\n return params;\n}\n","import {\n HttpContext,\n HttpHeaders,\n HttpResourceOptions,\n HttpResourceRef,\n httpResource,\n} from '@angular/common/http';\nimport type { PathsWithMethod, SuccessResponseJSON } from 'openapi-typescript-helpers';\nimport type { HasRequiredKeys, HttpMethod, OpenApiOperationRequest, PathRecord } from './types';\nimport { buildUrl as _buildUrl, toHttpParams as _toHttpParams } from './url-utils';\n\n// Re-export helpers so consumers and tests can import them from this module.\nexport { buildUrl, toHttpParams } from './url-utils';\n\n/** Configuration for creating an OpenAPI resource factory */\nexport interface OpenApiResourceConfig {\n /** Base URL to prepend to all resource paths */\n baseUrl?: string;\n}\n\n/** Options for the resource call, extending Angular's HttpResourceOptions with an optional HTTP method */\nexport type OpenApiResourceCallOptions<TValue, TError = unknown> = HttpResourceOptions<\n TValue,\n TError\n> & { method?: HttpMethod };\n\n/** Extracts the operation type for a given path and method */\ntype OpOf<Paths, Path extends keyof Paths, Method extends string> = Paths[Path] extends {\n [K in Method]: infer Op;\n}\n ? Op\n : never;\n\n/** Coerces the request object to a plain shape for URL building */\nfunction toRequestShape(req: unknown): {\n params?: {\n path?: Record<string, string | number | boolean>;\n query?: Record<string, string | number | boolean | null | undefined>;\n };\n body?: unknown;\n headers?: HttpHeaders | Record<string, string | ReadonlyArray<string>>;\n context?: HttpContext;\n withCredentials?: boolean;\n} {\n return ((req ?? {}) as ReturnType<typeof toRequestShape>);\n}\n\n/** Extract which HTTP methods a given path supports */\ntype MethodsOfPath<Paths, Path extends keyof Paths> = {\n [M in HttpMethod]: Paths[Path] extends { [K in M]: unknown } ? M : never;\n}[HttpMethod];\n\n/**\n * Narrows to only those paths (for the given method) where the full request object\n * has no required keys — i.e. `requestFn` can be safely omitted.\n */\ntype PathsWithOptionalRequest<Paths extends PathRecord, Method extends HttpMethod> = {\n [P in PathsWithMethod<Paths, Method> & keyof Paths]: HasRequiredKeys<\n OpenApiOperationRequest<NonNullable<OpOf<Paths, P, Method>>>\n > extends true\n ? never\n : P;\n}[PathsWithMethod<Paths, Method> & keyof Paths];\n\n/** The callable type returned by `createOpenApiResource` */\nexport interface OpenApiResource<Paths extends PathRecord> {\n /**\n * Creates a reactive resource for an OpenAPI endpoint with an explicit HTTP method.\n *\n * The `method` option is restricted to the methods the given path supports.\n */\n <Path extends keyof Paths & string, Method extends MethodsOfPath<Paths, Path>>(\n path: Path,\n requestFn: () => OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, Method>>> | undefined,\n options: OpenApiResourceCallOptions<\n SuccessResponseJSON<NonNullable<OpOf<Paths, Path, Method>>>,\n unknown\n > & { method: Method },\n ): HttpResourceRef<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, Method>>> | undefined>;\n\n /**\n * Creates a reactive GET resource for an OpenAPI endpoint (default).\n *\n * The resource re-fetches automatically when the signals read inside `requestFn` change.\n * When `requestFn` returns `undefined` the resource is put into the Idle state.\n */\n <Path extends PathsWithMethod<Paths, 'get'> & keyof Paths>(\n path: Path,\n requestFn: () => OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'get'>>> | undefined,\n options?: HttpResourceOptions<\n SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>>,\n unknown\n >,\n ): HttpResourceRef<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>> | undefined>;\n\n /**\n * Creates a reactive resource for an OpenAPI endpoint with an explicit HTTP method,\n * omitting `requestFn`. Only available when the operation has no required parameters or body.\n */\n <Path extends keyof Paths & string, Method extends MethodsOfPath<Paths, Path>>(\n path: Path extends PathsWithOptionalRequest<Paths, Method> ? Path : never,\n options: OpenApiResourceCallOptions<\n SuccessResponseJSON<NonNullable<OpOf<Paths, Path, Method>>>,\n unknown\n > & { method: Method },\n ): HttpResourceRef<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, Method>>> | undefined>;\n\n /**\n * Creates a reactive GET resource for an OpenAPI endpoint, omitting `requestFn`.\n * Only available when the operation has no required parameters or body.\n * The resource fetches immediately and always stays active.\n */\n <Path extends PathsWithOptionalRequest<Paths, 'get'>>(\n path: Path,\n options?: HttpResourceOptions<\n SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>>,\n unknown\n >,\n ): HttpResourceRef<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>> | undefined>;\n}\n\n/**\n * Creates a type-safe callable factory for Angular `httpResource`s backed by an OpenAPI schema.\n *\n * Must be called inside an Angular injection context (e.g. component/service field initializer\n * or constructor), because the returned function uses `httpResource` internally.\n *\n * The returned function defaults to GET. Pass `{ method: 'post' }` (or other method) in the\n * options to use a different HTTP method. Note: Angular recommends using `httpResource` only\n * for reads; prefer `OpenApiHttpClient` for mutations.\n *\n * @example\n * ```ts\n * import type { paths } from './api.types'; // generated by openapi-typescript\n *\n * const api = createOpenApiResource<paths>({ baseUrl: 'https://api.example.com' });\n *\n * // Reactive GET resource (default)\n * const pets = api('/pets', () => ({ params: { query: { limit: 10 } } }));\n *\n * // GET with path params (signal-driven)\n * const petId = signal(1);\n * const pet = api('/pets/{petId}', () => ({ params: { path: { petId: petId() } } }));\n *\n * // Explicit method override (prefer OpenApiHttpClient for mutations)\n * const created = api('/pets', () => ({ body: { name: 'Buddy' } }), { method: 'post' });\n * ```\n */\nexport function createOpenApiResource<Paths extends PathRecord>(\n config?: OpenApiResourceConfig,\n): OpenApiResource<Paths> {\n const baseUrl = config?.baseUrl ?? '';\n\n return ((\n path: string,\n reqFnOrOpts?: (() => unknown) | OpenApiResourceCallOptions<unknown>,\n maybeOpts?: OpenApiResourceCallOptions<unknown>,\n ) => {\n const hasRequestFn = typeof reqFnOrOpts === 'function';\n const requestFn = hasRequestFn ? reqFnOrOpts : () => ({});\n const options = hasRequestFn ? maybeOpts : (reqFnOrOpts as OpenApiResourceCallOptions<unknown> | undefined);\n const method = (options?.method ?? 'get').toUpperCase();\n\n return httpResource(\n () => {\n const req = requestFn();\n if (req === undefined) return undefined;\n const r = toRequestShape(req);\n return {\n url: _buildUrl(baseUrl, path, r.params?.path),\n method,\n body: r.body,\n params: _toHttpParams(r.params?.query),\n headers: r.headers,\n context: r.context,\n withCredentials: r.withCredentials,\n };\n },\n options,\n );\n }) as OpenApiResource<Paths>;\n}\n","import { HttpClient, HttpContext, HttpHeaders, HttpParams } from '@angular/common/http';\nimport { inject } from '@angular/core';\nimport type { Observable } from 'rxjs';\nimport type {\n PathsWithMethod,\n RequestBodyJSON,\n SuccessResponseJSON,\n} from 'openapi-typescript-helpers';\nimport type {\n OpenApiOperationRequest,\n PathRecord,\n} from './types';\nimport { buildUrl, toHttpParams } from './url-utils';\n\n/** Configuration for `OpenApiHttpClient` */\nexport interface OpenApiHttpClientConfig {\n /** Base URL to prepend to all request paths */\n baseUrl?: string;\n /** HTTP client to use instead of injecting Angular's configured HttpClient. */\n httpClient?: HttpClient;\n}\n\n/** Extracts the operation type for a given path and method */\ntype OpOf<Paths, Path extends keyof Paths, Method extends string> = Paths[Path] extends {\n [K in Method]: infer Op;\n}\n ? Op\n : never;\n\n/** Coerces the options to a plain shape */\nfunction toShape(opts: unknown): {\n params?: {\n path?: Record<string, string | number | boolean>;\n query?: Record<string, string | number | boolean | null | undefined>;\n };\n body?: unknown;\n headers?: HttpHeaders | Record<string, string | ReadonlyArray<string>>;\n context?: HttpContext;\n withCredentials?: boolean;\n} {\n return ((opts ?? {}) as ReturnType<typeof toShape>);\n}\n\nfunction buildOptions(r: ReturnType<typeof toShape>): {\n responseType: 'json';\n observe: 'body';\n params?: HttpParams;\n headers?: HttpHeaders | Record<string, string | string[]>;\n context?: HttpContext;\n withCredentials?: boolean;\n} {\n return {\n responseType: 'json',\n observe: 'body',\n params: toHttpParams(r.params?.query),\n // Cast needed: our public API allows ReadonlyArray<string> (consistent with httpResource),\n // but Angular HttpClient methods require string[].\n headers: r.headers as HttpHeaders | Record<string, string | string[]> | undefined,\n context: r.context,\n withCredentials: r.withCredentials,\n };\n}\n\n/**\n * A type-safe HTTP client for OpenAPI-described APIs.\n *\n * Wraps Angular's `HttpClient` and binds request/response types to an OpenAPI\n * schema generated by `openapi-typescript`.\n *\n * By default, injects Angular's configured `HttpClient`, requiring an injection\n * context. Supplying `config.httpClient` uses that instance without injection,\n * so construction outside an injection context is supported.\n *\n * Designed to be subclassed per-API:\n *\n * @example\n * ```ts\n * import type { paths } from './api.types'; // generated by openapi-typescript\n *\n * @Injectable({ providedIn: 'root' })\n * export class PetApiClient extends OpenApiHttpClient<paths> {\n * constructor() {\n * super({ baseUrl: 'https://api.example.com' });\n * }\n * }\n * ```\n *\n * Or used directly inside an injection context:\n *\n * @example\n * ```ts\n * const client = new OpenApiHttpClient<paths>({ baseUrl: 'https://api.example.com' });\n * ```\n */\nexport class OpenApiHttpClient<Paths extends PathRecord> {\n private readonly http: HttpClient;\n private readonly baseUrl: string;\n\n constructor(config?: OpenApiHttpClientConfig) {\n this.http = config?.httpClient ?? inject(HttpClient);\n this.baseUrl = config?.baseUrl ?? '';\n }\n\n /**\n * Performs a typed GET request.\n *\n * @example\n * ```ts\n * client.get('/pets', { params: { query: { limit: 10 } } }).subscribe(pets => console.log(pets));\n * ```\n */\n get<Path extends PathsWithMethod<Paths, 'get'> & keyof Paths>(\n path: Path,\n options?: OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'get'>>>,\n ): Observable<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>>> {\n const r = toShape(options);\n return this.http.get<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'get'>>>>(\n buildUrl(this.baseUrl, String(path), r.params?.path),\n buildOptions(r),\n );\n }\n\n /**\n * Performs a typed POST request.\n */\n post<Path extends PathsWithMethod<Paths, 'post'> & keyof Paths>(\n path: Path,\n options?: OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'post'>>>,\n ): Observable<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'post'>>>> {\n const r = toShape(options);\n return this.http.post<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'post'>>>>(\n buildUrl(this.baseUrl, String(path), r.params?.path),\n r.body as RequestBodyJSON<NonNullable<OpOf<Paths, Path, 'post'>>>,\n buildOptions(r),\n );\n }\n\n /**\n * Performs a typed PUT request.\n */\n put<Path extends PathsWithMethod<Paths, 'put'> & keyof Paths>(\n path: Path,\n options?: OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'put'>>>,\n ): Observable<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'put'>>>> {\n const r = toShape(options);\n return this.http.put<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'put'>>>>(\n buildUrl(this.baseUrl, String(path), r.params?.path),\n r.body as RequestBodyJSON<NonNullable<OpOf<Paths, Path, 'put'>>>,\n buildOptions(r),\n );\n }\n\n /**\n * Performs a typed PATCH request.\n */\n patch<Path extends PathsWithMethod<Paths, 'patch'> & keyof Paths>(\n path: Path,\n options?: OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'patch'>>>,\n ): Observable<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'patch'>>>> {\n const r = toShape(options);\n return this.http.patch<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'patch'>>>>(\n buildUrl(this.baseUrl, String(path), r.params?.path),\n r.body as RequestBodyJSON<NonNullable<OpOf<Paths, Path, 'patch'>>>,\n buildOptions(r),\n );\n }\n\n /**\n * Performs a typed DELETE request.\n */\n delete<Path extends PathsWithMethod<Paths, 'delete'> & keyof Paths>(\n path: Path,\n options?: OpenApiOperationRequest<NonNullable<OpOf<Paths, Path, 'delete'>>>,\n ): Observable<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'delete'>>>> {\n const r = toShape(options);\n const httpOptions = buildOptions(r) as { body?: unknown } & ReturnType<typeof buildOptions>;\n\n if (r.body !== undefined) {\n httpOptions.body = r.body as RequestBodyJSON<NonNullable<OpOf<Paths, Path, 'delete'>>>;\n }\n\n return this.http.delete<SuccessResponseJSON<NonNullable<OpOf<Paths, Path, 'delete'>>>>(\n buildUrl(this.baseUrl, String(path), r.params?.path),\n httpOptions,\n );\n }\n}\n","/*\n * Public API Surface of ngx-openapi-typescript\n */\n\nexport { createOpenApiResource } from './lib/open-api-resource';\nexport type {\n OpenApiResource, OpenApiResourceCallOptions, OpenApiResourceConfig\n} from './lib/open-api-resource';\n\nexport { OpenApiHttpClient } from './lib/open-api-http-client';\nexport type { OpenApiHttpClientConfig } from './lib/open-api-http-client';\n\nexport type {\n HasRequiredKeys,\n HttpMethod, OpenApiOperationRequest,\n OpenApiRequestOptions, OperationBody, OperationParamsObject, PathParameters, PathRecord, PathsWithMethod, QueryParameters, RequestBodyJSON, SuccessResponseJSON\n} from './lib/types';\n\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["_buildUrl","_toHttpParams"],"mappings":";;;AAEA;SACgB,QAAQ,CACtB,OAAe,EACf,IAAY,EACZ,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E,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,EACpD,CAAC,CAAC,IAA8D,EAChE,YAAY,CAAC,CAAC,CAAC,CAChB;IACH;AAEA;;AAEG;IACH,KAAK,CACH,IAAU,EACV,OAA0E,EAAA;AAE1E,QAAA,MAAM,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;AAC1B,QAAA,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CACpB,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,EACpD,CAAC,CAAC,IAAgE,EAClE,YAAY,CAAC,CAAC,CAAC,CAChB;IACH;AAEA;;AAEG;IACH,MAAM,CACJ,IAAU,EACV,OAA2E,EAAA;AAE3E,QAAA,MAAM,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;AAC1B,QAAA,MAAM,WAAW,GAAG,YAAY,CAAC,CAAC,CAAyD;AAE3F,QAAA,IAAI,CAAC,CAAC,IAAI,KAAK,SAAS,EAAE;AACxB,YAAA,WAAW,CAAC,IAAI,GAAG,CAAC,CAAC,IAAiE;QACxF;QAEA,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CACrB,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,EACpD,WAAW,CACZ;IACH;AACD;;AC1LD;;AAEG;;ACFH;;AAEG;;;;"}
|
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { HttpHeaders, HttpContext, HttpResourceOptions, HttpResourceRef } from '@angular/common/http';
|
|
1
|
+
import { HttpHeaders, HttpContext, HttpResourceOptions, HttpResourceRef, HttpClient } from '@angular/common/http';
|
|
2
2
|
import { RequestBodyJSON, IsOperationRequestBodyOptional, HttpMethod, SuccessResponseJSON, PathsWithMethod } from 'openapi-typescript-helpers';
|
|
3
3
|
export { HttpMethod, PathsWithMethod, RequestBodyJSON, SuccessResponseJSON } from 'openapi-typescript-helpers';
|
|
4
4
|
import { Observable } from 'rxjs';
|
|
@@ -139,6 +139,8 @@ declare function createOpenApiResource<Paths extends PathRecord>(config?: OpenAp
|
|
|
139
139
|
interface OpenApiHttpClientConfig {
|
|
140
140
|
/** Base URL to prepend to all request paths */
|
|
141
141
|
baseUrl?: string;
|
|
142
|
+
/** HTTP client to use instead of injecting Angular's configured HttpClient. */
|
|
143
|
+
httpClient?: HttpClient;
|
|
142
144
|
}
|
|
143
145
|
/** Extracts the operation type for a given path and method */
|
|
144
146
|
type OpOf<Paths, Path extends keyof Paths, Method extends string> = Paths[Path] extends {
|
|
@@ -150,6 +152,10 @@ type OpOf<Paths, Path extends keyof Paths, Method extends string> = Paths[Path]
|
|
|
150
152
|
* Wraps Angular's `HttpClient` and binds request/response types to an OpenAPI
|
|
151
153
|
* schema generated by `openapi-typescript`.
|
|
152
154
|
*
|
|
155
|
+
* By default, injects Angular's configured `HttpClient`, requiring an injection
|
|
156
|
+
* context. Supplying `config.httpClient` uses that instance without injection,
|
|
157
|
+
* so construction outside an injection context is supported.
|
|
158
|
+
*
|
|
153
159
|
* Designed to be subclassed per-API:
|
|
154
160
|
*
|
|
155
161
|
* @example
|