ts-typed-api 0.1.0
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/.eslintrc.json +16 -0
- package/LICENSE +201 -0
- package/README.md +181 -0
- package/dist/apiClient.d.ts +147 -0
- package/dist/apiClient.js +206 -0
- package/dist/client.d.ts +152 -0
- package/dist/client.js +215 -0
- package/dist/definition.d.ts +121 -0
- package/dist/definition.js +79 -0
- package/dist/example-server/client.d.ts +2 -0
- package/dist/example-server/client.js +19 -0
- package/dist/example-server/definitions.d.ts +157 -0
- package/dist/example-server/definitions.js +35 -0
- package/dist/example-server/server.d.ts +1 -0
- package/dist/example-server/server.js +66 -0
- package/dist/handler.d.ts +16 -0
- package/dist/handler.js +185 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +13 -0
- package/dist/object-handlers.d.ts +16 -0
- package/dist/object-handlers.js +39 -0
- package/dist/openapiGenerator.d.ts +2 -0
- package/dist/openapiGenerator.js +119 -0
- package/dist/router/definition.d.ts +118 -0
- package/dist/router/definition.js +80 -0
- package/dist/router/router.d.ts +29 -0
- package/dist/router/router.js +168 -0
- package/dist/router.d.ts +18 -0
- package/dist/router.js +20 -0
- package/dist/src/router/client.d.ts +151 -0
- package/dist/src/router/client.js +215 -0
- package/dist/src/router/definition.d.ts +121 -0
- package/dist/src/router/definition.js +79 -0
- package/dist/src/router/handler.d.ts +16 -0
- package/dist/src/router/handler.js +170 -0
- package/dist/src/router/index.d.ts +5 -0
- package/dist/src/router/index.js +22 -0
- package/dist/src/router/object-handlers.d.ts +16 -0
- package/dist/src/router/object-handlers.js +39 -0
- package/dist/src/router/router.d.ts +18 -0
- package/dist/src/router/router.js +20 -0
- package/examples/advanced/client.ts +226 -0
- package/examples/advanced/definitions.ts +156 -0
- package/examples/advanced/server.ts +298 -0
- package/examples/simple/client.ts +24 -0
- package/examples/simple/definitions.ts +57 -0
- package/examples/simple/server.ts +67 -0
- package/package.json +57 -0
- package/src/client.ts +368 -0
- package/src/definition.ts +231 -0
- package/src/handler.ts +220 -0
- package/src/index.ts +4 -0
- package/src/object-handlers.ts +84 -0
- package/src/router.ts +93 -0
- package/tsconfig.json +17 -0
package/.eslintrc.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"root": true,
|
|
3
|
+
"parser": "@typescript-eslint/parser",
|
|
4
|
+
"plugins": [
|
|
5
|
+
"@typescript-eslint"
|
|
6
|
+
],
|
|
7
|
+
"extends": [
|
|
8
|
+
"eslint:recommended",
|
|
9
|
+
"plugin:@typescript-eslint/recommended"
|
|
10
|
+
],
|
|
11
|
+
"rules": {
|
|
12
|
+
"no-console": "warn",
|
|
13
|
+
"@typescript-eslint/no-explicit-any": "warn",
|
|
14
|
+
"no-unused-vars": "warn"
|
|
15
|
+
}
|
|
16
|
+
}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# ts-typed-api 🚀
|
|
2
|
+
|
|
3
|
+
A lightweight, type-safe API library for TypeScript with Zod validation.
|
|
4
|
+
|
|
5
|
+
## Motivation
|
|
6
|
+
|
|
7
|
+
After building several full-stack applications, I discovered that Large Language Models (LLMs) face significant challenges when implementing features that span both backend and frontend components, particularly around API interfaces.
|
|
8
|
+
|
|
9
|
+
The core issues I observed:
|
|
10
|
+
- **API Contract Drift**: LLMs struggle to maintain consistency when defining an API endpoint and then implementing its usage in the frontend
|
|
11
|
+
- **Context Loss**: Without a clear, shared contract, LLMs lack the contextual assistance needed to ensure proper integration between client and server
|
|
12
|
+
- **Integration Errors**: The disconnect between backend definitions and frontend consumption leads to runtime errors that could be prevented
|
|
13
|
+
|
|
14
|
+
**The Solution**: Leverage TypeScript's powerful type system to provide real-time feedback and compile-time validation for both LLMs and developers. By creating a shared contract that enforces consistency across the entire stack, we eliminate the guesswork and reduce integration issues.
|
|
15
|
+
|
|
16
|
+
## 🤖 Built for LLM-Assisted Development
|
|
17
|
+
|
|
18
|
+
This module is specifically designed to make coding with Large Language Models (LLMs) easier and more efficient. When working on bigger applications with extensive APIs, maintaining context becomes challenging for both developers and AI assistants. ts-typed-api solves this by:
|
|
19
|
+
|
|
20
|
+
### 🔑 Key Benefits for LLM Development
|
|
21
|
+
- **Centralized Type Definitions**: Keep all API contracts in one place, making it easier for LLMs to understand your entire API surface
|
|
22
|
+
- **Automatic Type Synchronization**: The type system ensures both client and server stay perfectly in sync, preventing the drift that commonly occurs in large codebases. Compile-time checks prevent the common client-server mismatches that occur in AI-assisted development
|
|
23
|
+
- **Context-Friendly Structure**: Organized domain-based API definitions that LLMs can easily parse and understand
|
|
24
|
+
- **Compile-Time Validation**: Catch integration issues before runtime, reducing the debugging cycles when working with AI-generated code
|
|
25
|
+
- **Self-Documenting**: Type definitions serve as living documentation that LLMs can easily parse
|
|
26
|
+
|
|
27
|
+
## 📦 Installation
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install ts-typed-api
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
## How to use it?
|
|
35
|
+
1. Define your API in a file that will be shared by both the server and the client
|
|
36
|
+
2. Implement handlers in the server, leveraging the type system and request/response validation
|
|
37
|
+
3. Implement the client based on the contract from #1 leveraging type system
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
## Examples
|
|
41
|
+
|
|
42
|
+
Check out the `examples/` directory:
|
|
43
|
+
- `simple/` - Basic usage with ping endpoints and middleware
|
|
44
|
+
- `advanced/` - Complex schemas with authentication, CRUD operations, and file uploads
|
|
45
|
+
|
|
46
|
+
## 🚀 Quick Start
|
|
47
|
+
|
|
48
|
+
### 1. Define API Routes with Domains
|
|
49
|
+
|
|
50
|
+
Create your API definitions organized by logical domains:
|
|
51
|
+
|
|
52
|
+
```typescript
|
|
53
|
+
// definitions.ts
|
|
54
|
+
import { ZodSchema as z, CreateApiDefinition, CreateResponses } from 'ts-typed-api';
|
|
55
|
+
|
|
56
|
+
// you can create multiple definitions per app
|
|
57
|
+
export const PublicApiDefinition = CreateApiDefinition({
|
|
58
|
+
prefix: '/api/v1/public',
|
|
59
|
+
endpoints: {
|
|
60
|
+
common: { // domain name
|
|
61
|
+
ping: { // endpoint name
|
|
62
|
+
method: 'GET',
|
|
63
|
+
path: '/ping',
|
|
64
|
+
// validate route parameters with Zod
|
|
65
|
+
params: z.object({}),
|
|
66
|
+
// validate query parameters with Zod
|
|
67
|
+
query: z.object({}),
|
|
68
|
+
// validate body with Zod
|
|
69
|
+
body: z.object({}),
|
|
70
|
+
// validate query parameters with Zod
|
|
71
|
+
responses: CreateResponses({
|
|
72
|
+
// specify response codes and response shapes
|
|
73
|
+
200: z.enum(["pong"]),
|
|
74
|
+
201: z.boolean()
|
|
75
|
+
})
|
|
76
|
+
},
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### 2. Implement Server-Side Handlers
|
|
83
|
+
|
|
84
|
+
Register handlers with full type safety and middleware support:
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
// server.ts
|
|
88
|
+
import express from 'express';
|
|
89
|
+
import { RegisterHandlers, EndpointMiddleware } from 'ts-typed-api';
|
|
90
|
+
import { PublicApiDefinition } from './definitions';
|
|
91
|
+
|
|
92
|
+
const app = express();
|
|
93
|
+
app.use(express.json());
|
|
94
|
+
|
|
95
|
+
// Example middleware with endpoint information
|
|
96
|
+
const loggingMiddleware: EndpointMiddleware = (req, res, next, endpointInfo) => {
|
|
97
|
+
console.log(`[${new Date().toISOString()}] ${req.method} ${req.path} - Endpoint: ${endpointInfo.domain}.${endpointInfo.routeKey}`);
|
|
98
|
+
next();
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// Register handlers with TypeScript enforcing all required handlers are present
|
|
102
|
+
RegisterHandlers(app, PublicApiDefinition, {
|
|
103
|
+
common: {
|
|
104
|
+
ping: async (req, res) => {
|
|
105
|
+
console.log('Ping endpoint called');
|
|
106
|
+
res.respond(200, "pong");
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
}, [loggingMiddleware]);
|
|
110
|
+
|
|
111
|
+
app.listen(3001, () => {
|
|
112
|
+
console.log('Server running on http://localhost:3001');
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### 3. Type-Safe Client Calls
|
|
117
|
+
|
|
118
|
+
Make API calls with full type safety and response handling:
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
// client.ts
|
|
122
|
+
import { ApiClient, FetchHttpClientAdapter } from 'ts-typed-api';
|
|
123
|
+
import { PublicApiDefinition } from './definitions';
|
|
124
|
+
|
|
125
|
+
async function runClientExample(): Promise<void> {
|
|
126
|
+
const apiClient = new ApiClient('http://localhost:3001', PublicApiDefinition);
|
|
127
|
+
|
|
128
|
+
// Type-safe API calls with response handlers
|
|
129
|
+
await apiClient.callApi('common', 'ping', {}, {
|
|
130
|
+
// you have to handle each possible status code defined in your contract
|
|
131
|
+
200: (payload) => {
|
|
132
|
+
console.log('Success:', payload); // payload is typed as "pong"
|
|
133
|
+
},
|
|
134
|
+
201: (payload) => {
|
|
135
|
+
console.log('Success:', payload); // payload is typed as boolean
|
|
136
|
+
},
|
|
137
|
+
// you always need to handle 422 since it's returned on request validation
|
|
138
|
+
422: (payload) => {
|
|
139
|
+
console.log('Request validation error:', payload);
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
**Now both server and client are type safe and in sync! The moment you change the definition of the API, type system will let you know about potential changes you need to handle (like additional response code or a change request body schema).**
|
|
146
|
+
|
|
147
|
+
## 🌟 Features
|
|
148
|
+
|
|
149
|
+
### Custom HTTP Client Adapters
|
|
150
|
+
|
|
151
|
+
Create custom HTTP client adapters by implementing the `HttpClientAdapter` interface:
|
|
152
|
+
|
|
153
|
+
```typescript
|
|
154
|
+
interface HttpClientAdapter {
|
|
155
|
+
request<T = any>(url: string, options: HttpRequestOptions): Promise<HttpResponse<T>>;
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Middleware System
|
|
160
|
+
|
|
161
|
+
Add cross-cutting concerns like authentication, logging, and validation:
|
|
162
|
+
|
|
163
|
+
```typescript
|
|
164
|
+
const customMiddleware: EndpointMiddleware = (req, res, next, endpointInfo) => {
|
|
165
|
+
// Access to endpoint metadata
|
|
166
|
+
console.log(`Domain: ${endpointInfo.domain}, Route: ${endpointInfo.routeKey}`);
|
|
167
|
+
next();
|
|
168
|
+
};
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Roadmap
|
|
172
|
+
|
|
173
|
+
- OpenAPI generation with dynamic documentation based on Swagger
|
|
174
|
+
|
|
175
|
+
## 🤝 Contributing
|
|
176
|
+
|
|
177
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
178
|
+
|
|
179
|
+
## 📄 License
|
|
180
|
+
|
|
181
|
+
Apache 2.0 License
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { type ApiDefinitionSchema as BaseApiDefinitionSchema, // Renamed for clarity
|
|
2
|
+
type ApiRouteKey, type ApiClientParams, type ApiClientQuery, type ApiClientBody, type RouteSchema, type UnifiedError, type InferDataFromUnifiedResponse } from "./router/definition";
|
|
3
|
+
import { type ZodTypeAny } from 'zod';
|
|
4
|
+
/**
|
|
5
|
+
* Options for an HTTP request made by an adapter.
|
|
6
|
+
*/
|
|
7
|
+
export interface HttpRequestOptions {
|
|
8
|
+
method: RouteSchema['method'];
|
|
9
|
+
headers?: Record<string, string>;
|
|
10
|
+
body?: string | FormData;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Represents an HTTP response from an adapter.
|
|
14
|
+
* @template T The expected type of the JSON body.
|
|
15
|
+
*/
|
|
16
|
+
export interface HttpResponse<T = any> {
|
|
17
|
+
status: number;
|
|
18
|
+
headers: Headers;
|
|
19
|
+
json(): Promise<T>;
|
|
20
|
+
text(): Promise<string>;
|
|
21
|
+
/**
|
|
22
|
+
* Gets the underlying raw response object from the adapter (e.g., Fetch API's Response object).
|
|
23
|
+
* The type of this object depends on the adapter implementation.
|
|
24
|
+
*/
|
|
25
|
+
getRawResponse(): any;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Interface for an HTTP client adapter.
|
|
29
|
+
* Allows swapping out the underlying HTTP request mechanism (e.g., fetch, axios).
|
|
30
|
+
*/
|
|
31
|
+
export interface HttpClientAdapter {
|
|
32
|
+
/**
|
|
33
|
+
* Makes an HTTP request.
|
|
34
|
+
* @template T The expected type of the JSON response body.
|
|
35
|
+
* @param url The URL to request.
|
|
36
|
+
* @param options The request options.
|
|
37
|
+
* @returns A promise that resolves to an HttpResponse.
|
|
38
|
+
*/
|
|
39
|
+
request<T = any>(url: string, options: HttpRequestOptions): Promise<HttpResponse<T>>;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* An HttpClientAdapter implementation that uses the native Fetch API.
|
|
43
|
+
*/
|
|
44
|
+
export declare class FetchHttpClientAdapter implements HttpClientAdapter {
|
|
45
|
+
request<T = any>(url: string, options: HttpRequestOptions): Promise<HttpResponse<T>>;
|
|
46
|
+
}
|
|
47
|
+
type GetRoute<TActualDef extends BaseApiDefinitionSchema, TDomain extends keyof TActualDef, K extends ApiRouteKey<TActualDef, TDomain>> = TActualDef[TDomain][K] extends infer Rte ? Rte extends RouteSchema ? Rte : never : never;
|
|
48
|
+
type GetResponses<Rte extends RouteSchema> = Rte['responses'];
|
|
49
|
+
/**
|
|
50
|
+
* Discriminated union type for the result of callApi.
|
|
51
|
+
* @template TDef The specific ApiDefinition structure being used.
|
|
52
|
+
* @template TDomain The domain (controller) of the API.
|
|
53
|
+
* @template TRouteKey The key of the route within the domain.
|
|
54
|
+
*/
|
|
55
|
+
type ApiCallResultPayload<S_STATUS_NUM extends number, ActualSchema extends ZodTypeAny> = S_STATUS_NUM extends 422 ? {
|
|
56
|
+
status: S_STATUS_NUM;
|
|
57
|
+
error: UnifiedError;
|
|
58
|
+
rawResponse: any;
|
|
59
|
+
data?: undefined;
|
|
60
|
+
} : S_STATUS_NUM extends 204 ? {
|
|
61
|
+
status: S_STATUS_NUM;
|
|
62
|
+
data: void;
|
|
63
|
+
rawResponse: any;
|
|
64
|
+
error?: undefined;
|
|
65
|
+
} : {
|
|
66
|
+
status: S_STATUS_NUM;
|
|
67
|
+
data: InferDataFromUnifiedResponse<ActualSchema>;
|
|
68
|
+
rawResponse: any;
|
|
69
|
+
error?: undefined;
|
|
70
|
+
};
|
|
71
|
+
export type ApiCallResult<TActualDef extends BaseApiDefinitionSchema, TDomain extends keyof TActualDef, TRouteKey extends ApiRouteKey<TActualDef, TDomain>, CurrentRoute extends RouteSchema = GetRoute<TActualDef, TDomain, TRouteKey>, ResponsesMap = GetResponses<CurrentRoute>> = ResponsesMap extends Record<any, ZodTypeAny> ? {
|
|
72
|
+
[S_STATUS_NUM in keyof ResponsesMap]: S_STATUS_NUM extends number ? ResponsesMap[S_STATUS_NUM] extends infer ActualSchema extends ZodTypeAny ? ApiCallResultPayload<S_STATUS_NUM, ActualSchema> : never : never;
|
|
73
|
+
}[keyof ResponsesMap] : never;
|
|
74
|
+
/**
|
|
75
|
+
* Options for the callApi method.
|
|
76
|
+
* @template TDef The specific ApiDefinition structure being used.
|
|
77
|
+
* @template TDomainParam The domain (controller) of the API.
|
|
78
|
+
* @template TRouteKeyParam The key of the route within the domain.
|
|
79
|
+
*/
|
|
80
|
+
export type CallApiOptions<TActualDef extends BaseApiDefinitionSchema, // Made generic over TActualDef
|
|
81
|
+
TDomainParam extends keyof TActualDef, TRouteKeyParam extends ApiRouteKey<TActualDef, TDomainParam>> = {
|
|
82
|
+
params?: ApiClientParams<TActualDef, TDomainParam, TRouteKeyParam>;
|
|
83
|
+
query?: ApiClientQuery<TActualDef, TDomainParam, TRouteKeyParam>;
|
|
84
|
+
body?: ApiClientBody<TActualDef, TDomainParam, TRouteKeyParam>;
|
|
85
|
+
headers?: Record<string, string>;
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* A client for making API calls defined by an ApiDefinition.
|
|
89
|
+
* It uses an HttpClientAdapter for making actual HTTP requests and supports persistent headers.
|
|
90
|
+
*/
|
|
91
|
+
export declare class ApiClient<TActualDef extends BaseApiDefinitionSchema> {
|
|
92
|
+
private baseUrl;
|
|
93
|
+
private apiDefinitionObject;
|
|
94
|
+
private adapter;
|
|
95
|
+
private persistentHeaders;
|
|
96
|
+
/**
|
|
97
|
+
* Creates an instance of ApiClient.
|
|
98
|
+
* @param baseUrl The base URL for all API calls (e.g., 'http://localhost:3001').
|
|
99
|
+
* @param apiDefinitionObject The API definition object.
|
|
100
|
+
* @param adapter An instance of HttpClientAdapter to use for requests.
|
|
101
|
+
*/
|
|
102
|
+
constructor(baseUrl: string, apiDefinitionObject: TActualDef, // Parameter uses TActualDef
|
|
103
|
+
adapter: HttpClientAdapter);
|
|
104
|
+
/**
|
|
105
|
+
* Sets a persistent header that will be included in all subsequent API calls.
|
|
106
|
+
* If the header already exists, its value will be updated.
|
|
107
|
+
* @param name The name of the header.
|
|
108
|
+
* @param value The value of the header.
|
|
109
|
+
*/
|
|
110
|
+
setHeader(name: string, value: string): void;
|
|
111
|
+
/**
|
|
112
|
+
* Gets the value of a persistent header.
|
|
113
|
+
* @param name The name of the header.
|
|
114
|
+
* @returns The value of the header, or undefined if not set.
|
|
115
|
+
*/
|
|
116
|
+
getHeader(name: string): string | undefined;
|
|
117
|
+
/**
|
|
118
|
+
* Removes a persistent header.
|
|
119
|
+
* @param name The name of the header to remove.
|
|
120
|
+
*/
|
|
121
|
+
removeHeader(name: string): void;
|
|
122
|
+
/**
|
|
123
|
+
* Clears all persistent headers.
|
|
124
|
+
*/
|
|
125
|
+
clearHeaders(): void;
|
|
126
|
+
/**
|
|
127
|
+
* Makes an API call to a specified domain and route.
|
|
128
|
+
* @template TDomain The domain (controller) of the API.
|
|
129
|
+
* @template TRouteKey The key of the route within the domain.
|
|
130
|
+
* @template TInferredHandlers A type inferred from the handlers object, ensuring all defined statuses are handled.
|
|
131
|
+
* @param domain The API domain (e.g., 'user').
|
|
132
|
+
* @param routeKey The API route key (e.g., 'getUsers').
|
|
133
|
+
* @param callData Optional parameters, query, body, and headers for the request.
|
|
134
|
+
* @param handlers An object where keys are status codes and values are handler functions for those statuses.
|
|
135
|
+
* @returns A promise that resolves to the return value of the executed handler.
|
|
136
|
+
* @throws Error if the route configuration is invalid, a network error occurs, an unhandled status code is received, or JSON parsing fails.
|
|
137
|
+
*/
|
|
138
|
+
callApi<TDomain extends keyof TActualDef, TRouteKey extends ApiRouteKey<TActualDef, TDomain>, TInferredHandlers extends {
|
|
139
|
+
[KStatus in ApiCallResult<TActualDef, TDomain, TRouteKey>['status']]: (payload: Extract<ApiCallResult<TActualDef, TDomain, TRouteKey>, {
|
|
140
|
+
status: KStatus;
|
|
141
|
+
}>) => any;
|
|
142
|
+
}>(domain: TDomain, routeKey: TRouteKey, callData: CallApiOptions<TActualDef, TDomain, TRouteKey> | undefined, // Uses TActualDef
|
|
143
|
+
handlers: TInferredHandlers): Promise<{
|
|
144
|
+
[SKey in keyof TInferredHandlers]: TInferredHandlers[SKey] extends (...args: any[]) => infer R ? R : never;
|
|
145
|
+
}[keyof TInferredHandlers]>;
|
|
146
|
+
}
|
|
147
|
+
export {};
|