@diephp/vue-apix 0.1.4 → 0.2.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 +50 -13
- package/dist/apix.d.ts +4 -4
- package/dist/index.d.ts +3 -2
- package/dist/model.d.ts +12 -12
- package/dist/types.d.ts +12 -8
- package/dist/utils.d.ts +6 -2
- package/dist/vue-apix.cjs +1 -1
- package/dist/vue-apix.js +22 -23
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -114,15 +114,17 @@ interface AttrDto {
|
|
|
114
114
|
}
|
|
115
115
|
|
|
116
116
|
// response: {data: {item: {...}}} → model.data = item
|
|
117
|
-
const model = apix.getForm<AttrDto>('/api/attribute/123', 'item');
|
|
117
|
+
const model = apix.getForm<AttrDto>('/api/attribute/123', 'data.item');
|
|
118
118
|
```
|
|
119
119
|
|
|
120
120
|
Full options:
|
|
121
121
|
|
|
122
122
|
```ts
|
|
123
123
|
const model = apix.getForm<AttrDto>('/api/attribute/123', {
|
|
124
|
-
// dot-path
|
|
125
|
-
|
|
124
|
+
// dot-path against the RAW response body — there is no implicit body.data
|
|
125
|
+
// unwrapping, include `data` yourself when the API wraps its payload
|
|
126
|
+
// (see "Laravel pagination" below)
|
|
127
|
+
path: 'data.item',
|
|
126
128
|
// used while the request is in flight, and as the reset() fallback
|
|
127
129
|
default: () => ({ id: null, name: null, description: null }),
|
|
128
130
|
// default is true; false = no request until reload() or a watch trigger
|
|
@@ -164,6 +166,38 @@ default has an object falls back to the default object, explicit scalar `null`s
|
|
|
164
166
|
response are respected, and arrays are always replaced — never merged. The `reset()`
|
|
165
167
|
snapshot stores the merged state. Opt out with `mergeDefaults: false`.
|
|
166
168
|
|
|
169
|
+
### Laravel pagination — `data` + `links` + `meta`
|
|
170
|
+
|
|
171
|
+
There is no implicit `body.data` unwrapping — `path` is always a dot-path against the
|
|
172
|
+
**raw** response body, and without a `path` the whole body is used as-is. This matters for
|
|
173
|
+
a Laravel paginated collection, which wraps an **array** in `data` with `links`/`meta` as
|
|
174
|
+
siblings:
|
|
175
|
+
|
|
176
|
+
```json
|
|
177
|
+
{ "data": [{ "id": 1 }, { "id": 2 }], "links": { "next": "/?page=2" }, "meta": { "total": 42 } }
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Since nothing is auto-unwrapped, `links`/`meta` are never at risk of being silently dropped —
|
|
181
|
+
you decide exactly how much of the body ends up in `model.data`:
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
interface PageDto {
|
|
185
|
+
data: Array<{ id: number; name: string }>;
|
|
186
|
+
links: { next: string | null };
|
|
187
|
+
meta: { current_page: number; total: number };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// no `path` at all — model.data becomes the whole body
|
|
191
|
+
const table = apix.getForm<PageDto>('/api/attribute');
|
|
192
|
+
|
|
193
|
+
table.data.data; // the items array
|
|
194
|
+
table.data.meta.total; // pagination meta, fully reachable
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
If you don't need `links`/`meta` and just want the items array as `model.data`, ask for it
|
|
198
|
+
explicitly: `path: 'data'`. And for the common single-resource convention `{data: {...}}}`,
|
|
199
|
+
include `data` in the path too: `path: 'data.item'` reads `body.data.item`.
|
|
200
|
+
|
|
167
201
|
### Edit form — full component
|
|
168
202
|
|
|
169
203
|
```vue
|
|
@@ -177,7 +211,7 @@ interface AttrDto {
|
|
|
177
211
|
}
|
|
178
212
|
|
|
179
213
|
const model = apix.getForm<AttrDto>('/api/attribute/1', {
|
|
180
|
-
path: 'item',
|
|
214
|
+
path: 'data.item',
|
|
181
215
|
default: () => ({ id: null, name: null, description: null }),
|
|
182
216
|
});
|
|
183
217
|
|
|
@@ -251,18 +285,18 @@ and reactive. Two equivalent ways:
|
|
|
251
285
|
|
|
252
286
|
```ts
|
|
253
287
|
// ChildForm.vue — via defineModel (parent: <ChildForm v-model="model" />)
|
|
254
|
-
import type {
|
|
288
|
+
import type { ApixModel } from '@diephp/vue-apix';
|
|
255
289
|
|
|
256
290
|
// type it through the macro GENERIC — not a cast on the left side,
|
|
257
291
|
// otherwise .value loses the model members (errors, processing, data…)
|
|
258
|
-
const form = defineModel<
|
|
292
|
+
const form = defineModel<ApixModel<AttrDto>>({ required: true });
|
|
259
293
|
```
|
|
260
294
|
|
|
261
295
|
```ts
|
|
262
296
|
// ChildForm.vue — via a plain prop (parent: <ChildForm :form="model" />)
|
|
263
|
-
import type {
|
|
297
|
+
import type { ApixModel } from '@diephp/vue-apix';
|
|
264
298
|
|
|
265
|
-
const props = defineProps<{ form:
|
|
299
|
+
const props = defineProps<{ form: ApixModel<AttrDto> }>();
|
|
266
300
|
```
|
|
267
301
|
|
|
268
302
|
```html
|
|
@@ -300,6 +334,9 @@ interface PageDto {
|
|
|
300
334
|
|
|
301
335
|
const table = apix
|
|
302
336
|
.getForm<PageDto>('/api/attribute', {
|
|
337
|
+
// the API wraps its payload in `data` (see the JSON below) — spell it out,
|
|
338
|
+
// there is no implicit body.data unwrapping
|
|
339
|
+
path: 'data',
|
|
303
340
|
default: () => ({
|
|
304
341
|
items: [],
|
|
305
342
|
filters: { name: null, status: null },
|
|
@@ -430,9 +467,9 @@ When the API shape is awkward (nested, legacy), unwrap it into a comfortable mod
|
|
|
430
467
|
shape and wrap it back on submit:
|
|
431
468
|
|
|
432
469
|
```ts
|
|
433
|
-
//
|
|
470
|
+
// response: {data: {item: {attr: {name: {value: 'x'}}}}} ↔ model shape: {name: 'x'}
|
|
434
471
|
const model = apix
|
|
435
|
-
.getForm<{ name: string | null }>('/api/attribute/1', 'item')
|
|
472
|
+
.getForm<{ name: string | null }>('/api/attribute/1', 'data.item')
|
|
436
473
|
.transformResponse((data) => ({ name: data?.attr?.name?.value ?? null }))
|
|
437
474
|
.transformRequest((data) => ({ attr: { name: { value: data.name } } }));
|
|
438
475
|
|
|
@@ -453,15 +490,15 @@ model.put();
|
|
|
453
490
|
## TypeScript
|
|
454
491
|
|
|
455
492
|
```ts
|
|
456
|
-
const model = apix.getForm<AttrDto>('/api/attribute/1', 'item');
|
|
493
|
+
const model = apix.getForm<AttrDto>('/api/attribute/1', 'data.item');
|
|
457
494
|
|
|
458
|
-
// typed via magic props:
|
|
495
|
+
// typed via magic props: ApixModel<AttrDto> = ApixFormModel<AttrDto> & AttrDto
|
|
459
496
|
model.name;
|
|
460
497
|
|
|
461
498
|
// full escape hatch
|
|
462
499
|
model.data?.description;
|
|
463
500
|
|
|
464
|
-
const list = apix.getForm<ItemDto[]>('/api/attribute', 'items');
|
|
501
|
+
const list = apix.getForm<ItemDto[]>('/api/attribute', 'data.items');
|
|
465
502
|
|
|
466
503
|
// arrays: no magic props, iterate .data directly
|
|
467
504
|
list.data?.map((item) => item.name);
|
package/dist/apix.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ApixConfig, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod,
|
|
1
|
+
import { ApixConfig, ApixModel, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, ProcessingHook, RequestOptions } from './types';
|
|
2
2
|
export declare class Apix {
|
|
3
3
|
private baseUrl;
|
|
4
4
|
private headers;
|
|
@@ -34,11 +34,11 @@ export declare class Apix {
|
|
|
34
34
|
/** DELETE with an optional body. */
|
|
35
35
|
delete<T = any>(url: string, data?: unknown, options?: RequestOptions): Promise<T>;
|
|
36
36
|
/** Create a form model without any request (like Inertia's useForm). */
|
|
37
|
-
form<T extends object>(defaults: T | (() => T), options?: Omit<FormOptions<T>, 'default'>):
|
|
37
|
+
form<T extends object>(defaults: T | (() => T), options?: Omit<FormOptions<T>, 'default'>): ApixModel<T>;
|
|
38
38
|
/** Create a form model and fill it with a GET request. */
|
|
39
|
-
getForm<T = any>(url: string,
|
|
39
|
+
getForm<T = any>(url: string, options?: string | FormOptions<T>): ApixModel<T>;
|
|
40
40
|
/** Same as getForm, but the fill request is a POST (complex search endpoints etc.). */
|
|
41
|
-
postForm<T = any>(url: string,
|
|
41
|
+
postForm<T = any>(url: string, options?: string | FormOptions<T>): ApixModel<T>;
|
|
42
42
|
private createFormModel;
|
|
43
43
|
private trackStart;
|
|
44
44
|
private trackEnd;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
export { Apix, createApix } from './apix';
|
|
2
2
|
export { ApixError } from './client';
|
|
3
|
-
|
|
4
|
-
export
|
|
3
|
+
/** The underlying model class (advanced use, e.g. `instanceof` checks). Prefer the `ApixModel<T>` type for annotations. */
|
|
4
|
+
export { ApixFormModel } from './model';
|
|
5
|
+
export type { ApixConfig, ApixModel, BodyTransformer, ErrorHook, FormOptions, HeaderValue, HttpMethod, MagicData, ProcessingHook, RequestContext, RequestOptions, SubmitOptions, WatchOptions, } from './types';
|
|
5
6
|
/** Shared default instance — configure it once (e.g. in your api.ts) and import everywhere. */
|
|
6
7
|
export declare const apix: import('./apix').Apix;
|
|
7
8
|
export default apix;
|
package/dist/model.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Apix } from './apix';
|
|
2
|
-
import { FillSource, FormOptions,
|
|
2
|
+
import { ApixModel, FillSource, FormOptions, SubmitOptions, WatchOptions } from './types';
|
|
3
3
|
interface ModelState {
|
|
4
4
|
data: any;
|
|
5
5
|
errors: Record<string, string>;
|
|
@@ -17,14 +17,14 @@ interface ModelState {
|
|
|
17
17
|
* post, put, patch, delete, reload, refresh, watch, unwatch,
|
|
18
18
|
* transformRequest, transformResponse.
|
|
19
19
|
*/
|
|
20
|
-
export declare class
|
|
20
|
+
export declare class ApixFormModel<T = any> {
|
|
21
21
|
/** @internal */ _apix: Apix;
|
|
22
22
|
/** @internal */ _options: FormOptions<T>;
|
|
23
23
|
/** @internal */ _state: ModelState;
|
|
24
24
|
/** @internal */ _source: FillSource | null;
|
|
25
25
|
/** @internal */ _snapshot: any;
|
|
26
26
|
/** @internal */ _snapshotLocked: boolean;
|
|
27
|
-
/** @internal */ _proxy:
|
|
27
|
+
/** @internal */ _proxy: ApixModel<T>;
|
|
28
28
|
/** @internal */ _stopWatch: (() => void) | null;
|
|
29
29
|
/** @internal */ _debounceTimer: ReturnType<typeof setTimeout> | null;
|
|
30
30
|
/** @internal */ _watched: string[] | null;
|
|
@@ -50,21 +50,21 @@ export declare class ApixModel<T = any> {
|
|
|
50
50
|
*/
|
|
51
51
|
get(path: string): any;
|
|
52
52
|
/** Replace data entirely (object or array). A detached clone is stored. */
|
|
53
|
-
setData(data: T):
|
|
53
|
+
setData(data: T): ApixModel<T>;
|
|
54
54
|
/**
|
|
55
55
|
* First error for the key. Falls back to the first `key.*` sub-error,
|
|
56
56
|
* so `error('name')` also surfaces `name.en.label` messages.
|
|
57
57
|
*/
|
|
58
58
|
error(key: string): string | undefined;
|
|
59
|
-
setErrors(errors: Record<string, string | string[]>):
|
|
59
|
+
setErrors(errors: Record<string, string | string[]>): ApixModel<T>;
|
|
60
60
|
/** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
|
|
61
|
-
clearErrors(keys?: string[]):
|
|
61
|
+
clearErrors(keys?: string[]): ApixModel<T>;
|
|
62
62
|
/**
|
|
63
63
|
* Restore data to the snapshot: the first server response, or `default()`
|
|
64
64
|
* if nothing was loaded yet. Pass keys to reset only those dot-paths.
|
|
65
65
|
* An active watch() reacts to the change as usual (the request is re-sent).
|
|
66
66
|
*/
|
|
67
|
-
reset(keys?: string | string[]):
|
|
67
|
+
reset(keys?: string | string[]): ApixModel<T>;
|
|
68
68
|
post(url?: string, options?: SubmitOptions): Promise<any>;
|
|
69
69
|
put(url?: string, options?: SubmitOptions): Promise<any>;
|
|
70
70
|
patch(url?: string, options?: SubmitOptions): Promise<any>;
|
|
@@ -84,13 +84,13 @@ export declare class ApixModel<T = any> {
|
|
|
84
84
|
* never causes a false watch trigger. The snapshot for reset() stores the
|
|
85
85
|
* transformed shape. Return the new data (or mutate in place and return nothing).
|
|
86
86
|
*/
|
|
87
|
-
transformResponse(transformer: ((data: any, response: any) => any) | null):
|
|
87
|
+
transformResponse(transformer: ((data: any, response: any) => any) | null): ApixModel<T>;
|
|
88
88
|
/**
|
|
89
89
|
* Map model data back into the server shape. Runs on the payload of
|
|
90
90
|
* post/put/patch/delete (unless an explicit `data` option is passed) and on
|
|
91
91
|
* watch payloads. Receives a detached clone — mutations never touch the model.
|
|
92
92
|
*/
|
|
93
|
-
transformRequest(transformer: ((data: any) => any) | null):
|
|
93
|
+
transformRequest(transformer: ((data: any) => any) | null): ApixModel<T>;
|
|
94
94
|
/**
|
|
95
95
|
* Re-send the fill request whenever data changes.
|
|
96
96
|
* `paths` limits both what is observed and what is sent
|
|
@@ -98,8 +98,8 @@ export declare class ApixModel<T = any> {
|
|
|
98
98
|
* The response updates everything except the watched paths (see WatchOptions).
|
|
99
99
|
* A new trigger aborts the previous in-flight watch request.
|
|
100
100
|
*/
|
|
101
|
-
watch(paths?: string[] | WatchOptions, options?: WatchOptions):
|
|
102
|
-
unwatch():
|
|
101
|
+
watch(paths?: string[] | WatchOptions, options?: WatchOptions): ApixModel<T>;
|
|
102
|
+
unwatch(): ApixModel<T>;
|
|
103
103
|
/** @internal */
|
|
104
104
|
_fill(extra?: {
|
|
105
105
|
params?: Record<string, unknown>;
|
|
@@ -117,5 +117,5 @@ export declare class ApixModel<T = any> {
|
|
|
117
117
|
private _syncLastSent;
|
|
118
118
|
}
|
|
119
119
|
/** @internal Factory: wraps the model in the magic Proxy and fires the initial fill. */
|
|
120
|
-
export declare function createModel<T>(apix: Apix, options?: FormOptions<T>, source?: FillSource | null):
|
|
120
|
+
export declare function createModel<T>(apix: Apix, options?: FormOptions<T>, source?: FillSource | null): ApixModel<T>;
|
|
121
121
|
export {};
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ApixFormModel } from './model';
|
|
2
2
|
/** Header value: a plain string or a lazy callback resolved on every request. */
|
|
3
3
|
export type HeaderValue = string | null | undefined | (() => string | null | undefined);
|
|
4
4
|
export interface ApixConfig {
|
|
@@ -41,9 +41,12 @@ export type ErrorHook = (error: unknown, context: RequestContext) => Error | voi
|
|
|
41
41
|
export type BodyTransformer = (body: any, context: RequestContext) => any;
|
|
42
42
|
export interface FormOptions<T = any> {
|
|
43
43
|
/**
|
|
44
|
-
* Dot-path to the payload
|
|
45
|
-
*
|
|
46
|
-
*
|
|
44
|
+
* Dot-path to the payload, resolved against the RAW response body — there is
|
|
45
|
+
* no implicit `body.data` unwrapping. Include `data` yourself when the API
|
|
46
|
+
* wraps its payload: `path: 'data.item'` for `{data: {item: {...}}}`,
|
|
47
|
+
* `path: 'data'` for a paginated collection. No path → the whole body, so a
|
|
48
|
+
* Laravel paginator's `links`/`meta` (`{data: [...], links, meta}`) are
|
|
49
|
+
* always reachable, e.g. via `model.data.meta`.
|
|
47
50
|
*/
|
|
48
51
|
path?: string;
|
|
49
52
|
/** Factory for the initial data used while the request is in flight (and as reset() fallback). */
|
|
@@ -63,9 +66,9 @@ export interface FormOptions<T = any> {
|
|
|
63
66
|
/** Body for `postForm` fill requests. */
|
|
64
67
|
data?: unknown;
|
|
65
68
|
/** Called after every successful fill request (initial, reload(), watch-triggered). */
|
|
66
|
-
onSuccess?: (response: any, model:
|
|
69
|
+
onSuccess?: (response: any, model: ApixModel<T>) => void;
|
|
67
70
|
/** Called after every failed fill request. Aborted (superseded) requests are ignored. */
|
|
68
|
-
onError?: (error: unknown, model:
|
|
71
|
+
onError?: (error: unknown, model: ApixModel<T>) => void;
|
|
69
72
|
/** See model.transformResponse(). */
|
|
70
73
|
transformResponse?: (data: any, response: any) => any;
|
|
71
74
|
/** See model.transformRequest(). */
|
|
@@ -104,5 +107,6 @@ export interface FillSource {
|
|
|
104
107
|
* model member — those stay reachable via `model.data.<key>`.
|
|
105
108
|
* Arrays get no magic props — iterate `model.data` directly.
|
|
106
109
|
*/
|
|
107
|
-
export type MagicData<T> = T extends readonly unknown[] ? {} : T extends object ? Omit<T, keyof
|
|
108
|
-
|
|
110
|
+
export type MagicData<T> = T extends readonly unknown[] ? {} : T extends object ? Omit<T, keyof ApixFormModel> : {};
|
|
111
|
+
/** Public type of a vue-apix model: `apix.form()` / `apix.getForm()` / `apix.postForm()` all return this. */
|
|
112
|
+
export type ApixModel<T = any> = ApixFormModel<T> & MagicData<T>;
|
package/dist/utils.d.ts
CHANGED
|
@@ -24,7 +24,11 @@ export declare function flattenErrors(errors: Record<string, unknown>): Record<s
|
|
|
24
24
|
export declare function extractMessage(body: unknown): string | null;
|
|
25
25
|
/**
|
|
26
26
|
* Pull the payload out of a response body.
|
|
27
|
-
*
|
|
28
|
-
* `path` is a dot-path
|
|
27
|
+
*
|
|
28
|
+
* There is no implicit `body.data` unwrapping — `path` is a dot-path against
|
|
29
|
+
* the RAW body, and you include `data` in it yourself when the API wraps its
|
|
30
|
+
* payload: `path: 'data.item'` for `{data: {item: {...}}}`, `path: 'data'` for
|
|
31
|
+
* a paginated collection. Without a `path`, the whole body is returned as-is,
|
|
32
|
+
* so a Laravel paginator's `links`/`meta` are never silently dropped.
|
|
29
33
|
*/
|
|
30
34
|
export declare function extractData(body: any, path?: string): any;
|
package/dist/vue-apix.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const d=require("vue");function c(i){const t=d.toRaw(i);if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(s=>c(s));if(t instanceof Date)return new Date(t.getTime());const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const s={};for(const r of Object.keys(t))s[r]=c(t[r]);return s}return t}function b(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function A(i,t){if(!b(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!b(i))return i;for(const e of Object.keys(t))i[e]=e in i?A(i[e],t[e]):c(t[e]);return i}function f(i,t){if(i==null)return;let e=i;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function m(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const a=s[o];(r[a]===null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}r[s[s.length-1]]=e}function w(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&m(e,s,c(r))}return e}function x(i){const t={};for(const[e,s]of Object.entries(i??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function _(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function T(i,t){const e=i&&typeof i=="object"&&!Array.isArray(i)&&"data"in i?i.data:i;return t?f(e,t):e}class y extends Error{constructor(t,e,s){super(_(e)??`Request failed with status ${t}`),this.name="ApixError",this.status=t,this.body=e,this.response=s,this.errors=e&&typeof e=="object"&&e.errors&&typeof e.errors=="object"?e.errors:{}}get isValidationError(){return this.status>=400&&this.status<500&&Object.keys(this.errors).length>0}}function E(i){return i instanceof Error&&i.name==="AbortError"}function S(i){const t=[],e=(r,o)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`)},s=(r,o)=>{if(r!=null){if(typeof r=="boolean")return e(o,r?"1":"0");if(r instanceof Date)return e(o,r.toISOString());if(Array.isArray(r)){r.forEach((a,n)=>s(a,`${o}[${n}]`));return}if(typeof r=="object"){for(const[a,n]of Object.entries(r))s(n,`${o}[${a}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function k(i){if(i.status===204)return null;const t=await i.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class R{constructor(t,e={},s=null){this._snapshot=null,this._snapshotLocked=!1,this._stopWatch=null,this._debounceTimer=null,this._watched=null,this._watchOptions={},this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._apix=t,this._options=e,this._source=s,this._transformResponse=e.transformResponse??null,this._transformRequest=e.transformRequest??null;const r=e.default?e.default():null;this._state=d.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r)}get data(){return this._state.data}set data(t){this._state.data=t}get errors(){return this._state.errors}get message(){return this._state.message}get processing(){return this._state.processing}get hasErrors(){return Object.keys(this._state.errors).length>0}get isDirty(){return JSON.stringify(this._state.data)!==JSON.stringify(this._snapshot)}get(t){return c(f(this._state.data,t))}setData(t){return this._state.data=c(t),this._proxy}error(t){const e=this._state.errors;if(e[t]!==void 0)return e[t];const s=`${t}.`;for(const r of Object.keys(e))if(r.startsWith(s))return e[r]}setErrors(t){return this._state.errors=x(t),this._proxy}clearErrors(t){if(!t)return this._state.errors={},this._proxy;for(const e of t){const s=`${e}.`;for(const r of Object.keys(this._state.errors))(r===e||r.startsWith(s))&&delete this._state.errors[r]}return this._proxy}reset(t){if(t===void 0||Array.isArray(t)&&t.length===0)return this._state.data=c(this._snapshot),this._state.errors={},this._state.message=null,this._proxy;const e=Array.isArray(t)?t:[t];if(this._state.data&&typeof this._state.data=="object")for(const s of e)m(this._state.data,s,c(f(this._snapshot,s)));return this.clearErrors(e),this._proxy}post(t,e){return this._submit("post",t,e)}put(t,e){return this._submit("put",t,e)}patch(t,e){return this._submit("patch",t,e)}delete(t,e){return this._submit("delete",t,e)}reload(t){var e;return t&&(this._source={url:t,method:((e=this._source)==null?void 0:e.method)??"get"}),this._source?this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}refresh(){return this._source?this._stopWatch?(this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._lastSent=this._payloadJson(),this._fill(this._watchExtra())):this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}watch(t,e){let s=null,r;Array.isArray(t)?(s=t,r=e??{}):r=t??e??{},this._source||console.warn("[vue-apix] model.watch() has no effect until the model has a source URL (getForm/postForm/reload)."),this.unwatch(),this._watched=s,this._watchOptions=r,this._syncLastSent();const o=s&&s.length?s.map(a=>()=>f(this._state.data,a)):()=>this._state.data;return this._stopWatch=d.watch(o,()=>this._onWatchTrigger(),{deep:r.deep??!0}),this._proxy}unwatch(){var t;return(t=this._stopWatch)==null||t.call(this),this._stopWatch=null,this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._proxy}async _fill(t={}){var o,a,n,h,u;const e=this._source;(o=this._fillAbort)==null||o.abort();const s=new AbortController;this._fillAbort=s,this._state.processing=!0;const r={signal:s.signal};e.method==="get"?r.params={...this._options.params,...t.params}:(r.params=this._options.params,r.data=t.data!==void 0?t.data:this._options.data);try{const l=await this._apix.request(e.method,e.url,r);let p=T(l,this._options.path);if(this._transformResponse){const g=c(p);p=this._transformResponse(g,l)??g}return this._applyFill(p,t.preserve??null),this._state.message=_(l),this._state.errors={},(n=(a=this._options).onSuccess)==null||n.call(a,l,this._proxy),l}catch(l){throw E(l)||(this._applyError(l),(u=(h=this._options).onError)==null||u.call(h,l,this._proxy)),l}finally{this._fillAbort===s&&(this._fillAbort=null,this._state.processing=!1)}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=A(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const a=f(this._state.data,o);a!==void 0&&m(s,o,c(a))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof y&&(this._state.message=_(t.body)??t.message,t.isValidationError&&(this._state.errors=x(t.errors)))}async _submit(t,e,s={}){var a;const r=e??((a=this._source)==null?void 0:a.url);if(!r)throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);let o=s.data!==void 0?s.data:s.only?w(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const n=c(o);o=this._transformRequest(n)??n}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const n=await this._apix.request(t,r,{data:o,params:s.params,headers:s.headers});return this._state.message=_(n),n}catch(n){throw this._applyError(n),n}finally{this._state.processing=!1}}_onWatchTrigger(){if(this._payloadJson()===this._lastSent)return;this._debounceTimer&&clearTimeout(this._debounceTimer);const t=this._watchOptions.debounce??0;t>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),t):this._sendWatchRequest()}_sendWatchRequest(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._watchExtra()).catch(()=>{}))}_watchExtra(){const t=this._watched,e=this._watchOptions.payload??t;let s=e&&e.length?w(this._state.data,e):c(this._state.data);this._transformRequest&&(s=this._transformRequest(s)??s);const r=this._watchOptions.refreshWatched?null:t;return this._source.method==="get"?{params:s,preserve:r}:{data:s,preserve:r}}_payloadJson(){const t=this._watched,e=t&&t.length?t.map(s=>f(this._state.data,s)):this._state.data;return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function j(i,t={},e=null){const s=new R(i,t,e),r=new Proxy(s,{get(o,a){if(typeof a=="symbol"||a in o)return Reflect.get(o,a);const n=o._state.data;if(n&&typeof n=="object")return n[a]},set(o,a,n){if(typeof a=="symbol"||a in o)return Reflect.set(o,a,n);const h=o._state.data;return h&&typeof h=="object"?(h[a]=n,!0):(o._state.data={[a]:n},!0)},has(o,a){if(a in o)return!0;const n=o._state.data;return!!n&&typeof n=="object"&&a in n}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().catch(()=>{}),r}class v{constructor(t={}){this.baseUrl="",this.headers={},this.processingHooks=[],this.errorHooks=[],this.bodyTransformer=null,this.active=0,t.baseUrl&&this.setBaseUrl(t.baseUrl),t.headers&&this.setHeader(t.headers),t.credentials&&(this.credentials=t.credentials)}setBaseUrl(t){return this.baseUrl=t.replace(/\/+$/,""),this}setHeader(t){return Object.assign(this.headers,t),this}setCredentials(t){return this.credentials=t,this}onProcessing(t){return this.processingHooks.push(t),()=>{this.processingHooks=this.processingHooks.filter(e=>e!==t)}}onError(t){return this.errorHooks.push(t),()=>{this.errorHooks=this.errorHooks.filter(e=>e!==t)}}transformResponse(t){return this.bodyTransformer=t,this}async request(t,e,s={}){let r=/^https?:\/\//i.test(e)?e:this.baseUrl+e;if(s.params){const h=S(s.params);h&&(r+=(r.includes("?")?"&":"?")+h)}const o={accept:"application/json","x-requested-with":"XMLHttpRequest"};for(const[h,u]of Object.entries(this.headers)){const l=typeof u=="function"?u():u;l!=null&&(o[h.toLowerCase()]=l)}for(const[h,u]of Object.entries(s.headers??{}))o[h.toLowerCase()]=u;const a={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(a.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],a.body=s.data):(o["content-type"]??(o["content-type"]="application/json"),a.body=JSON.stringify(s.data)));const n={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,a);let u=await k(h);if(this.bodyTransformer&&(u=this.bodyTransformer(u,n)??u),!h.ok)throw new y(h.status,u,h);return u}catch(h){throw E(h)?h:this.emitError(h,n)}finally{this.trackEnd()}}get(t,e,s={}){return this.request("get",t,e?{...s,params:e}:s)}post(t,e,s={}){return this.request("post",t,e!==void 0?{...s,data:e}:s)}put(t,e,s={}){return this.request("put",t,e!==void 0?{...s,data:e}:s)}patch(t,e,s={}){return this.request("patch",t,e!==void 0?{...s,data:e}:s)}delete(t,e,s={}){return this.request("delete",t,e!==void 0?{...s,data:e}:s)}form(t,e={}){return j(this,{...e,default:typeof t=="function"?t:()=>c(t)})}getForm(t,e){return this.createFormModel("get",t,e)}postForm(t,e){return this.createFormModel("post",t,e)}createFormModel(t,e,s){const r=typeof s=="string"?{path:s}:{...s??{}};return j(this,r,{url:e,method:t})}trackStart(){++this.active===1&&this.emitProcessing(!0)}trackEnd(){--this.active===0&&this.emitProcessing(!1)}emitProcessing(t){for(const e of this.processingHooks)try{e(t)}catch{}}emitError(t,e){let s=t;for(const r of this.errorHooks)try{const o=r(s,e);o instanceof Error&&(s=o)}catch{}return s}}function O(i={}){return new v(i)}const q=O();exports.Apix=v;exports.ApixError=y;exports.ApixModel=R;exports.apix=q;exports.createApix=O;exports.default=q;
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const d=require("vue");function c(i){const t=d.toRaw(i);if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(s=>c(s));if(t instanceof Date)return new Date(t.getTime());const e=Object.getPrototypeOf(t);if(e===Object.prototype||e===null){const s={};for(const r of Object.keys(t))s[r]=c(t[r]);return s}return t}function g(i){if(i===null||typeof i!="object")return!1;const t=Object.getPrototypeOf(i);return t===Object.prototype||t===null}function O(i,t){if(!g(t))return i===void 0?c(t):i;if(i==null)return c(t);if(!g(i))return i;for(const e of Object.keys(t))i[e]=e in i?O(i[e],t[e]):c(t[e]);return i}function f(i,t){if(i==null)return;let e=i;for(const s of t.split(".")){if(e==null)return;e=e[s]}return e}function m(i,t,e){const s=t.split(".");let r=i;for(let o=0;o<s.length-1;o++){const a=s[o];(r[a]===null||typeof r[a]!="object")&&(r[a]={}),r=r[a]}r[s[s.length-1]]=e}function w(i,t){const e={};for(const s of t){const r=f(i,s);r!==void 0&&m(e,s,c(r))}return e}function x(i){const t={};for(const[e,s]of Object.entries(i??{}))s!=null&&(t[e]=Array.isArray(s)?String(s[0]):String(s));return t}function _(i){return i&&typeof i=="object"&&typeof i.message=="string"?i.message:null}function T(i,t){return t&&i&&typeof i=="object"?f(i,t):i}class y extends Error{constructor(t,e,s){super(_(e)??`Request failed with status ${t}`),this.name="ApixError",this.status=t,this.body=e,this.response=s,this.errors=e&&typeof e=="object"&&e.errors&&typeof e.errors=="object"?e.errors:{}}get isValidationError(){return this.status>=400&&this.status<500&&Object.keys(this.errors).length>0}}function E(i){return i instanceof Error&&i.name==="AbortError"}function S(i){const t=[],e=(r,o)=>{t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`)},s=(r,o)=>{if(r!=null){if(typeof r=="boolean")return e(o,r?"1":"0");if(r instanceof Date)return e(o,r.toISOString());if(Array.isArray(r)){r.forEach((a,n)=>s(a,`${o}[${n}]`));return}if(typeof r=="object"){for(const[a,n]of Object.entries(r))s(n,`${o}[${a}]`);return}e(o,String(r))}};for(const[r,o]of Object.entries(i))s(o,r);return t.join("&")}async function k(i){if(i.status===204)return null;const t=await i.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}class R{constructor(t,e={},s=null){this._snapshot=null,this._snapshotLocked=!1,this._stopWatch=null,this._debounceTimer=null,this._watched=null,this._watchOptions={},this._lastSent=null,this._fillAbort=null,this._transformResponse=null,this._transformRequest=null,this._apix=t,this._options=e,this._source=s,this._transformResponse=e.transformResponse??null,this._transformRequest=e.transformRequest??null;const r=e.default?e.default():null;this._state=d.reactive({data:r,errors:{},message:null,processing:!1}),this._snapshot=c(r)}get data(){return this._state.data}set data(t){this._state.data=t}get errors(){return this._state.errors}get message(){return this._state.message}get processing(){return this._state.processing}get hasErrors(){return Object.keys(this._state.errors).length>0}get isDirty(){return JSON.stringify(this._state.data)!==JSON.stringify(this._snapshot)}get(t){return c(f(this._state.data,t))}setData(t){return this._state.data=c(t),this._proxy}error(t){const e=this._state.errors;if(e[t]!==void 0)return e[t];const s=`${t}.`;for(const r of Object.keys(e))if(r.startsWith(s))return e[r]}setErrors(t){return this._state.errors=x(t),this._proxy}clearErrors(t){if(!t)return this._state.errors={},this._proxy;for(const e of t){const s=`${e}.`;for(const r of Object.keys(this._state.errors))(r===e||r.startsWith(s))&&delete this._state.errors[r]}return this._proxy}reset(t){if(t===void 0||Array.isArray(t)&&t.length===0)return this._state.data=c(this._snapshot),this._state.errors={},this._state.message=null,this._proxy;const e=Array.isArray(t)?t:[t];if(this._state.data&&typeof this._state.data=="object")for(const s of e)m(this._state.data,s,c(f(this._snapshot,s)));return this.clearErrors(e),this._proxy}post(t,e){return this._submit("post",t,e)}put(t,e){return this._submit("put",t,e)}patch(t,e){return this._submit("patch",t,e)}delete(t,e){return this._submit("delete",t,e)}reload(t){var e;return t&&(this._source={url:t,method:((e=this._source)==null?void 0:e.method)??"get"}),this._source?this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}refresh(){return this._source?this._stopWatch?(this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._lastSent=this._payloadJson(),this._fill(this._watchExtra())):this._fill():Promise.reject(new Error("[vue-apix] The model has no source URL. Use apix.getForm(url) or model.reload(url)."))}transformResponse(t){return this._transformResponse=t,this._proxy}transformRequest(t){return this._transformRequest=t,this._proxy}watch(t,e){let s=null,r;Array.isArray(t)?(s=t,r=e??{}):r=t??e??{},this._source||console.warn("[vue-apix] model.watch() has no effect until the model has a source URL (getForm/postForm/reload)."),this.unwatch(),this._watched=s,this._watchOptions=r,this._syncLastSent();const o=s&&s.length?s.map(a=>()=>f(this._state.data,a)):()=>this._state.data;return this._stopWatch=d.watch(o,()=>this._onWatchTrigger(),{deep:r.deep??!0}),this._proxy}unwatch(){var t;return(t=this._stopWatch)==null||t.call(this),this._stopWatch=null,this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._proxy}async _fill(t={}){var o,a,n,h,u;const e=this._source;(o=this._fillAbort)==null||o.abort();const s=new AbortController;this._fillAbort=s,this._state.processing=!0;const r={signal:s.signal};e.method==="get"?r.params={...this._options.params,...t.params}:(r.params=this._options.params,r.data=t.data!==void 0?t.data:this._options.data);try{const l=await this._apix.request(e.method,e.url,r);let p=T(l,this._options.path);if(this._transformResponse){const b=c(p);p=this._transformResponse(b,l)??b}return this._applyFill(p,t.preserve??null),this._state.message=_(l),this._state.errors={},(n=(a=this._options).onSuccess)==null||n.call(a,l,this._proxy),l}catch(l){throw E(l)||(this._applyError(l),(u=(h=this._options).onError)==null||u.call(h,l,this._proxy)),l}finally{this._fillAbort===s&&(this._fillAbort=null,this._state.processing=!1)}}_applyFill(t,e){let s=c(t);this._options.mergeDefaults!==!1&&this._options.default&&(s=O(s,this._options.default()));const r=this._snapshotLocked?null:c(s);if(e&&e.length&&s&&typeof s=="object"&&this._state.data&&typeof this._state.data=="object")for(const o of e){const a=f(this._state.data,o);a!==void 0&&m(s,o,c(a))}this._state.data=s,this._snapshotLocked||(this._snapshot=r,this._snapshotLocked=!0),this._syncLastSent()}_applyError(t){t instanceof y&&(this._state.message=_(t.body)??t.message,t.isValidationError&&(this._state.errors=x(t.errors)))}async _submit(t,e,s={}){var a;const r=e??((a=this._source)==null?void 0:a.url);if(!r)throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);let o=s.data!==void 0?s.data:s.only?w(this._state.data,s.only):this._state.data??void 0;if(s.data===void 0&&this._transformRequest&&o!==void 0){const n=c(o);o=this._transformRequest(n)??n}this._state.processing=!0,this._state.errors={},this._state.message=null;try{const n=await this._apix.request(t,r,{data:o,params:s.params,headers:s.headers});return this._state.message=_(n),n}catch(n){throw this._applyError(n),n}finally{this._state.processing=!1}}_onWatchTrigger(){if(this._payloadJson()===this._lastSent)return;this._debounceTimer&&clearTimeout(this._debounceTimer);const t=this._watchOptions.debounce??0;t>0?this._debounceTimer=setTimeout(()=>this._sendWatchRequest(),t):this._sendWatchRequest()}_sendWatchRequest(){this._debounceTimer=null,this._source&&(this._lastSent=this._payloadJson(),this._fill(this._watchExtra()).catch(()=>{}))}_watchExtra(){const t=this._watched,e=this._watchOptions.payload??t;let s=e&&e.length?w(this._state.data,e):c(this._state.data);this._transformRequest&&(s=this._transformRequest(s)??s);const r=this._watchOptions.refreshWatched?null:t;return this._source.method==="get"?{params:s,preserve:r}:{data:s,preserve:r}}_payloadJson(){const t=this._watched,e=t&&t.length?t.map(s=>f(this._state.data,s)):this._state.data;return JSON.stringify(e)??"undefined"}_syncLastSent(){this._lastSent=this._payloadJson()}}function j(i,t={},e=null){const s=new R(i,t,e),r=new Proxy(s,{get(o,a){if(typeof a=="symbol"||a in o)return Reflect.get(o,a);const n=o._state.data;if(n&&typeof n=="object")return n[a]},set(o,a,n){if(typeof a=="symbol"||a in o)return Reflect.set(o,a,n);const h=o._state.data;return h&&typeof h=="object"?(h[a]=n,!0):(o._state.data={[a]:n},!0)},has(o,a){if(a in o)return!0;const n=o._state.data;return!!n&&typeof n=="object"&&a in n}});return s._proxy=r,e&&t.immediate!==!1&&r.reload().catch(()=>{}),r}class v{constructor(t={}){this.baseUrl="",this.headers={},this.processingHooks=[],this.errorHooks=[],this.bodyTransformer=null,this.active=0,t.baseUrl&&this.setBaseUrl(t.baseUrl),t.headers&&this.setHeader(t.headers),t.credentials&&(this.credentials=t.credentials)}setBaseUrl(t){return this.baseUrl=t.replace(/\/+$/,""),this}setHeader(t){return Object.assign(this.headers,t),this}setCredentials(t){return this.credentials=t,this}onProcessing(t){return this.processingHooks.push(t),()=>{this.processingHooks=this.processingHooks.filter(e=>e!==t)}}onError(t){return this.errorHooks.push(t),()=>{this.errorHooks=this.errorHooks.filter(e=>e!==t)}}transformResponse(t){return this.bodyTransformer=t,this}async request(t,e,s={}){let r=/^https?:\/\//i.test(e)?e:this.baseUrl+e;if(s.params){const h=S(s.params);h&&(r+=(r.includes("?")?"&":"?")+h)}const o={accept:"application/json","x-requested-with":"XMLHttpRequest"};for(const[h,u]of Object.entries(this.headers)){const l=typeof u=="function"?u():u;l!=null&&(o[h.toLowerCase()]=l)}for(const[h,u]of Object.entries(s.headers??{}))o[h.toLowerCase()]=u;const a={method:t.toUpperCase(),headers:o,signal:s.signal};this.credentials&&(a.credentials=this.credentials),s.data!==void 0&&t!=="get"&&(typeof FormData<"u"&&s.data instanceof FormData?(delete o["content-type"],a.body=s.data):(o["content-type"]??(o["content-type"]="application/json"),a.body=JSON.stringify(s.data)));const n={method:t,url:r,options:s};this.trackStart();try{const h=await fetch(r,a);let u=await k(h);if(this.bodyTransformer&&(u=this.bodyTransformer(u,n)??u),!h.ok)throw new y(h.status,u,h);return u}catch(h){throw E(h)?h:this.emitError(h,n)}finally{this.trackEnd()}}get(t,e,s={}){return this.request("get",t,e?{...s,params:e}:s)}post(t,e,s={}){return this.request("post",t,e!==void 0?{...s,data:e}:s)}put(t,e,s={}){return this.request("put",t,e!==void 0?{...s,data:e}:s)}patch(t,e,s={}){return this.request("patch",t,e!==void 0?{...s,data:e}:s)}delete(t,e,s={}){return this.request("delete",t,e!==void 0?{...s,data:e}:s)}form(t,e={}){return j(this,{...e,default:typeof t=="function"?t:()=>c(t)})}getForm(t,e){return this.createFormModel("get",t,e)}postForm(t,e){return this.createFormModel("post",t,e)}createFormModel(t,e,s){const r=typeof s=="string"?{path:s}:{...s??{}};return j(this,r,{url:e,method:t})}trackStart(){++this.active===1&&this.emitProcessing(!0)}trackEnd(){--this.active===0&&this.emitProcessing(!1)}emitProcessing(t){for(const e of this.processingHooks)try{e(t)}catch{}}emitError(t,e){let s=t;for(const r of this.errorHooks)try{const o=r(s,e);o instanceof Error&&(s=o)}catch{}return s}}function A(i={}){return new v(i)}const q=A();exports.Apix=v;exports.ApixError=y;exports.ApixFormModel=R;exports.apix=q;exports.createApix=A;exports.default=q;
|
package/dist/vue-apix.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { toRaw as
|
|
1
|
+
import { toRaw as R, reactive as E, watch as v } from "vue";
|
|
2
2
|
function c(i) {
|
|
3
|
-
const t =
|
|
3
|
+
const t = R(i);
|
|
4
4
|
if (t === null || typeof t != "object") return t;
|
|
5
5
|
if (Array.isArray(t)) return t.map((s) => c(s));
|
|
6
6
|
if (t instanceof Date) return new Date(t.getTime());
|
|
@@ -44,7 +44,7 @@ function d(i, t, e) {
|
|
|
44
44
|
}
|
|
45
45
|
r[s[s.length - 1]] = e;
|
|
46
46
|
}
|
|
47
|
-
function
|
|
47
|
+
function b(i, t) {
|
|
48
48
|
const e = {};
|
|
49
49
|
for (const s of t) {
|
|
50
50
|
const r = f(i, s);
|
|
@@ -52,7 +52,7 @@ function g(i, t) {
|
|
|
52
52
|
}
|
|
53
53
|
return e;
|
|
54
54
|
}
|
|
55
|
-
function
|
|
55
|
+
function g(i) {
|
|
56
56
|
const t = {};
|
|
57
57
|
for (const [e, s] of Object.entries(i ?? {}))
|
|
58
58
|
s != null && (t[e] = Array.isArray(s) ? String(s[0]) : String(s));
|
|
@@ -61,9 +61,8 @@ function b(i) {
|
|
|
61
61
|
function _(i) {
|
|
62
62
|
return i && typeof i == "object" && typeof i.message == "string" ? i.message : null;
|
|
63
63
|
}
|
|
64
|
-
function
|
|
65
|
-
|
|
66
|
-
return t ? f(e, t) : e;
|
|
64
|
+
function q(i, t) {
|
|
65
|
+
return t && i && typeof i == "object" ? f(i, t) : i;
|
|
67
66
|
}
|
|
68
67
|
class j extends Error {
|
|
69
68
|
constructor(t, e, s) {
|
|
@@ -78,10 +77,10 @@ class j extends Error {
|
|
|
78
77
|
return this.status >= 400 && this.status < 500 && Object.keys(this.errors).length > 0;
|
|
79
78
|
}
|
|
80
79
|
}
|
|
81
|
-
function
|
|
80
|
+
function O(i) {
|
|
82
81
|
return i instanceof Error && i.name === "AbortError";
|
|
83
82
|
}
|
|
84
|
-
function
|
|
83
|
+
function A(i) {
|
|
85
84
|
const t = [], e = (r, o) => {
|
|
86
85
|
t.push(`${encodeURIComponent(r)}=${encodeURIComponent(o)}`);
|
|
87
86
|
}, s = (r, o) => {
|
|
@@ -116,7 +115,7 @@ class S {
|
|
|
116
115
|
constructor(t, e = {}, s = null) {
|
|
117
116
|
this._snapshot = null, this._snapshotLocked = !1, this._stopWatch = null, this._debounceTimer = null, this._watched = null, this._watchOptions = {}, this._lastSent = null, this._fillAbort = null, this._transformResponse = null, this._transformRequest = null, this._apix = t, this._options = e, this._source = s, this._transformResponse = e.transformResponse ?? null, this._transformRequest = e.transformRequest ?? null;
|
|
118
117
|
const r = e.default ? e.default() : null;
|
|
119
|
-
this._state =
|
|
118
|
+
this._state = E({ data: r, errors: {}, message: null, processing: !1 }), this._snapshot = c(r);
|
|
120
119
|
}
|
|
121
120
|
// --- reactive state ---------------------------------------------------------
|
|
122
121
|
get data() {
|
|
@@ -167,7 +166,7 @@ class S {
|
|
|
167
166
|
if (r.startsWith(s)) return e[r];
|
|
168
167
|
}
|
|
169
168
|
setErrors(t) {
|
|
170
|
-
return this._state.errors =
|
|
169
|
+
return this._state.errors = g(t), this._proxy;
|
|
171
170
|
}
|
|
172
171
|
/** Clear all errors, or only the given keys (including their `key.*` sub-errors). */
|
|
173
172
|
clearErrors(t) {
|
|
@@ -255,7 +254,7 @@ class S {
|
|
|
255
254
|
let s = null, r;
|
|
256
255
|
Array.isArray(t) ? (s = t, r = e ?? {}) : r = t ?? e ?? {}, this._source || console.warn("[vue-apix] model.watch() has no effect until the model has a source URL (getForm/postForm/reload)."), this.unwatch(), this._watched = s, this._watchOptions = r, this._syncLastSent();
|
|
257
256
|
const o = s && s.length ? s.map((a) => () => f(this._state.data, a)) : () => this._state.data;
|
|
258
|
-
return this._stopWatch =
|
|
257
|
+
return this._stopWatch = v(o, () => this._onWatchTrigger(), {
|
|
259
258
|
deep: r.deep ?? !0
|
|
260
259
|
}), this._proxy;
|
|
261
260
|
}
|
|
@@ -275,14 +274,14 @@ class S {
|
|
|
275
274
|
e.method === "get" ? r.params = { ...this._options.params, ...t.params } : (r.params = this._options.params, r.data = t.data !== void 0 ? t.data : this._options.data);
|
|
276
275
|
try {
|
|
277
276
|
const l = await this._apix.request(e.method, e.url, r);
|
|
278
|
-
let p =
|
|
277
|
+
let p = q(l, this._options.path);
|
|
279
278
|
if (this._transformResponse) {
|
|
280
279
|
const m = c(p);
|
|
281
280
|
p = this._transformResponse(m, l) ?? m;
|
|
282
281
|
}
|
|
283
282
|
return this._applyFill(p, t.preserve ?? null), this._state.message = _(l), this._state.errors = {}, (n = (a = this._options).onSuccess) == null || n.call(a, l, this._proxy), l;
|
|
284
283
|
} catch (l) {
|
|
285
|
-
throw
|
|
284
|
+
throw O(l) || (this._applyError(l), (u = (h = this._options).onError) == null || u.call(h, l, this._proxy)), l;
|
|
286
285
|
} finally {
|
|
287
286
|
this._fillAbort === s && (this._fillAbort = null, this._state.processing = !1);
|
|
288
287
|
}
|
|
@@ -299,14 +298,14 @@ class S {
|
|
|
299
298
|
this._state.data = s, this._snapshotLocked || (this._snapshot = r, this._snapshotLocked = !0), this._syncLastSent();
|
|
300
299
|
}
|
|
301
300
|
_applyError(t) {
|
|
302
|
-
t instanceof j && (this._state.message = _(t.body) ?? t.message, t.isValidationError && (this._state.errors =
|
|
301
|
+
t instanceof j && (this._state.message = _(t.body) ?? t.message, t.isValidationError && (this._state.errors = g(t.errors)));
|
|
303
302
|
}
|
|
304
303
|
async _submit(t, e, s = {}) {
|
|
305
304
|
var a;
|
|
306
305
|
const r = e ?? ((a = this._source) == null ? void 0 : a.url);
|
|
307
306
|
if (!r)
|
|
308
307
|
throw new Error(`[vue-apix] The model has no URL. Pass one explicitly: model.${t}(url).`);
|
|
309
|
-
let o = s.data !== void 0 ? s.data : s.only ?
|
|
308
|
+
let o = s.data !== void 0 ? s.data : s.only ? b(this._state.data, s.only) : this._state.data ?? void 0;
|
|
310
309
|
if (s.data === void 0 && this._transformRequest && o !== void 0) {
|
|
311
310
|
const n = c(o);
|
|
312
311
|
o = this._transformRequest(n) ?? n;
|
|
@@ -338,7 +337,7 @@ class S {
|
|
|
338
337
|
/** Build the fill() extra for a watch-shaped request from the current state. */
|
|
339
338
|
_watchExtra() {
|
|
340
339
|
const t = this._watched, e = this._watchOptions.payload ?? t;
|
|
341
|
-
let s = e && e.length ?
|
|
340
|
+
let s = e && e.length ? b(this._state.data, e) : c(this._state.data);
|
|
342
341
|
this._transformRequest && (s = this._transformRequest(s) ?? s);
|
|
343
342
|
const r = this._watchOptions.refreshWatched ? null : t;
|
|
344
343
|
return this._source.method === "get" ? { params: s, preserve: r } : { data: s, preserve: r };
|
|
@@ -415,7 +414,7 @@ class k {
|
|
|
415
414
|
async request(t, e, s = {}) {
|
|
416
415
|
let r = /^https?:\/\//i.test(e) ? e : this.baseUrl + e;
|
|
417
416
|
if (s.params) {
|
|
418
|
-
const h =
|
|
417
|
+
const h = A(s.params);
|
|
419
418
|
h && (r += (r.includes("?") ? "&" : "?") + h);
|
|
420
419
|
}
|
|
421
420
|
const o = {
|
|
@@ -438,7 +437,7 @@ class k {
|
|
|
438
437
|
if (this.bodyTransformer && (u = this.bodyTransformer(u, n) ?? u), !h.ok) throw new j(h.status, u, h);
|
|
439
438
|
return u;
|
|
440
439
|
} catch (h) {
|
|
441
|
-
throw
|
|
440
|
+
throw O(h) ? h : this.emitError(h, n);
|
|
442
441
|
} finally {
|
|
443
442
|
this.trackEnd();
|
|
444
443
|
}
|
|
@@ -505,12 +504,12 @@ class k {
|
|
|
505
504
|
function U(i = {}) {
|
|
506
505
|
return new k(i);
|
|
507
506
|
}
|
|
508
|
-
const
|
|
507
|
+
const L = U();
|
|
509
508
|
export {
|
|
510
509
|
k as Apix,
|
|
511
510
|
j as ApixError,
|
|
512
|
-
S as
|
|
513
|
-
|
|
511
|
+
S as ApixFormModel,
|
|
512
|
+
L as apix,
|
|
514
513
|
U as createApix,
|
|
515
|
-
|
|
514
|
+
L as default
|
|
516
515
|
};
|