@jokio/rpc 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/LICENSE +21 -0
- package/README.md +178 -0
- package/dist/index.d.mts +48 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.js +108 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +104 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
# jokRPC
|
|
2
|
+
|
|
3
|
+
A type-safe RPC framework for TypeScript with Zod validation, designed for Express servers and HTTP clients.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- Full TypeScript type safety from server to client
|
|
8
|
+
- Runtime validation using Zod schemas
|
|
9
|
+
- Express.js integration for server-side
|
|
10
|
+
- Flexible fetch-based client with custom fetch support
|
|
11
|
+
- Support for both GET and POST routes
|
|
12
|
+
- Query parameters and request body validation
|
|
13
|
+
- Automatic response validation
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install jokrpc zod express
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
### 1. Define Your Router Configuration
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { defineRouterConfig } from 'jokrpc'
|
|
27
|
+
import { z } from 'zod'
|
|
28
|
+
|
|
29
|
+
const routerConfig = defineRouterConfig({
|
|
30
|
+
GET: {
|
|
31
|
+
'/users/:id': {
|
|
32
|
+
query: z.object({
|
|
33
|
+
include: z.enum(['posts', 'comments']).optional(),
|
|
34
|
+
}),
|
|
35
|
+
result: z.object({
|
|
36
|
+
id: z.string(),
|
|
37
|
+
name: z.string(),
|
|
38
|
+
email: z.string(),
|
|
39
|
+
}),
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
POST: {
|
|
43
|
+
'/users': {
|
|
44
|
+
body: z.object({
|
|
45
|
+
name: z.string(),
|
|
46
|
+
email: z.string().email(),
|
|
47
|
+
}),
|
|
48
|
+
query: z.object({
|
|
49
|
+
sendEmail: z.boolean().optional(),
|
|
50
|
+
}),
|
|
51
|
+
result: z.object({
|
|
52
|
+
id: z.string(),
|
|
53
|
+
name: z.string(),
|
|
54
|
+
email: z.string(),
|
|
55
|
+
}),
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
})
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### 2. Set Up the Server
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
import express from 'express'
|
|
65
|
+
import { applyConfigToExpressRouter } from 'jokrpc'
|
|
66
|
+
|
|
67
|
+
const app = express()
|
|
68
|
+
app.use(express.json())
|
|
69
|
+
|
|
70
|
+
const router = express.Router()
|
|
71
|
+
|
|
72
|
+
applyConfigToExpressRouter(router, routerConfig, {
|
|
73
|
+
GET: {
|
|
74
|
+
'/users/:id': async ({ query }) => {
|
|
75
|
+
// Handler implementation
|
|
76
|
+
return {
|
|
77
|
+
id: '1',
|
|
78
|
+
name: 'John Doe',
|
|
79
|
+
email: 'john@example.com',
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
POST: {
|
|
84
|
+
'/users': async ({ body, query }) => {
|
|
85
|
+
// Handler implementation
|
|
86
|
+
return {
|
|
87
|
+
id: '2',
|
|
88
|
+
name: body.name,
|
|
89
|
+
email: body.email,
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
app.use('/api', router)
|
|
96
|
+
app.listen(3000)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### 3. Create a Type-Safe Client
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
import { createClient } from 'jokrpc'
|
|
103
|
+
|
|
104
|
+
const client = createClient(routerConfig, {
|
|
105
|
+
baseUrl: 'http://localhost:3000/api',
|
|
106
|
+
validateRequest: true, // Optional: validate requests on client-side
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
// Fully typed API calls
|
|
110
|
+
const user = await client.GET['/users/:id']({
|
|
111
|
+
query: { include: 'posts' },
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
const newUser = await client.POST['/users']({
|
|
115
|
+
body: { name: 'Jane Doe', email: 'jane@example.com' },
|
|
116
|
+
query: { sendEmail: true },
|
|
117
|
+
})
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## API Reference
|
|
121
|
+
|
|
122
|
+
### `defineRouterConfig(config)`
|
|
123
|
+
|
|
124
|
+
Helper function to define a router configuration with type inference.
|
|
125
|
+
|
|
126
|
+
### `applyConfigToExpressRouter(router, config, handlers)`
|
|
127
|
+
|
|
128
|
+
Applies route handlers to an Express router with automatic validation.
|
|
129
|
+
|
|
130
|
+
**Parameters:**
|
|
131
|
+
- `router`: Express Router instance
|
|
132
|
+
- `config`: Router configuration object
|
|
133
|
+
- `handlers`: Handler functions for each route
|
|
134
|
+
|
|
135
|
+
### `createClient(config, options)`
|
|
136
|
+
|
|
137
|
+
Creates a type-safe HTTP client.
|
|
138
|
+
|
|
139
|
+
**Options:**
|
|
140
|
+
- `baseUrl`: Base URL for API requests
|
|
141
|
+
- `headers`: Optional default headers
|
|
142
|
+
- `fetch`: Optional custom fetch function (useful for Node.js or testing)
|
|
143
|
+
- `validateRequest`: Enable client-side request validation (default: false)
|
|
144
|
+
|
|
145
|
+
## Type Safety
|
|
146
|
+
|
|
147
|
+
The library provides end-to-end type safety:
|
|
148
|
+
|
|
149
|
+
```typescript
|
|
150
|
+
// TypeScript knows the exact shape of requests and responses
|
|
151
|
+
const result = await client.POST['/users']({
|
|
152
|
+
body: {
|
|
153
|
+
name: 'John',
|
|
154
|
+
email: 'invalid-email', // Zod will catch this at runtime
|
|
155
|
+
},
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
// result is typed as { id: string; name: string; email: string }
|
|
159
|
+
console.log(result.id)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## Error Handling
|
|
163
|
+
|
|
164
|
+
The library throws errors for:
|
|
165
|
+
- HTTP errors (non-2xx responses)
|
|
166
|
+
- Validation errors (invalid request/response data)
|
|
167
|
+
|
|
168
|
+
```typescript
|
|
169
|
+
try {
|
|
170
|
+
await client.POST['/users']({ body: invalidData })
|
|
171
|
+
} catch (error) {
|
|
172
|
+
// Handle validation or HTTP errors
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## License
|
|
177
|
+
|
|
178
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import z from 'zod';
|
|
2
|
+
import { Router } from 'express';
|
|
3
|
+
|
|
4
|
+
type RouteConfig = {
|
|
5
|
+
body: z.ZodType;
|
|
6
|
+
query?: z.ZodType;
|
|
7
|
+
result: z.ZodType;
|
|
8
|
+
};
|
|
9
|
+
type RouterConfig = {
|
|
10
|
+
GET: Record<string, Omit<RouteConfig, 'body'>>;
|
|
11
|
+
POST: Record<string, RouteConfig>;
|
|
12
|
+
};
|
|
13
|
+
declare const defineRouterConfig: <T extends RouterConfig>(config: T) => T;
|
|
14
|
+
|
|
15
|
+
type InferRouteConfig$1<T extends RouteConfig | Omit<RouteConfig, "body">> = {
|
|
16
|
+
[K in keyof T]: T[K] extends z.ZodType ? z.infer<T[K]> : never;
|
|
17
|
+
};
|
|
18
|
+
type RouterClient<T extends RouterConfig> = {
|
|
19
|
+
GET: {
|
|
20
|
+
[K in keyof T["GET"]]: (data?: Omit<Omit<InferRouteConfig$1<T["GET"][K]>, "body">, "result">) => Promise<InferRouteConfig$1<T["GET"][K]>["result"]>;
|
|
21
|
+
};
|
|
22
|
+
POST: {
|
|
23
|
+
[K in keyof T["POST"]]: (data: Omit<InferRouteConfig$1<T["POST"][K]>, "result">) => Promise<InferRouteConfig$1<T["POST"][K]>["result"]>;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
type FetchFunction = (url: string, options: RequestInit) => Promise<Response>;
|
|
27
|
+
type CreateClientOptions = {
|
|
28
|
+
baseUrl: string;
|
|
29
|
+
headers?: Record<string, string>;
|
|
30
|
+
fetch?: FetchFunction;
|
|
31
|
+
validateRequest?: boolean;
|
|
32
|
+
};
|
|
33
|
+
declare const createClient: <T extends RouterConfig>(config: T, options: CreateClientOptions) => RouterClient<T>;
|
|
34
|
+
|
|
35
|
+
type InferRouteConfig<T extends RouteConfig | Omit<RouteConfig, "body">> = {
|
|
36
|
+
[K in keyof T]: T[K] extends z.ZodType ? z.infer<T[K]> : never;
|
|
37
|
+
};
|
|
38
|
+
type RouterHandlerConfig<T extends RouterConfig> = {
|
|
39
|
+
GET: {
|
|
40
|
+
[K in keyof T["GET"]]: (data: Omit<Omit<InferRouteConfig<T["GET"][K]>, "body">, "result">) => Promise<InferRouteConfig<T["GET"][K]>["result"]>;
|
|
41
|
+
};
|
|
42
|
+
POST: {
|
|
43
|
+
[K in keyof T["POST"]]: (data: Omit<InferRouteConfig<T["POST"][K]>, "result">) => Promise<InferRouteConfig<T["POST"][K]>["result"]>;
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
declare const applyConfigToExpressRouter: <T extends RouterConfig>(router: Router, config: T, handlers: RouterHandlerConfig<T>) => Router;
|
|
47
|
+
|
|
48
|
+
export { type RouteConfig, type RouterClient, type RouterConfig, type RouterHandlerConfig, applyConfigToExpressRouter, createClient, defineRouterConfig };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import z from 'zod';
|
|
2
|
+
import { Router } from 'express';
|
|
3
|
+
|
|
4
|
+
type RouteConfig = {
|
|
5
|
+
body: z.ZodType;
|
|
6
|
+
query?: z.ZodType;
|
|
7
|
+
result: z.ZodType;
|
|
8
|
+
};
|
|
9
|
+
type RouterConfig = {
|
|
10
|
+
GET: Record<string, Omit<RouteConfig, 'body'>>;
|
|
11
|
+
POST: Record<string, RouteConfig>;
|
|
12
|
+
};
|
|
13
|
+
declare const defineRouterConfig: <T extends RouterConfig>(config: T) => T;
|
|
14
|
+
|
|
15
|
+
type InferRouteConfig$1<T extends RouteConfig | Omit<RouteConfig, "body">> = {
|
|
16
|
+
[K in keyof T]: T[K] extends z.ZodType ? z.infer<T[K]> : never;
|
|
17
|
+
};
|
|
18
|
+
type RouterClient<T extends RouterConfig> = {
|
|
19
|
+
GET: {
|
|
20
|
+
[K in keyof T["GET"]]: (data?: Omit<Omit<InferRouteConfig$1<T["GET"][K]>, "body">, "result">) => Promise<InferRouteConfig$1<T["GET"][K]>["result"]>;
|
|
21
|
+
};
|
|
22
|
+
POST: {
|
|
23
|
+
[K in keyof T["POST"]]: (data: Omit<InferRouteConfig$1<T["POST"][K]>, "result">) => Promise<InferRouteConfig$1<T["POST"][K]>["result"]>;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
type FetchFunction = (url: string, options: RequestInit) => Promise<Response>;
|
|
27
|
+
type CreateClientOptions = {
|
|
28
|
+
baseUrl: string;
|
|
29
|
+
headers?: Record<string, string>;
|
|
30
|
+
fetch?: FetchFunction;
|
|
31
|
+
validateRequest?: boolean;
|
|
32
|
+
};
|
|
33
|
+
declare const createClient: <T extends RouterConfig>(config: T, options: CreateClientOptions) => RouterClient<T>;
|
|
34
|
+
|
|
35
|
+
type InferRouteConfig<T extends RouteConfig | Omit<RouteConfig, "body">> = {
|
|
36
|
+
[K in keyof T]: T[K] extends z.ZodType ? z.infer<T[K]> : never;
|
|
37
|
+
};
|
|
38
|
+
type RouterHandlerConfig<T extends RouterConfig> = {
|
|
39
|
+
GET: {
|
|
40
|
+
[K in keyof T["GET"]]: (data: Omit<Omit<InferRouteConfig<T["GET"][K]>, "body">, "result">) => Promise<InferRouteConfig<T["GET"][K]>["result"]>;
|
|
41
|
+
};
|
|
42
|
+
POST: {
|
|
43
|
+
[K in keyof T["POST"]]: (data: Omit<InferRouteConfig<T["POST"][K]>, "result">) => Promise<InferRouteConfig<T["POST"][K]>["result"]>;
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
declare const applyConfigToExpressRouter: <T extends RouterConfig>(router: Router, config: T, handlers: RouterHandlerConfig<T>) => Router;
|
|
47
|
+
|
|
48
|
+
export { type RouteConfig, type RouterClient, type RouterConfig, type RouterHandlerConfig, applyConfigToExpressRouter, createClient, defineRouterConfig };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/types.ts
|
|
4
|
+
var defineRouterConfig = (config) => config;
|
|
5
|
+
|
|
6
|
+
// src/client.ts
|
|
7
|
+
var createClient = (config, options) => {
|
|
8
|
+
const {
|
|
9
|
+
baseUrl,
|
|
10
|
+
headers = {},
|
|
11
|
+
fetch: customFetch = fetch,
|
|
12
|
+
validateRequest = false
|
|
13
|
+
} = options;
|
|
14
|
+
const client = {
|
|
15
|
+
GET: {},
|
|
16
|
+
POST: {}
|
|
17
|
+
};
|
|
18
|
+
Object.keys(config.GET).forEach((path) => {
|
|
19
|
+
client.GET[path] = async (data) => {
|
|
20
|
+
if (validateRequest && data?.query) {
|
|
21
|
+
config.GET[path]?.query?.parse(data.query);
|
|
22
|
+
}
|
|
23
|
+
const queryString = data?.query ? "?" + new URLSearchParams(data.query).toString() : "";
|
|
24
|
+
const response = await customFetch(`${baseUrl}${path}${queryString}`, {
|
|
25
|
+
method: "GET",
|
|
26
|
+
headers: {
|
|
27
|
+
"Content-Type": "application/json",
|
|
28
|
+
...headers
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
if (!response.ok) {
|
|
32
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
33
|
+
}
|
|
34
|
+
const json = await response.json();
|
|
35
|
+
return config.GET[path]?.result.parse(json);
|
|
36
|
+
};
|
|
37
|
+
});
|
|
38
|
+
Object.keys(config.POST).forEach((path) => {
|
|
39
|
+
client.POST[path] = async (data) => {
|
|
40
|
+
if (validateRequest) {
|
|
41
|
+
if (data?.body) {
|
|
42
|
+
config.POST[path]?.body?.parse(data.body);
|
|
43
|
+
}
|
|
44
|
+
if (data?.query) {
|
|
45
|
+
config.POST[path]?.query?.parse(data.query);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const queryString = data?.query ? "?" + new URLSearchParams(data.query).toString() : "";
|
|
49
|
+
const response = await customFetch(`${baseUrl}${path}${queryString}`, {
|
|
50
|
+
method: "POST",
|
|
51
|
+
headers: {
|
|
52
|
+
"Content-Type": "application/json",
|
|
53
|
+
...headers
|
|
54
|
+
},
|
|
55
|
+
body: JSON.stringify(data.body)
|
|
56
|
+
});
|
|
57
|
+
if (!response.ok) {
|
|
58
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
59
|
+
}
|
|
60
|
+
const json = await response.json();
|
|
61
|
+
return config.POST[path]?.result.parse(json);
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
return client;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// src/server.ts
|
|
68
|
+
var applyConfigToExpressRouter = (router, config, handlers) => {
|
|
69
|
+
const routes = Object.keys(config.GET);
|
|
70
|
+
routes.reduce(
|
|
71
|
+
(r, x) => r.get(x, async (req, res, next) => {
|
|
72
|
+
try {
|
|
73
|
+
const data = {
|
|
74
|
+
query: config.GET[x]?.query?.parse(req.query)
|
|
75
|
+
};
|
|
76
|
+
const result = await handlers.GET[x]?.(data);
|
|
77
|
+
const validatedResult = config.GET[x]?.result.parse(result);
|
|
78
|
+
res.json(validatedResult);
|
|
79
|
+
} catch (err) {
|
|
80
|
+
next(err);
|
|
81
|
+
}
|
|
82
|
+
}),
|
|
83
|
+
router
|
|
84
|
+
);
|
|
85
|
+
routes.reduce(
|
|
86
|
+
(r, x) => r.post(x, async (req, res, next) => {
|
|
87
|
+
try {
|
|
88
|
+
const data = {
|
|
89
|
+
body: config.POST[x]?.body.parse(req.body),
|
|
90
|
+
query: config.POST[x]?.query?.parse(req.query)
|
|
91
|
+
};
|
|
92
|
+
const result = await handlers.POST[x]?.(data);
|
|
93
|
+
const validatedResult = config.POST[x]?.result.parse(result);
|
|
94
|
+
res.json(validatedResult);
|
|
95
|
+
} catch (err) {
|
|
96
|
+
next(err);
|
|
97
|
+
}
|
|
98
|
+
}),
|
|
99
|
+
router
|
|
100
|
+
);
|
|
101
|
+
return router;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
exports.applyConfigToExpressRouter = applyConfigToExpressRouter;
|
|
105
|
+
exports.createClient = createClient;
|
|
106
|
+
exports.defineRouterConfig = defineRouterConfig;
|
|
107
|
+
//# sourceMappingURL=index.js.map
|
|
108
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/client.ts","../src/server.ts"],"names":[],"mappings":";;;AAaO,IAAM,kBAAA,GAAqB,CAAyB,MAAA,KAAiB;;;ACgBrE,IAAM,YAAA,GAAe,CAC1B,MAAA,EACA,OAAA,KACoB;AACpB,EAAA,MAAM;AAAA,IACJ,OAAA;AAAA,IACA,UAAU,EAAC;AAAA,IACX,OAAO,WAAA,GAAc,KAAA;AAAA,IACrB,eAAA,GAAkB;AAAA,GACpB,GAAI,OAAA;AAEJ,EAAA,MAAM,MAAA,GAAS;AAAA,IACb,KAAK,EAAC;AAAA,IACN,MAAM;AAAC,GACT;AAEA,EAAA,MAAA,CAAO,KAAK,MAAA,CAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,CAAC,IAAA,KAAS;AACxC,IAAC,MAAA,CAAO,GAAA,CAAI,IAAsB,CAAA,GAAY,OAAO,IAAA,KAAe;AAClE,MAAA,IAAI,eAAA,IAAmB,MAAM,KAAA,EAAO;AAClC,QAAA,MAAA,CAAO,IAAI,IAAI,CAAA,EAAG,KAAA,EAAO,KAAA,CAAM,KAAK,KAAK,CAAA;AAAA,MAC3C;AACA,MAAA,MAAM,WAAA,GAAc,IAAA,EAAM,KAAA,GACtB,GAAA,GAAM,IAAI,gBAAgB,IAAA,CAAK,KAAK,CAAA,CAAE,QAAA,EAAS,GAC/C,EAAA;AACJ,MAAA,MAAM,QAAA,GAAW,MAAM,WAAA,CAAY,CAAA,EAAG,OAAO,CAAA,EAAG,IAAI,CAAA,EAAG,WAAW,CAAA,CAAA,EAAI;AAAA,QACpE,MAAA,EAAQ,KAAA;AAAA,QACR,OAAA,EAAS;AAAA,UACP,cAAA,EAAgB,kBAAA;AAAA,UAChB,GAA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L,CAAC,GAAG,CAAA,KACF,CAAA,CAAE,KAAK,CAAA,EAAG,OAAO,GAAA,EAAK,GAAA,EAAK,IAAA,KAAS;AAClC,MAAA,IAAI;AACF,QAAA,MAAM,IAAA,GAAO;AAAA,UACX,IAAA,EAAM,OAAO,IAAA,CAAK,CAAC,GAAG,IAAA,CAAK,KAAA,CAAM,IAAI,IAAI,CAAA;AAAA,UACzC,KAAA,EAAO,OAAO,IAAA,CAAK,CAAC,GAAG,KAAA,EAAO,KAAA,CAAM,IAAI,KAAK;AAAA,SAC/C;AACA,QAAA,MAAM,SAAS,MAAM,QAAA,CAAS,IAAA,CAAK,CAAC,IAAI,IAAW,CAAA;AACnD,QAAA,MAAM,kBAAkB,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,EAAG,MAAA,CAAO,MAAM,MAAM,CAAA;AAC3D,QAAA,GAAA,CAAI,KAAK,eAAe,CAAA;AAAA,MAC1B,SAAS,GAAA,EAAK;AACZ,QAAA,IAAA,CAAK,GAAG,CAAA;AAAA,MACV;AAAA,IACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["import type z from 'zod'\n\nexport type RouteConfig = {\n body: z.ZodType\n query?: z.ZodType\n result: z.ZodType\n}\n\nexport type RouterConfig = {\n GET: Record<string, Omit<RouteConfig, 'body'>>\n POST: Record<string, RouteConfig>\n}\n\nexport const defineRouterConfig = <T extends RouterConfig>(config: T): T => config\n","import type z from \"zod\";\nimport type { RouteConfig, RouterConfig } from \"./types\";\n\ntype InferRouteConfig<T extends RouteConfig | Omit<RouteConfig, \"body\">> = {\n [K in keyof T]: T[K] extends z.ZodType ? z.infer<T[K]> : never;\n};\n\nexport type RouterClient<T extends RouterConfig> = {\n GET: {\n [K in keyof T[\"GET\"]]: (\n data?: Omit<Omit<InferRouteConfig<T[\"GET\"][K]>, \"body\">, \"result\">\n ) => Promise<InferRouteConfig<T[\"GET\"][K]>[\"result\"]>;\n };\n POST: {\n [K in keyof T[\"POST\"]]: (\n data: Omit<InferRouteConfig<T[\"POST\"][K]>, \"result\">\n ) => Promise<InferRouteConfig<T[\"POST\"][K]>[\"result\"]>;\n };\n};\n\ntype FetchFunction = (url: string, options: RequestInit) => Promise<Response>;\n\ntype CreateClientOptions = {\n baseUrl: string;\n headers?: Record<string, string>;\n fetch?: FetchFunction;\n validateRequest?: boolean;\n};\n\nexport const createClient = <T extends RouterConfig>(\n config: T,\n options: CreateClientOptions\n): RouterClient<T> => {\n const {\n baseUrl,\n headers = {},\n fetch: customFetch = fetch,\n validateRequest = false,\n } = options;\n\n const client = {\n GET: {} as RouterClient<T>[\"GET\"],\n POST: {} as RouterClient<T>[\"POST\"],\n };\n\n Object.keys(config.GET).forEach((path) => {\n (client.GET[path as keyof T[\"GET\"]] as any) = async (data?: any) => {\n if (validateRequest && data?.query) {\n config.GET[path]?.query?.parse(data.query);\n }\n const queryString = data?.query\n ? \"?\" + new URLSearchParams(data.query).toString()\n : \"\";\n const response = await customFetch(`${baseUrl}${path}${queryString}`, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers,\n },\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n const json = await response.json();\n\n return config.GET[path]?.result.parse(json);\n };\n });\n\n Object.keys(config.POST).forEach((path) => {\n (client.POST[path as keyof T[\"POST\"]] as any) = async (data: any) => {\n if (validateRequest) {\n if (data?.body) {\n config.POST[path]?.body?.parse(data.body);\n }\n if (data?.query) {\n config.POST[path]?.query?.parse(data.query);\n }\n }\n const queryString = data?.query\n ? \"?\" + new URLSearchParams(data.query).toString()\n : \"\";\n const response = await customFetch(`${baseUrl}${path}${queryString}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers,\n },\n body: JSON.stringify(data.body),\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n const json = await response.json();\n\n return config.POST[path]?.result.parse(json);\n };\n });\n\n return client;\n};\n","import type { Router } from \"express\";\nimport type z from \"zod\";\nimport type { RouteConfig, RouterConfig } from \"./types\";\n\ntype InferRouteConfig<T extends RouteConfig | Omit<RouteConfig, \"body\">> = {\n [K in keyof T]: T[K] extends z.ZodType ? z.infer<T[K]> : never;\n};\n\nexport type RouterHandlerConfig<T extends RouterConfig> = {\n GET: {\n [K in keyof T[\"GET\"]]: (\n data: Omit<Omit<InferRouteConfig<T[\"GET\"][K]>, \"body\">, \"result\">\n ) => Promise<InferRouteConfig<T[\"GET\"][K]>[\"result\"]>;\n };\n POST: {\n [K in keyof T[\"POST\"]]: (\n data: Omit<InferRouteConfig<T[\"POST\"][K]>, \"result\">\n ) => Promise<InferRouteConfig<T[\"POST\"][K]>[\"result\"]>;\n };\n};\n\nexport const applyConfigToExpressRouter = <T extends RouterConfig>(\n router: Router,\n config: T,\n handlers: RouterHandlerConfig<T>\n) => {\n const routes = Object.keys(config.GET);\n\n routes.reduce(\n (r, x) =>\n r.get(x, async (req, res, next) => {\n try {\n const data = {\n query: config.GET[x]?.query?.parse(req.query),\n };\n const result = await handlers.GET[x]?.(data as any);\n const validatedResult = config.GET[x]?.result.parse(result);\n res.json(validatedResult);\n } catch (err) {\n next(err);\n }\n }),\n router\n );\n\n routes.reduce(\n (r, x) =>\n r.post(x, async (req, res, next) => {\n try {\n const data = {\n body: config.POST[x]?.body.parse(req.body),\n query: config.POST[x]?.query?.parse(req.query),\n };\n const result = await handlers.POST[x]?.(data as any);\n const validatedResult = config.POST[x]?.result.parse(result);\n res.json(validatedResult);\n } catch (err) {\n next(err);\n }\n }),\n router\n );\n\n return router;\n};\n"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
var defineRouterConfig = (config) => config;
|
|
3
|
+
|
|
4
|
+
// src/client.ts
|
|
5
|
+
var createClient = (config, options) => {
|
|
6
|
+
const {
|
|
7
|
+
baseUrl,
|
|
8
|
+
headers = {},
|
|
9
|
+
fetch: customFetch = fetch,
|
|
10
|
+
validateRequest = false
|
|
11
|
+
} = options;
|
|
12
|
+
const client = {
|
|
13
|
+
GET: {},
|
|
14
|
+
POST: {}
|
|
15
|
+
};
|
|
16
|
+
Object.keys(config.GET).forEach((path) => {
|
|
17
|
+
client.GET[path] = async (data) => {
|
|
18
|
+
if (validateRequest && data?.query) {
|
|
19
|
+
config.GET[path]?.query?.parse(data.query);
|
|
20
|
+
}
|
|
21
|
+
const queryString = data?.query ? "?" + new URLSearchParams(data.query).toString() : "";
|
|
22
|
+
const response = await customFetch(`${baseUrl}${path}${queryString}`, {
|
|
23
|
+
method: "GET",
|
|
24
|
+
headers: {
|
|
25
|
+
"Content-Type": "application/json",
|
|
26
|
+
...headers
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
if (!response.ok) {
|
|
30
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
31
|
+
}
|
|
32
|
+
const json = await response.json();
|
|
33
|
+
return config.GET[path]?.result.parse(json);
|
|
34
|
+
};
|
|
35
|
+
});
|
|
36
|
+
Object.keys(config.POST).forEach((path) => {
|
|
37
|
+
client.POST[path] = async (data) => {
|
|
38
|
+
if (validateRequest) {
|
|
39
|
+
if (data?.body) {
|
|
40
|
+
config.POST[path]?.body?.parse(data.body);
|
|
41
|
+
}
|
|
42
|
+
if (data?.query) {
|
|
43
|
+
config.POST[path]?.query?.parse(data.query);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const queryString = data?.query ? "?" + new URLSearchParams(data.query).toString() : "";
|
|
47
|
+
const response = await customFetch(`${baseUrl}${path}${queryString}`, {
|
|
48
|
+
method: "POST",
|
|
49
|
+
headers: {
|
|
50
|
+
"Content-Type": "application/json",
|
|
51
|
+
...headers
|
|
52
|
+
},
|
|
53
|
+
body: JSON.stringify(data.body)
|
|
54
|
+
});
|
|
55
|
+
if (!response.ok) {
|
|
56
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
57
|
+
}
|
|
58
|
+
const json = await response.json();
|
|
59
|
+
return config.POST[path]?.result.parse(json);
|
|
60
|
+
};
|
|
61
|
+
});
|
|
62
|
+
return client;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// src/server.ts
|
|
66
|
+
var applyConfigToExpressRouter = (router, config, handlers) => {
|
|
67
|
+
const routes = Object.keys(config.GET);
|
|
68
|
+
routes.reduce(
|
|
69
|
+
(r, x) => r.get(x, async (req, res, next) => {
|
|
70
|
+
try {
|
|
71
|
+
const data = {
|
|
72
|
+
query: config.GET[x]?.query?.parse(req.query)
|
|
73
|
+
};
|
|
74
|
+
const result = await handlers.GET[x]?.(data);
|
|
75
|
+
const validatedResult = config.GET[x]?.result.parse(result);
|
|
76
|
+
res.json(validatedResult);
|
|
77
|
+
} catch (err) {
|
|
78
|
+
next(err);
|
|
79
|
+
}
|
|
80
|
+
}),
|
|
81
|
+
router
|
|
82
|
+
);
|
|
83
|
+
routes.reduce(
|
|
84
|
+
(r, x) => r.post(x, async (req, res, next) => {
|
|
85
|
+
try {
|
|
86
|
+
const data = {
|
|
87
|
+
body: config.POST[x]?.body.parse(req.body),
|
|
88
|
+
query: config.POST[x]?.query?.parse(req.query)
|
|
89
|
+
};
|
|
90
|
+
const result = await handlers.POST[x]?.(data);
|
|
91
|
+
const validatedResult = config.POST[x]?.result.parse(result);
|
|
92
|
+
res.json(validatedResult);
|
|
93
|
+
} catch (err) {
|
|
94
|
+
next(err);
|
|
95
|
+
}
|
|
96
|
+
}),
|
|
97
|
+
router
|
|
98
|
+
);
|
|
99
|
+
return router;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
export { applyConfigToExpressRouter, createClient, defineRouterConfig };
|
|
103
|
+
//# sourceMappingURL=index.mjs.map
|
|
104
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/client.ts","../src/server.ts"],"names":[],"mappings":";AAaO,IAAM,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AAAA,UACzC,KAAA,EAAO,OAAO,IAAA,CAAK,CAAC,GAAG,KAAA,EAAO,KAAA,CAAM,IAAI,KAAK;AAAA,SAC/C;AACA,QAAA,MAAM,SAAS,MAAM,QAAA,CAAS,IAAA,CAAK,CAAC,IAAI,IAAW,CAAA;AACnD,QAAA,MAAM,kBAAkB,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,EAAG,MAAA,CAAO,MAAM,MAAM,CAAA;AAC3D,QAAA,GAAA,CAAI,KAAK,eAAe,CAAA;AAAA,MAC1B,SAAS,GAAA,EAAK;AACZ,QAAA,IAAA,CAAK,GAAG,CAAA;AAAA,MACV;AAAA,IACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.mjs","sourcesContent":["import type z from 'zod'\n\nexport type RouteConfig = {\n body: z.ZodType\n query?: z.ZodType\n result: z.ZodType\n}\n\nexport type RouterConfig = {\n GET: Record<string, Omit<RouteConfig, 'body'>>\n POST: Record<string, RouteConfig>\n}\n\nexport const defineRouterConfig = <T extends RouterConfig>(config: T): T => config\n","import type z from \"zod\";\nimport type { RouteConfig, RouterConfig } from \"./types\";\n\ntype InferRouteConfig<T extends RouteConfig | Omit<RouteConfig, \"body\">> = {\n [K in keyof T]: T[K] extends z.ZodType ? z.infer<T[K]> : never;\n};\n\nexport type RouterClient<T extends RouterConfig> = {\n GET: {\n [K in keyof T[\"GET\"]]: (\n data?: Omit<Omit<InferRouteConfig<T[\"GET\"][K]>, \"body\">, \"result\">\n ) => Promise<InferRouteConfig<T[\"GET\"][K]>[\"result\"]>;\n };\n POST: {\n [K in keyof T[\"POST\"]]: (\n data: Omit<InferRouteConfig<T[\"POST\"][K]>, \"result\">\n ) => Promise<InferRouteConfig<T[\"POST\"][K]>[\"result\"]>;\n };\n};\n\ntype FetchFunction = (url: string, options: RequestInit) => Promise<Response>;\n\ntype CreateClientOptions = {\n baseUrl: string;\n headers?: Record<string, string>;\n fetch?: FetchFunction;\n validateRequest?: boolean;\n};\n\nexport const createClient = <T extends RouterConfig>(\n config: T,\n options: CreateClientOptions\n): RouterClient<T> => {\n const {\n baseUrl,\n headers = {},\n fetch: customFetch = fetch,\n validateRequest = false,\n } = options;\n\n const client = {\n GET: {} as RouterClient<T>[\"GET\"],\n POST: {} as RouterClient<T>[\"POST\"],\n };\n\n Object.keys(config.GET).forEach((path) => {\n (client.GET[path as keyof T[\"GET\"]] as any) = async (data?: any) => {\n if (validateRequest && data?.query) {\n config.GET[path]?.query?.parse(data.query);\n }\n const queryString = data?.query\n ? \"?\" + new URLSearchParams(data.query).toString()\n : \"\";\n const response = await customFetch(`${baseUrl}${path}${queryString}`, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers,\n },\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n const json = await response.json();\n\n return config.GET[path]?.result.parse(json);\n };\n });\n\n Object.keys(config.POST).forEach((path) => {\n (client.POST[path as keyof T[\"POST\"]] as any) = async (data: any) => {\n if (validateRequest) {\n if (data?.body) {\n config.POST[path]?.body?.parse(data.body);\n }\n if (data?.query) {\n config.POST[path]?.query?.parse(data.query);\n }\n }\n const queryString = data?.query\n ? \"?\" + new URLSearchParams(data.query).toString()\n : \"\";\n const response = await customFetch(`${baseUrl}${path}${queryString}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers,\n },\n body: JSON.stringify(data.body),\n });\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n const json = await response.json();\n\n return config.POST[path]?.result.parse(json);\n };\n });\n\n return client;\n};\n","import type { Router } from \"express\";\nimport type z from \"zod\";\nimport type { RouteConfig, RouterConfig } from \"./types\";\n\ntype InferRouteConfig<T extends RouteConfig | Omit<RouteConfig, \"body\">> = {\n [K in keyof T]: T[K] extends z.ZodType ? z.infer<T[K]> : never;\n};\n\nexport type RouterHandlerConfig<T extends RouterConfig> = {\n GET: {\n [K in keyof T[\"GET\"]]: (\n data: Omit<Omit<InferRouteConfig<T[\"GET\"][K]>, \"body\">, \"result\">\n ) => Promise<InferRouteConfig<T[\"GET\"][K]>[\"result\"]>;\n };\n POST: {\n [K in keyof T[\"POST\"]]: (\n data: Omit<InferRouteConfig<T[\"POST\"][K]>, \"result\">\n ) => Promise<InferRouteConfig<T[\"POST\"][K]>[\"result\"]>;\n };\n};\n\nexport const applyConfigToExpressRouter = <T extends RouterConfig>(\n router: Router,\n config: T,\n handlers: RouterHandlerConfig<T>\n) => {\n const routes = Object.keys(config.GET);\n\n routes.reduce(\n (r, x) =>\n r.get(x, async (req, res, next) => {\n try {\n const data = {\n query: config.GET[x]?.query?.parse(req.query),\n };\n const result = await handlers.GET[x]?.(data as any);\n const validatedResult = config.GET[x]?.result.parse(result);\n res.json(validatedResult);\n } catch (err) {\n next(err);\n }\n }),\n router\n );\n\n routes.reduce(\n (r, x) =>\n r.post(x, async (req, res, next) => {\n try {\n const data = {\n body: config.POST[x]?.body.parse(req.body),\n query: config.POST[x]?.query?.parse(req.query),\n };\n const result = await handlers.POST[x]?.(data as any);\n const validatedResult = config.POST[x]?.result.parse(result);\n res.json(validatedResult);\n } catch (err) {\n next(err);\n }\n }),\n router\n );\n\n return router;\n};\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@jokio/rpc",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Type-safe RPC framework with Zod validation for Express and TypeScript",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"require": "./dist/index.js",
|
|
14
|
+
"import": "./dist/index.mjs",
|
|
15
|
+
"types": "./dist/index.d.ts"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsup",
|
|
20
|
+
"dev": "tsup --watch",
|
|
21
|
+
"prepublishOnly": "npm run build",
|
|
22
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"rpc",
|
|
26
|
+
"typescript",
|
|
27
|
+
"zod",
|
|
28
|
+
"express",
|
|
29
|
+
"type-safe",
|
|
30
|
+
"api",
|
|
31
|
+
"validation",
|
|
32
|
+
"framework"
|
|
33
|
+
],
|
|
34
|
+
"author": "",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"express": "^4.0.0",
|
|
38
|
+
"zod": "^4.0.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@types/express": "^4.17.21",
|
|
42
|
+
"@types/node": "^20.10.0",
|
|
43
|
+
"express": "^4.18.2",
|
|
44
|
+
"tsup": "^8.0.1",
|
|
45
|
+
"typescript": "^5.3.3",
|
|
46
|
+
"zod": "^3.22.4"
|
|
47
|
+
},
|
|
48
|
+
"repository": {
|
|
49
|
+
"type": "git",
|
|
50
|
+
"url": ""
|
|
51
|
+
},
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": ""
|
|
54
|
+
},
|
|
55
|
+
"homepage": "",
|
|
56
|
+
"publishConfig": {
|
|
57
|
+
"access": "public"
|
|
58
|
+
}
|
|
59
|
+
}
|