@diephp/vue-apix 0.1.0 → 0.1.1

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.
Files changed (2) hide show
  1. package/README.md +262 -81
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,68 +1,89 @@
1
1
  # @diephp/vue-apix
2
2
 
3
3
  Tiny form / model / api toolkit for Vue 3. Fetch data, edit it, send it back — with reactive
4
- `processing`, Laravel-style validation errors and auto-refetch on change. No axios, zero
5
- runtime dependencies, only Vue 3 as a peer.
4
+ `processing`, Laravel-style validation errors and auto-refetch on change. Built on native
5
+ `fetch`, zero runtime dependencies, only Vue 3 as a peer.
6
6
 
7
7
  The closest relative is Inertia's `useForm`, but vue-apix works with any JSON API and also
8
8
  covers "load → edit → submit" and "filters + pagination" flows.
9
9
 
10
+ ## Installation
11
+
10
12
  ```bash
11
13
  npm i @diephp/vue-apix
12
14
  ```
13
15
 
16
+ ```bash
17
+ yarn add @diephp/vue-apix
18
+ ```
19
+
20
+ ```bash
21
+ pnpm add @diephp/vue-apix
22
+ ```
23
+
24
+ Requires Vue `^3.3`. TypeScript definitions are bundled.
25
+
14
26
  ## Setup
15
27
 
16
- Create your own configured instance (e.g. `src/api.ts`) and import it everywhere:
28
+ Create your own configured instance once (e.g. `src/api.ts`) and import it everywhere:
17
29
 
18
30
  ```ts
31
+ // src/api.ts
19
32
  import apix from '@diephp/vue-apix';
20
33
 
21
- apix.setBaseUrl('https://api.domain.com/v1'); // all request URLs then start with /
34
+ // all relative request URLs are prefixed with this, so they must start with /
35
+ apix.setBaseUrl('https://api.domain.com/v1');
36
+
22
37
  apix.setHeader({
23
- 'x-auth-token': () => localStorage.getItem('token'), // lazy: resolved on every request
24
- 'x-app': 'admin', // static
38
+ // lazy value: the callback is resolved on every request
39
+ 'x-auth-token': () => localStorage.getItem('token'),
40
+ // static value
41
+ 'x-app': 'admin',
25
42
  });
26
43
 
27
- apix.onProcessing((active) => progressBar.toggle(active)); // any request in flight
28
- apix.onError((error, ctx) => { // any failed request
29
- if (error instanceof ApixError && error.status === 401) redirectToLogin();
30
- });
44
+ // fires with true when the first request starts, false when the last one ends —
45
+ // perfect for a global progress bar / spinner
46
+ apix.onProcessing((active) => progressBar.toggle(active));
31
47
 
32
- // onError may RETURN an Error to replace the original one — the replacement goes
33
- // to the next hooks, to model.errors/message and to the rejected promise.
34
- // Handy for normalizing non-Laravel validation formats:
35
- apix.onError((error) => {
36
- if (error instanceof ApixError && error.status === 400 && error.body?.details) {
37
- return new ApixError(422, { message: error.body.error_text, errors: error.body.details });
38
- }
39
- });
40
-
41
- // Global body transformer: applied to EVERY parsed response body (success and
42
- // error statuses) before it is used anywhere — ApixError.message/errors included.
43
- // Return a new body, or mutate in place and return nothing.
44
- apix.transformResponse((body) => {
45
- if (body?.messages?.[0]?.message) body.message = body.messages[0].message;
48
+ // fires on every failed request
49
+ apix.onError((error, ctx) => {
50
+ if (error instanceof ApixError && error.status === 401) redirectToLogin();
46
51
  });
47
52
 
48
53
  export default apix;
49
54
  ```
50
55
 
51
- Or create isolated instances: `const other = createApix({ baseUrl, headers, credentials: 'include' })`.
56
+ ```ts
57
+ // any component / store
58
+ import apix from '@/api';
59
+ ```
60
+
61
+ Need an isolated instance (a second API with different auth)? Create one:
62
+
63
+ ```ts
64
+ import { createApix } from '@diephp/vue-apix';
65
+
66
+ // credentials: 'include' — for cookie-based auth like Laravel Sanctum
67
+ const other = createApix({ baseUrl: 'https://other.api', credentials: 'include' });
68
+ ```
52
69
 
53
70
  ## Plain requests (Promise, no model)
54
71
 
55
72
  ```ts
56
- apix.get('/users', { filters: { name: 'x' }, page: 2 }); // → /users?filters[name]=x&page=2
73
+ // GET /users?filters[name]=x&page=2
74
+ apix.get('/users', { filters: { name: 'x' }, page: 2 });
75
+
57
76
  apix.post('/users', { name: 'a' });
58
77
  apix.put('/users/1', { name: 'b' });
59
78
  apix.patch('/users/1', { name: 'c' });
60
- apix.delete('/users', { ids: [1, 2] }); // DELETE with a body is allowed
79
+
80
+ // DELETE with a body is allowed
81
+ apix.delete('/users', { ids: [1, 2] });
61
82
  ```
62
83
 
63
84
  Query params are serialized PHP-style (`filters[name]=x`), booleans become `1/0`,
64
85
  `null`/`undefined` are skipped. Non-2xx responses reject with `ApixError`
65
- (`status`, `body`, `errors`, `isValidationError`).
86
+ (`status`, `body`, `message`, `errors`, `isValidationError`).
66
87
 
67
88
  ## Forms
68
89
 
@@ -70,53 +91,93 @@ Query params are serialized PHP-style (`filters[name]=x`), booleans become `1/0`
70
91
 
71
92
  ```ts
72
93
  const model = apix.form({ name: null, description: null });
73
- model.name = 'tosic'; // magic prop ≡ model.data.name, fully reactive
94
+
95
+ // magic prop ≡ model.data.name, fully reactive
96
+ model.name = 'tosic';
97
+
74
98
  model.post('/api/attribute').then(({ message }) => alert(message));
75
99
  ```
76
100
 
77
101
  ### Filled from the API
78
102
 
79
103
  ```ts
80
- interface AttrDto { id: number | null; name: string | null; description: string | null }
104
+ interface AttrDto {
105
+ id: number | null;
106
+ name: string | null;
107
+ description: string | null;
108
+ }
81
109
 
82
110
  // response: {data: {item: {...}}} → model.data = item
83
111
  const model = apix.getForm<AttrDto>('/api/attribute/123', 'item');
112
+ ```
113
+
114
+ Full options:
84
115
 
85
- // full options:
116
+ ```ts
86
117
  const model = apix.getForm<AttrDto>('/api/attribute/123', {
87
- path: 'item', // dot-path inside body.data (or body if no data wrapper)
88
- default: () => ({ id: null, name: null, description: null }), // used while loading
89
- immediate: true, // default; false = wait for reload()/watch trigger
90
- params: { with: 'labels' }, // extra query params for every fill request
91
- onSuccess: (response, model) => {}, // every successful fill (initial, reload, watch)
118
+ // dot-path inside body.data (or inside body when there is no data wrapper)
119
+ path: 'item',
120
+ // used while the request is in flight, and as the reset() fallback
121
+ default: () => ({ id: null, name: null, description: null }),
122
+ // default is true; false = no request until reload() or a watch trigger
123
+ immediate: true,
124
+ // extra query params added to every fill request
125
+ params: { with: 'labels' },
126
+ // called after every successful fill (initial, reload(), watch-triggered)
127
+ onSuccess: (response, model) => {},
128
+ // called after every failed fill; aborted (superseded) requests are ignored
92
129
  onError: (error, model) => {},
93
130
  });
94
131
  ```
95
132
 
96
133
  While the request is in flight `model.processing === true` and `model.data` is
97
134
  `default()` (or `null` without a default). `apix.postForm(url, options)` is the same,
98
- but fills via POST (complex search endpoints).
135
+ but fills via POST — for complex search endpoints.
99
136
 
100
- ### In a component
137
+ ### Edit form — full component
101
138
 
102
139
  ```vue
103
140
  <script setup lang="ts">
104
- const model = apix.getForm<AttrDto>('/api/attribute/1', { path: 'item', default: () => ({ name: null, description: null }) });
141
+ import apix from '@/api';
142
+
143
+ interface AttrDto {
144
+ id: number | null;
145
+ name: string | null;
146
+ description: string | null;
147
+ }
148
+
149
+ const model = apix.getForm<AttrDto>('/api/attribute/1', {
150
+ path: 'item',
151
+ default: () => ({ id: null, name: null, description: null }),
152
+ });
105
153
 
106
154
  // NOTE: wrap in a function! `model.put(...)` directly in setup would fire immediately.
107
- const submit = () => model.put('/api/attribute/1').then(({ message }) => alert(message));
155
+ const submit = () =>
156
+ model
157
+ .put('/api/attribute/1')
158
+ .then(({ message }) => alert(message))
159
+ .catch(() => {
160
+ // validation errors are already in model.errors — nothing to do here
161
+ });
108
162
  </script>
109
163
 
110
164
  <template>
111
- <form v-loading="model.processing" @submit.prevent="submit">
112
- <input v-model="model.name" />
165
+ <form @submit.prevent="submit">
166
+ <!-- magic prop: model.name ≡ model.data.name -->
167
+ <input v-model="model.name" :disabled="model.processing" />
113
168
  <span v-if="model.errors.name">{{ model.errors.name }}</span>
114
169
 
115
- <input v-model="model.data.description" />
170
+ <!-- explicit path works too -->
171
+ <input v-model="model.data.description" :disabled="model.processing" />
116
172
  <span v-if="model.error('description')">{{ model.error('description') }}</span>
117
173
 
118
174
  <button type="submit" :disabled="model.processing">Save</button>
175
+
176
+ <!-- restore the first server response -->
119
177
  <button type="button" @click="model.reset()">Reset</button>
178
+
179
+ <!-- or reset specific fields only -->
180
+ <button type="button" @click="model.reset(['name'])">Reset name</button>
120
181
  </form>
121
182
  </template>
122
183
  ```
@@ -139,6 +200,7 @@ const submit = () => model.put('/api/attribute/1').then(({ message }) => alert(m
139
200
  | `model.post/put/patch/delete(url?, opts?)` | submit `model.data` (or `opts.data` / `opts.only: ['name']`), returns the response Promise |
140
201
  | `model.reload(url?)` | re-run the fill request |
141
202
  | `model.watch(paths?, opts?)` / `model.unwatch()` | auto-refetch on change, see below |
203
+ | `model.transformResponse(fn)` / `model.transformRequest(fn)` | reshape server data ↔ model data, see below |
142
204
 
143
205
  Submitting clears previous errors; any **4xx** response carrying an `errors` object in the
144
206
  body (Laravel's 422, or any backend using the same shape on 400-499) fills `model.errors`
@@ -150,20 +212,166 @@ treated as validation errors — only `model.message` is surfaced.
150
212
  clearErrors, reset, post, put, patch, delete, reload, watch, unwatch, transformRequest,
151
213
  transformResponse`. A data field with such a name is still there — via `model.data.<key>`.
152
214
 
215
+ ## watch() — filters, pagination, live search
216
+
217
+ The classic SPA page: a table, a filter form and a paginator. One model holds all of it,
218
+ `watch()` re-sends the request whenever the watched paths change:
219
+
220
+ ```vue
221
+ <script setup lang="ts">
222
+ import apix from '@/api';
223
+
224
+ interface ItemDto {
225
+ id: number;
226
+ name: string;
227
+ description: string;
228
+ }
229
+
230
+ interface PageDto {
231
+ items: ItemDto[];
232
+ filters: { name: string | null; status: string | null };
233
+ paginator: { page: number; total: number; per_page: number };
234
+ }
235
+
236
+ const table = apix
237
+ .getForm<PageDto>('/api/attribute', {
238
+ default: () => ({
239
+ items: [],
240
+ filters: { name: null, status: null },
241
+ paginator: { page: 1, total: 0, per_page: 15 },
242
+ }),
243
+ })
244
+ // watch paginator.page (not the whole paginator!) so the server-owned
245
+ // `total` keeps updating from responses — see the note below
246
+ .watch(['filters', 'paginator.page'], { debounce: 300 });
247
+
248
+ const lastPage = () => Math.max(1, Math.ceil(table.paginator.total / table.paginator.per_page));
249
+
250
+ // changing a filter should always jump back to the first page
251
+ const applyFilter = () => (table.paginator.page = 1);
252
+ </script>
253
+
254
+ <template>
255
+ <div>
256
+ <!-- typing here fires ONE debounced request: GET /api/attribute?filters[name]=...&paginator[page]=1 -->
257
+ <input v-model="table.filters.name" placeholder="Search…" @input="applyFilter" />
258
+
259
+ <select v-model="table.filters.status" @change="applyFilter">
260
+ <option :value="null">All</option>
261
+ <option value="active">Active</option>
262
+ <option value="archived">Archived</option>
263
+ </select>
264
+
265
+ <span v-if="table.processing">Loading…</span>
266
+
267
+ <table>
268
+ <tr v-for="item in table.items" :key="item.id">
269
+ <td>{{ item.id }}</td>
270
+ <td>{{ item.name }}</td>
271
+ </tr>
272
+ </table>
273
+
274
+ <!-- pagination: just mutate the watched path, the table refetches itself -->
275
+ <button :disabled="table.paginator.page <= 1" @click="table.paginator.page--">Prev</button>
276
+ <span>{{ table.paginator.page }} / {{ lastPage() }} · total {{ table.paginator.total }}</span>
277
+ <button :disabled="table.paginator.page >= lastPage()" @click="table.paginator.page++">Next</button>
278
+
279
+ <!-- back to the first-response state; the watcher notices and refetches clean data -->
280
+ <button @click="table.reset()">Reset filters</button>
281
+ </div>
282
+ </template>
283
+ ```
284
+
285
+ Expected server response shape for the example above (Laravel-style):
286
+
287
+ ```json
288
+ {
289
+ "data": {
290
+ "items": [{ "id": 1, "name": "Attribute 1", "description": "..." }],
291
+ "filters": { "name": null, "status": null },
292
+ "paginator": { "page": 1, "total": 42, "per_page": 15 }
293
+ }
294
+ }
295
+ ```
296
+
297
+ How `watch()` behaves:
298
+
299
+ - **Only the watched paths are sent.** GET → PHP-style query
300
+ (`filters[name]=x&paginator[page]=2`), postForm → JSON body. Override with `payload: [...]`.
301
+ - **The response updates everything except the watched paths**, so a slow response never
302
+ clobbers what the user is typing. Opt out with `refreshWatched: true`.
303
+ - **A new trigger aborts the previous in-flight request** (AbortController) — the last
304
+ change wins, out-of-order responses can't overwrite fresh data.
305
+ - **Debounce** (`debounce: 300`) collapses fast typing into one request.
306
+ - `reset()` restores the first-response snapshot; if that actually changes watched data,
307
+ the request is re-sent — reset filters, the table refreshes itself.
308
+ - **Watch server-owned fields precisely**: `['filters', 'paginator.page']`, not
309
+ `['paginator']` — a watched path is preserved from responses, so watching the whole
310
+ `paginator` would freeze `paginator.total` at its first value.
311
+ - Created inside `setup()`, the watcher is bound to the component scope and stops on
312
+ unmount. Module-level models live until `model.unwatch()`.
313
+
314
+ ### Live search (minimal)
315
+
316
+ ```ts
317
+ interface SearchDto {
318
+ results: Array<{ id: number; title: string }>;
319
+ query: string | null;
320
+ }
321
+
322
+ const search = apix
323
+ .getForm<SearchDto>('/api/search', {
324
+ default: () => ({ results: [], query: null }),
325
+ // don't hit the API until the user types something
326
+ immediate: false,
327
+ })
328
+ .watch(['query'], { debounce: 400 });
329
+
330
+ // template: <input v-model="search.query" /> — that's the whole feature
331
+ ```
332
+
333
+ ## Global hooks and error normalization
334
+
335
+ ```ts
336
+ // onError may RETURN an Error to replace the original one — the replacement goes
337
+ // to the next hooks, to model.errors/message and to the rejected promise.
338
+ // Handy when a backend uses its own validation format:
339
+ apix.onError((error) => {
340
+ if (error instanceof ApixError && error.status === 400 && error.body?.details) {
341
+ return new ApixError(422, {
342
+ message: error.body.error_text,
343
+ errors: error.body.details,
344
+ });
345
+ }
346
+ });
347
+ ```
348
+
349
+ ```ts
350
+ // Global body transformer: applied to EVERY parsed response body (success and
351
+ // error statuses) before it is used anywhere — ApixError.message/errors included.
352
+ // Return a new body, or mutate it in place and return nothing.
353
+ apix.transformResponse((body) => {
354
+ // example: the backend sends messages as an array — lift the first one to body.message
355
+ if (body?.messages?.[0]?.message) body.message = body.messages[0].message;
356
+ });
357
+ ```
358
+
153
359
  ## Model transformers — reshape server data
154
360
 
155
361
  When the API shape is awkward (nested, legacy), unwrap it into a comfortable model
156
362
  shape and wrap it back on submit:
157
363
 
158
364
  ```ts
159
- // server: {attr: {name: {value: 'x'}}} ↔ model: {name: 'x'}
365
+ // server shape: {attr: {name: {value: 'x'}}} ↔ model shape: {name: 'x'}
160
366
  const model = apix
161
367
  .getForm<{ name: string | null }>('/api/attribute/1', 'item')
162
368
  .transformResponse((data) => ({ name: data?.attr?.name?.value ?? null }))
163
369
  .transformRequest((data) => ({ attr: { name: { value: data.name } } }));
164
370
 
165
371
  model.name = 'edited';
166
- model.put(); // body: {attr: {name: {value: 'edited'}}}
372
+
373
+ // body sent: {attr: {name: {value: 'edited'}}}
374
+ model.put();
167
375
  ```
168
376
 
169
377
  - `transformResponse(data, response)` runs on every fill (initial, `reload()`, watch) after
@@ -174,48 +382,21 @@ model.put(); // body: {attr: {name: {value: 'edited'}}}
174
382
  mutations never touch the model.
175
383
  - Both are also accepted as `getForm`/`postForm`/`form` options.
176
384
 
177
- ## watch() — filters, pagination, live search
178
-
179
- ```ts
180
- interface PageDto {
181
- items: ItemDto[];
182
- filters: { name: string | null };
183
- paginator: { page: number; total: number; per_page: number };
184
- }
185
-
186
- const table = apix
187
- .getForm<PageDto>('/api/fetch/data', {
188
- default: () => ({ items: [], filters: { name: null }, paginator: { page: 1, total: 0, per_page: 15 } }),
189
- })
190
- .watch(['filters', 'paginator.page'], { debounce: 300 });
191
-
192
- // template: v-model="table.filters.name", @click="table.paginator.page++" — the table refetches itself
193
- ```
194
-
195
- How it behaves:
196
-
197
- - **Only the watched paths are sent** — GET → PHP-style query (`filters[name]=x&paginator[page]=2`),
198
- postForm → JSON body. Override with `payload: [...]`.
199
- - **The response updates everything except the watched paths**, so a slow response never
200
- clobbers what the user is typing. Opt out with `refreshWatched: true`.
201
- - **A new trigger aborts the previous in-flight request** (AbortController) — the last change wins.
202
- - **Debounce** (`debounce: 300`) collapses fast typing into one request.
203
- - `reset()` restores the first-response snapshot; if that actually changes watched data,
204
- the request is re-sent — reset filters, table refreshes.
205
- - Watch server-owned fields precisely: `['filters', 'paginator.page']`, not `['paginator']` —
206
- otherwise `paginator.total` from the response would be preserved away too.
207
- - Created inside `setup()`, the watcher is bound to the component scope and stops on unmount.
208
- Module-level models live until `model.unwatch()`.
209
-
210
385
  ## TypeScript
211
386
 
212
387
  ```ts
213
388
  const model = apix.getForm<AttrDto>('/api/attribute/1', 'item');
214
- model.name; // typed via magic props: Model<AttrDto> = ApixModel<AttrDto> & AttrDto
215
- model.data?.description; // full escape hatch
389
+
390
+ // typed via magic props: Model<AttrDto> = ApixModel<AttrDto> & AttrDto
391
+ model.name;
392
+
393
+ // full escape hatch
394
+ model.data?.description;
216
395
 
217
396
  const list = apix.getForm<ItemDto[]>('/api/attribute', 'items');
218
- list.data?.map((item) => item.name); // arrays: no magic props, use .data
397
+
398
+ // arrays: no magic props, iterate .data directly
399
+ list.data?.map((item) => item.name);
219
400
  ```
220
401
 
221
402
  ## License
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diephp/vue-apix",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Tiny form/model/api toolkit for Vue 3 — fetch-based, Laravel-friendly, zero dependencies",
5
5
  "type": "module",
6
6
  "license": "MIT",