@tylix/client 1.5.0 → 2.0.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/README.md CHANGED
@@ -26,6 +26,22 @@ throws for HTTP errors. Session cookies are sent automatically. When the
26
26
  access token has expired, the client renews the session once (shared by
27
27
  all requests in flight) and retries.
28
28
 
29
+ ## Typed routes
30
+
31
+ `tylix routes:types` (and `tylix dev`) writes `api.generated.ts` from the
32
+ app's routes. It runs on `createRouteClient`:
33
+
34
+ ```ts
35
+ import { routes } from './api.generated'
36
+
37
+ const post = await routes.posts.show({ id: 7 }) // ApiResult<{ data: Post }>
38
+ await routes.posts.update({ id: 7 }, { title: 'New' })
39
+ await routes.$request('DELETE /api/posts/:id', { params: { id: 7 } })
40
+ ```
41
+
42
+ `buildPath('/api/posts/:id', { id: 7 }, { page: 2 })` gives
43
+ `/api/posts/7?page=2`, and throws when a parameter is missing.
44
+
29
45
  ## The session
30
46
 
31
47
  ```js
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tylix/client",
3
- "version": "1.5.0",
4
- "description": "Browser client for Tylix apps: API requests and the auth session, with no framework dependency.",
3
+ "version": "2.0.0",
4
+ "description": "Browser client for Tylix apps: API requests, the auth session, live channels and the typed route client, with no framework dependency.",
5
5
  "license": "MIT",
6
6
  "author": "Mbiyrukzz",
7
7
  "type": "module",
@@ -10,7 +10,10 @@
10
10
  "client",
11
11
  "auth",
12
12
  "fetch",
13
- "websocket"
13
+ "websocket",
14
+ "typed-api",
15
+ "typescript",
16
+ "routes"
14
17
  ],
15
18
  "homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/client#readme",
16
19
  "repository": {
package/src/index.d.ts CHANGED
@@ -138,3 +138,9 @@ declare global {
138
138
  // eslint-disable-next-line no-var
139
139
  var __TYLIX_DATA__: Record<string, ApiResult> | undefined
140
140
  }
141
+
142
+ /** The runtime of the client "tylix routes:types" generates. */
143
+ export type RouteTable = { [name: string]: [method: string, pattern: string] | RouteTable }
144
+ export function createRouteClient(api: Api, table: RouteTable): any
145
+ /** "/api/posts/:id" + { id: 7 } + { page: 2 } -> "/api/posts/7?page=2". Throws when a param is missing. */
146
+ export function buildPath(pattern: string, params?: Record<string, string | number>, query?: Record<string, unknown>): string
package/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createApi, resultFromResponse } from './createApi.js'
2
2
  import { createAuth } from './createAuth.js'
3
3
  export { channel, lazyChannel } from './channel.js'
4
+ export { createRouteClient, buildPath } from './routeClient.js'
4
5
 
5
6
  export { createApi, createAuth, resultFromResponse }
6
7
 
@@ -0,0 +1,71 @@
1
+ // The runtime behind the typed client "tylix routes:types" writes. It
2
+ // turns a table of names -> [method, pattern] into functions:
3
+ //
4
+ // const routes = createRouteClient(api, { posts: { show: ['GET', '/api/posts/:id'] } })
5
+ // await routes.posts.show({ id: 7 }, { query: { include: 'author' } })
6
+ //
7
+ // Arguments, in order: path params (when the pattern has any), the body
8
+ // (POST, PUT, PATCH), then options ({ query, headers, signal, timeout }).
9
+
10
+ const BODY_METHODS = new Set(['POST', 'PUT', 'PATCH'])
11
+
12
+ function paramNames(pattern) {
13
+ return [...pattern.matchAll(/:([A-Za-z_]\w*)/g)].map((m) => m[1])
14
+ }
15
+
16
+ export function buildPath(pattern, params = {}, query) {
17
+ const missing = []
18
+ let url = pattern.replace(/:([A-Za-z_]\w*)/g, (_, name) => {
19
+ const value = params?.[name]
20
+ if (value === undefined || value === null || value === '') {
21
+ missing.push(name)
22
+ return ''
23
+ }
24
+ return encodeURIComponent(String(value))
25
+ })
26
+ if (missing.length) throw new Error(`[tylix] ${pattern} needs ${missing.map((m) => `"${m}"`).join(', ')}.`)
27
+ if (query && typeof query === 'object') {
28
+ const search = new URLSearchParams()
29
+ for (const [key, value] of Object.entries(query)) {
30
+ if (value === undefined || value === null) continue
31
+ if (Array.isArray(value)) for (const item of value) search.append(key, String(item))
32
+ else search.append(key, String(value))
33
+ }
34
+ const text = search.toString()
35
+ if (text) url += `?${text}`
36
+ }
37
+ return url
38
+ }
39
+
40
+ function call(api, method, pattern, { params, body, query, ...options } = {}) {
41
+ const url = buildPath(pattern, params, query)
42
+ return api(url, { ...options, method, ...(BODY_METHODS.has(method) && body !== undefined ? { body } : {}) })
43
+ }
44
+
45
+ function routeFunction(api, method, pattern) {
46
+ const hasParams = paramNames(pattern).length > 0
47
+ const hasBody = BODY_METHODS.has(method)
48
+ return (...args) => {
49
+ const params = hasParams ? args.shift() : undefined
50
+ const body = hasBody ? args.shift() : undefined
51
+ const options = args.shift() ?? {}
52
+ return call(api, method, pattern, { ...options, params, body })
53
+ }
54
+ }
55
+
56
+ function build(api, table) {
57
+ const out = {}
58
+ for (const [name, value] of Object.entries(table)) {
59
+ out[name] = Array.isArray(value) ? routeFunction(api, value[0], value[1]) : build(api, value)
60
+ }
61
+ return out
62
+ }
63
+
64
+ export function createRouteClient(api, table) {
65
+ const client = build(api, table)
66
+ client.$request = (route, input = {}) => {
67
+ const at = route.indexOf(' ')
68
+ return call(api, route.slice(0, at).toUpperCase(), route.slice(at + 1), input)
69
+ }
70
+ return client
71
+ }