nuxt-precognition 0.1.2 → 0.1.4
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 +1 -397
- package/dist/module.json +1 -1
- package/dist/runtime/core.d.ts +1 -1
- package/dist/runtime/core.js +1 -1
- package/dist/runtime/server/definePrecognitiveEventHandler.d.ts +1 -1
- package/dist/runtime/types/core.d.ts +4 -1
- package/dist/runtime/types/form.d.ts +24 -2
- package/dist/runtime/useForm.d.ts +2 -2
- package/dist/runtime/useForm.js +2 -0
- package/dist/runtime/validator.d.ts +3 -2
- package/dist/runtime/validator.js +6 -2
- package/package.json +6 -3
package/README.md
CHANGED
|
@@ -20,26 +20,6 @@
|
|
|
20
20
|
|
|
21
21
|
Nuxt Precognition is a validation module for Nuxt that implements the [Precognition protocol](https://laravel.com/docs/10.x/precognition) in a backend-agnostic way. It supports any backend or validation library, and is not tied to Laravel.
|
|
22
22
|
|
|
23
|
-
## Table of Contents
|
|
24
|
-
|
|
25
|
-
- [Nuxt Precognition](#nuxt-precognition)
|
|
26
|
-
- [Table of Contents](#table-of-contents)
|
|
27
|
-
- [Requirements](#requirements)
|
|
28
|
-
- [Why Nuxt Precognition?](#why-nuxt-precognition)
|
|
29
|
-
- [Quick Example](#quick-example)
|
|
30
|
-
- [Features](#features)
|
|
31
|
-
- [Installation](#installation)
|
|
32
|
-
- [How It Works](#how-it-works)
|
|
33
|
-
- [Define Zod Error Parser](#define-zod-error-parser)
|
|
34
|
-
- [Client Side Validation](#client-side-validation)
|
|
35
|
-
- [Server Side Validation](#server-side-validation)
|
|
36
|
-
- [Precognition Protocol](#precognition-protocol)
|
|
37
|
-
- [Configuration](#configuration)
|
|
38
|
-
- [Options](#options)
|
|
39
|
-
- [Status Handlers](#status-handlers)
|
|
40
|
-
- [Laravel Integration](#laravel-integration)
|
|
41
|
-
- [Contributing](#contributing)
|
|
42
|
-
- [License](#license)
|
|
43
23
|
|
|
44
24
|
## Requirements
|
|
45
25
|
|
|
@@ -72,13 +52,7 @@ const form = useForm(
|
|
|
72
52
|
|
|
73
53
|
---
|
|
74
54
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
- Laravel compliant
|
|
78
|
-
- Validation library agnostic
|
|
79
|
-
- Client and server side validation
|
|
80
|
-
- TypeScript support
|
|
81
|
-
- Customizable error parsing and status handling
|
|
55
|
+
[Official Documentation](https://precognition.presot-studio.it/)
|
|
82
56
|
|
|
83
57
|
---
|
|
84
58
|
|
|
@@ -92,376 +66,6 @@ npx nuxi module add nuxt-precognition
|
|
|
92
66
|
|
|
93
67
|
---
|
|
94
68
|
|
|
95
|
-
## How It Works
|
|
96
|
-
|
|
97
|
-
The core concept is **error parsers**: functions that extract validation errors from thrown errors.
|
|
98
|
-
|
|
99
|
-
```ts
|
|
100
|
-
type ValidationErrors = Record<string, string | string[]>
|
|
101
|
-
|
|
102
|
-
interface ValidationErrorsData {
|
|
103
|
-
message: string
|
|
104
|
-
errors: ValidationErrors
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
type ValidationErrorParser = (error: Error) => ValidationErrorsData | undefined | null
|
|
108
|
-
```
|
|
109
|
-
|
|
110
|
-
### Define Zod Error Parser
|
|
111
|
-
|
|
112
|
-
```ts
|
|
113
|
-
// app/utils/precognition.ts or shared/utils/precognition.ts
|
|
114
|
-
import { ZodError } from 'zod'
|
|
115
|
-
|
|
116
|
-
export const zodPrecognitionErrorParser: ValidationErrorParser = (error) => {
|
|
117
|
-
if (error instanceof ZodError) {
|
|
118
|
-
const errors: Record<string, string[]> = {}
|
|
119
|
-
for (const issue of error.issues) {
|
|
120
|
-
const key = issue.path.join('.')
|
|
121
|
-
if (key in errors) {
|
|
122
|
-
errors[key].push(issue.message)
|
|
123
|
-
continue
|
|
124
|
-
}
|
|
125
|
-
errors[key] = [issue.message]
|
|
126
|
-
}
|
|
127
|
-
return { errors, message: error.message }
|
|
128
|
-
}
|
|
129
|
-
return null
|
|
130
|
-
}
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
> **Note:**
|
|
134
|
-
> For Server side validation, place this file in `shared/utils` folder.
|
|
135
|
-
|
|
136
|
-
### Client Side Validation
|
|
137
|
-
|
|
138
|
-
Add the parser client side globally.
|
|
139
|
-
|
|
140
|
-
```ts
|
|
141
|
-
// app/plugins/precognition.ts
|
|
142
|
-
export default defineNuxtPlugin(() => {
|
|
143
|
-
const { $precognition } = useNuxtApp()
|
|
144
|
-
|
|
145
|
-
$precognition.errorParsers.push(zodErrorParser)
|
|
146
|
-
|
|
147
|
-
// ..
|
|
148
|
-
})
|
|
149
|
-
```
|
|
150
|
-
|
|
151
|
-
Use the composable in setup method.
|
|
152
|
-
```ts
|
|
153
|
-
const UserSchema = z.object({
|
|
154
|
-
email: z.string().email(),
|
|
155
|
-
password: z.string().min(8),
|
|
156
|
-
})
|
|
157
|
-
|
|
158
|
-
const form = useForm(
|
|
159
|
-
(): z.infer<typeof UserSchema> => ({
|
|
160
|
-
email: '',
|
|
161
|
-
password: '',
|
|
162
|
-
}),
|
|
163
|
-
(body, headers) => $fetch('/api/login', {
|
|
164
|
-
method: 'POST',
|
|
165
|
-
headers,
|
|
166
|
-
body,
|
|
167
|
-
}),
|
|
168
|
-
{
|
|
169
|
-
clientValidation(data) {
|
|
170
|
-
UserSchema.parse(data)
|
|
171
|
-
},
|
|
172
|
-
},
|
|
173
|
-
)
|
|
174
|
-
|
|
175
|
-
function login() {
|
|
176
|
-
form.submit()
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
function reset() {
|
|
180
|
-
form.reset()
|
|
181
|
-
document.getElementById('email')?.focus()
|
|
182
|
-
}
|
|
183
|
-
```
|
|
184
|
-
|
|
185
|
-
```html
|
|
186
|
-
<form
|
|
187
|
-
@submit.prevent="login"
|
|
188
|
-
@reset.prevent="reset"
|
|
189
|
-
>
|
|
190
|
-
<div>
|
|
191
|
-
<label for="email">Email address</label>
|
|
192
|
-
<input
|
|
193
|
-
id="email"
|
|
194
|
-
v-model="form.email"
|
|
195
|
-
name="email"
|
|
196
|
-
type="email"
|
|
197
|
-
@change="form.validate('email')"
|
|
198
|
-
>
|
|
199
|
-
<span v-if="form.valid('email')">OK!!</span>
|
|
200
|
-
<span v-if="form.invalid('email')">{{ form.errors.email }}</span>
|
|
201
|
-
</div>
|
|
202
|
-
|
|
203
|
-
<div>
|
|
204
|
-
<label for="password">Password</label>
|
|
205
|
-
<input
|
|
206
|
-
id="password"
|
|
207
|
-
v-model="form.password"
|
|
208
|
-
name="password"
|
|
209
|
-
type="password"
|
|
210
|
-
autocomplete="current-password"
|
|
211
|
-
required
|
|
212
|
-
@change="form.validate('password')"
|
|
213
|
-
>
|
|
214
|
-
<span v-if="form.valid('password')">OK!!</span>
|
|
215
|
-
<span v-if="form.invalid('password')">{{ form.errors.password }}</span>
|
|
216
|
-
</div>
|
|
217
|
-
|
|
218
|
-
<div>
|
|
219
|
-
<button type="submit">Sign in</button>
|
|
220
|
-
<button type="reset">Reset</button>
|
|
221
|
-
</div>
|
|
222
|
-
</form>
|
|
223
|
-
```
|
|
224
|
-
|
|
225
|
-
### Server Side Validation
|
|
226
|
-
|
|
227
|
-
1. update the default configuration.
|
|
228
|
-
```ts
|
|
229
|
-
// nuxt.config.ts
|
|
230
|
-
|
|
231
|
-
export default defineNuxtConfig({
|
|
232
|
-
modules: [
|
|
233
|
-
'nuxt-precognition'
|
|
234
|
-
],
|
|
235
|
-
precognition: {
|
|
236
|
-
backendValidation: true,
|
|
237
|
-
enableNuxtClientErrorParser: true,
|
|
238
|
-
},
|
|
239
|
-
})
|
|
240
|
-
```
|
|
241
|
-
2. Create a Nitro plugin to parse server errors:
|
|
242
|
-
```ts
|
|
243
|
-
// server/plugins/precognition.ts
|
|
244
|
-
import { ZodError } from 'zod'
|
|
245
|
-
|
|
246
|
-
export default defineNitroPlugin((nitroApp) => {
|
|
247
|
-
nitroApp.hooks.hook('request', (event) => {
|
|
248
|
-
event.context.$precognition.errorParsers = [
|
|
249
|
-
zodErrorParser
|
|
250
|
-
]
|
|
251
|
-
})
|
|
252
|
-
})
|
|
253
|
-
```
|
|
254
|
-
|
|
255
|
-
3. Use `definePrecognitiveEventHandler` in the _object_ way and add validation in the `onRequest` hook.
|
|
256
|
-
```ts
|
|
257
|
-
// server/api/login.post.ts
|
|
258
|
-
import { z } from 'zod'
|
|
259
|
-
import { definePrecognitiveEventHandler, readBody } from '#imports'
|
|
260
|
-
|
|
261
|
-
const loginSchema = z.object({
|
|
262
|
-
email: z.string().email(),
|
|
263
|
-
password: z.string()
|
|
264
|
-
}).refine((_data) => {
|
|
265
|
-
// Check for email and password match
|
|
266
|
-
// ...
|
|
267
|
-
return true
|
|
268
|
-
},
|
|
269
|
-
{ message: 'invalid credentials', path: ['email'] },
|
|
270
|
-
)
|
|
271
|
-
|
|
272
|
-
export default definePrecognitiveEventHandler({
|
|
273
|
-
async onRequest(event) {
|
|
274
|
-
const body = await readBody(event)
|
|
275
|
-
loginSchema.parse(body)
|
|
276
|
-
},
|
|
277
|
-
handler: () => {
|
|
278
|
-
return {
|
|
279
|
-
status: 200,
|
|
280
|
-
body: {
|
|
281
|
-
message: 'Success',
|
|
282
|
-
},
|
|
283
|
-
}
|
|
284
|
-
},
|
|
285
|
-
})
|
|
286
|
-
```
|
|
287
|
-
---
|
|
288
|
-
|
|
289
|
-
## Precognition Protocol
|
|
290
|
-
|
|
291
|
-
If you need to define your own backend logic outside Nitro, follow these requirements.
|
|
292
|
-
|
|
293
|
-
- Precognitive Requests must have:
|
|
294
|
-
1. Precognitive Header `{ 'Precognitive': 'true' }`
|
|
295
|
-
- To validate specific variables, each keys must be specified inside the ValidateOnly Header, comma separated and leveraging dot notation `{ 'Precognition-Validate-Only': 'name,age,address.street,address.number' }`
|
|
296
|
-
- To validate the full Form the ValidateOnly Header should be omitted or define as an empty string.
|
|
297
|
-
- Successful validation response must have:
|
|
298
|
-
1. Precognitive Header `{ 'Precognitive': 'true' }`
|
|
299
|
-
2. Precognitive Successful Header `{ 'Precognition-Success': 'true' }`
|
|
300
|
-
3. Precognitive Successful status code: `204`
|
|
301
|
-
- Error validation response must have:
|
|
302
|
-
1. Precognitive Header `{ 'Precognitive': 'true' }`
|
|
303
|
-
2. Precognition-Validate-Only header if needed `{ 'Precognition-Validate-Only': 'name,age,address.street,address.number' }`
|
|
304
|
-
3. Validation Error status code: `422`
|
|
305
|
-
4. Validation Errors and Message will be parsed as per your define logic, or using standard `errorParsers`:
|
|
306
|
-
- NuxtErrorParsers: `NuxtPrecognitiveErrorResponse`: `Response & { _data: { data: ValidationErrorsData }}`
|
|
307
|
-
- LaravelErrorParsers: `LaravelPrecognitiveErrorResponse`: `Response & { _data: ValidationErrorsData }`
|
|
308
|
-
|
|
309
|
-
---
|
|
310
|
-
|
|
311
|
-
## Configuration
|
|
312
|
-
|
|
313
|
-
Add to your `nuxt.config.ts`:
|
|
314
|
-
|
|
315
|
-
```ts
|
|
316
|
-
export default defineNuxtConfig({
|
|
317
|
-
modules: ['nuxt-precognition'],
|
|
318
|
-
precognition: {
|
|
319
|
-
backendValidation: true,
|
|
320
|
-
enableNuxtClientErrorParser: true,
|
|
321
|
-
// ...other options
|
|
322
|
-
}
|
|
323
|
-
})
|
|
324
|
-
```
|
|
325
|
-
|
|
326
|
-
### Options
|
|
327
|
-
| name | type | default | description |
|
|
328
|
-
|---|---|---|---|
|
|
329
|
-
|validationTimeout|_number_|`1500`|Debounce time, in milliseconds, between two precognitive validation requests.|
|
|
330
|
-
|backendValidation|_boolean_|`false`|Flag to enable the precognitive validation.|
|
|
331
|
-
|validateFiles|_boolean_|`false`|Flag to enable files validation on precognitive requests.|
|
|
332
|
-
|enableNuxtClientErrorParser|_boolean_|`false`|Flag to enable _nuxtErrorParsers_ on client side (in `form.validate` and `form.submit`).|
|
|
333
|
-
|enableLaravelClientErrorParser|_boolean_|`false`|Flag to enable _laravelErrorParsers_ on client side (in `form.validate` and `form.submit`).|
|
|
334
|
-
|enableLaravelServerErrorParser|_boolean_|`false`|Flag to enable _laravelErrorParsers_ on server side (in `definePrecognitiveEventHandler`).|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
---
|
|
338
|
-
|
|
339
|
-
### Status Handlers
|
|
340
|
-
Like in [official package](https://github.com/laravel/precognition), you can define globally, or @instance level, custom handlers for specific error codes:
|
|
341
|
-
|
|
342
|
-
```ts
|
|
343
|
-
// plugins/precognition.ts
|
|
344
|
-
|
|
345
|
-
export default defineNuxtPlugin(() => {
|
|
346
|
-
const { $precognition } = useNuxtApp()
|
|
347
|
-
|
|
348
|
-
$precognition.statusHandlers = {
|
|
349
|
-
401: async (error, form) => {
|
|
350
|
-
form.error = createError('Unauthorized')
|
|
351
|
-
await navigateTo('/login')
|
|
352
|
-
},
|
|
353
|
-
403: async (error, form) => {
|
|
354
|
-
form.error = createError('Forbidden')
|
|
355
|
-
},
|
|
356
|
-
}
|
|
357
|
-
})
|
|
358
|
-
```
|
|
359
|
-
|
|
360
|
-
---
|
|
361
|
-
|
|
362
|
-
## Laravel Integration
|
|
363
|
-
|
|
364
|
-
If you want to use Laravel, you won't need nuxt nitro integration.
|
|
365
|
-
|
|
366
|
-
1. **Enable Backend Validation and Error Parsers:**
|
|
367
|
-
|
|
368
|
-
```ts
|
|
369
|
-
// nuxt.config.ts
|
|
370
|
-
export default defineNuxtConfig({
|
|
371
|
-
modules: ['nuxt-precognition'],
|
|
372
|
-
precognition: {
|
|
373
|
-
backendValidation: true,
|
|
374
|
-
enableLaravelClientErrorParser: true,
|
|
375
|
-
}
|
|
376
|
-
})
|
|
377
|
-
```
|
|
378
|
-
|
|
379
|
-
2. **Plugin Example:**
|
|
380
|
-
|
|
381
|
-
Add Sanctum token prefetch and ensure proper handling of all precognitive requests.
|
|
382
|
-
|
|
383
|
-
```ts
|
|
384
|
-
// plugins/laravel.ts
|
|
385
|
-
export default defineNuxtPlugin((app) => {
|
|
386
|
-
const { $precognition } = useNuxtApp()
|
|
387
|
-
const token = useCookie('XSRF-TOKEN')
|
|
388
|
-
|
|
389
|
-
const api = $fetch.create({
|
|
390
|
-
baseURL: 'http://localhost',
|
|
391
|
-
credentials: 'include',
|
|
392
|
-
headers: {
|
|
393
|
-
'Accept': 'application/json',
|
|
394
|
-
'Content-Type': 'application/json',
|
|
395
|
-
},
|
|
396
|
-
onRequest: ({ options }) => {
|
|
397
|
-
if (token.value) {
|
|
398
|
-
const headers = new Headers(options.headers)
|
|
399
|
-
headers.set('X-XSRF-TOKEN', token.value)
|
|
400
|
-
options.headers = headers
|
|
401
|
-
}
|
|
402
|
-
},
|
|
403
|
-
onResponse: (context) => {
|
|
404
|
-
// ensure non false positive validations
|
|
405
|
-
$precognition.assertSuccessfulPrecognitiveResponses(context)
|
|
406
|
-
},
|
|
407
|
-
})
|
|
408
|
-
|
|
409
|
-
async function fetchSanctumToken() {
|
|
410
|
-
try {
|
|
411
|
-
await api('/sanctum/csrf-cookie')
|
|
412
|
-
token.value = useCookie('XSRF-TOKEN').value
|
|
413
|
-
if (!token.value) throw new Error('Failed to get CSRF token')
|
|
414
|
-
} catch (e) {
|
|
415
|
-
console.error(e)
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
app.hook('app:mounted', fetchSanctumToken)
|
|
420
|
-
|
|
421
|
-
return {
|
|
422
|
-
provide: {
|
|
423
|
-
api,
|
|
424
|
-
sanctum: {
|
|
425
|
-
fetchToken: fetchSanctumToken,
|
|
426
|
-
token,
|
|
427
|
-
},
|
|
428
|
-
},
|
|
429
|
-
}
|
|
430
|
-
})
|
|
431
|
-
```
|
|
432
|
-
|
|
433
|
-
3. **Laravel CORS Configuration:**
|
|
434
|
-
|
|
435
|
-
Ensure Precognitive headers will be shared with Nuxt application.
|
|
436
|
-
|
|
437
|
-
```php
|
|
438
|
-
// config/cors.php
|
|
439
|
-
return [
|
|
440
|
-
'paths' => ['*'],
|
|
441
|
-
'allowed_methods' => ['*'],
|
|
442
|
-
'allowed_origins' => ['*'],
|
|
443
|
-
'allowed_origins_patterns' => [env('FRONTEND_URL', 'http://localhost:3000')],
|
|
444
|
-
'allowed_headers' => ['*'],
|
|
445
|
-
'exposed_headers' => ['Precognition', 'Precognition-Success'],
|
|
446
|
-
'max_age' => 0,
|
|
447
|
-
'supports_credentials' => true,
|
|
448
|
-
];
|
|
449
|
-
```
|
|
450
|
-
|
|
451
|
-
4. **Enable Precognition Middleware:**
|
|
452
|
-
|
|
453
|
-
Apply precognitive middleware where needed.
|
|
454
|
-
|
|
455
|
-
```php
|
|
456
|
-
// routes/api.php
|
|
457
|
-
Route::middleware('precognitive')->group(function () {
|
|
458
|
-
Route::apiResource('posts', \App\Http\Controllers\PostController::class);
|
|
459
|
-
});
|
|
460
|
-
```
|
|
461
|
-
|
|
462
|
-
That's it. Nuxt validation will be in sync with Laravel!!.
|
|
463
|
-
|
|
464
|
-
---
|
|
465
69
|
|
|
466
70
|
## Contributing
|
|
467
71
|
|
package/dist/module.json
CHANGED
package/dist/runtime/core.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export declare function resolveDynamicObject<T extends object>(object: T | (() =
|
|
|
7
7
|
export declare function requestPrecognitiveHeaders(headers?: HeadersInit, keys?: string[]): Headers;
|
|
8
8
|
export declare function getAllNestedKeys<TData extends object, TPrefix extends string | undefined = undefined>(obj: TData, prefix?: TPrefix, keys?: string[]): TPrefix extends undefined ? NestedKeyOf<TData>[] : string[];
|
|
9
9
|
export declare function isFile(value: unknown): value is Blob | File | FileList;
|
|
10
|
-
export declare function resolveValidationErrorData(error: Error, parsers: ValidationErrorParser[]): ValidationErrorsData | null | undefined;
|
|
10
|
+
export declare function resolveValidationErrorData<TResp>(error: Error, parsers: ValidationErrorParser<TResp>[]): ValidationErrorsData | null | undefined;
|
|
11
11
|
export declare function makeNuxtValidationErrorParser(): ValidationErrorParser;
|
|
12
12
|
export declare function makeLaravelValidationErrorParser(): ValidationErrorParser;
|
|
13
13
|
/**
|
package/dist/runtime/core.js
CHANGED
|
@@ -51,7 +51,7 @@ export function isFile(value) {
|
|
|
51
51
|
}
|
|
52
52
|
export function resolveValidationErrorData(error, parsers) {
|
|
53
53
|
return parsers.reduce(
|
|
54
|
-
(errors, parser) => errors ?? parser(error),
|
|
54
|
+
(errors, parser) => errors ?? (typeof parser === "function" ? parser(error) : parser.errorParser(error)),
|
|
55
55
|
null
|
|
56
56
|
);
|
|
57
57
|
}
|
|
@@ -2,7 +2,7 @@ import type { EventHandler, EventHandlerObject, EventHandlerRequest } from 'h3';
|
|
|
2
2
|
import type { ValidationErrorParser } from '../types/core.js';
|
|
3
3
|
import type { ServerStatusHandlers } from '../types/eventHandler.js';
|
|
4
4
|
declare function definePrecognitiveEventHandler<TRequest extends EventHandlerRequest, TResponse>(handler: EventHandlerObject<TRequest, TResponse>, options?: {
|
|
5
|
-
errorParsers?: ValidationErrorParser[];
|
|
5
|
+
errorParsers?: ValidationErrorParser<TResponse>[];
|
|
6
6
|
statusHandlers?: ServerStatusHandlers;
|
|
7
7
|
}): EventHandler<TRequest, TResponse>;
|
|
8
8
|
declare namespace definePrecognitiveEventHandler {
|
|
@@ -3,5 +3,8 @@ export interface ValidationErrorsData {
|
|
|
3
3
|
message: string;
|
|
4
4
|
errors: ValidationErrors;
|
|
5
5
|
}
|
|
6
|
-
export type ValidationErrorParser = (error: Error) => ValidationErrorsData | undefined | null
|
|
6
|
+
export type ValidationErrorParser<TResp = unknown> = ((error: Error) => ValidationErrorsData | undefined | null) | {
|
|
7
|
+
errorParser: (error: Error) => ValidationErrorsData | undefined | null;
|
|
8
|
+
responseParser: (resp: TResp) => unknown;
|
|
9
|
+
};
|
|
7
10
|
export {};
|
|
@@ -2,9 +2,31 @@ import type { ValidationErrorParser, ValidationErrorsData } from './core.js';
|
|
|
2
2
|
import type { NestedKeyOf, ErrorStatusCode } from './utils.js';
|
|
3
3
|
interface SubmitOptions<TData extends object, TResp> {
|
|
4
4
|
headers?: Headers;
|
|
5
|
+
/**
|
|
6
|
+
* callback triggered when error is captured
|
|
7
|
+
* @param error
|
|
8
|
+
* @param data
|
|
9
|
+
* @returns
|
|
10
|
+
*/
|
|
5
11
|
onError?: (error: Error, data: TData) => Promise<void> | void;
|
|
12
|
+
/**
|
|
13
|
+
* first lifecycle hook. Useful to prevent request submission.
|
|
14
|
+
* @param data
|
|
15
|
+
* @returns
|
|
16
|
+
*/
|
|
6
17
|
onBefore?: (data: TData) => Promise<boolean> | boolean;
|
|
18
|
+
/**
|
|
19
|
+
* callback triggered before starting the request.
|
|
20
|
+
* @param data
|
|
21
|
+
* @returns
|
|
22
|
+
*/
|
|
7
23
|
onStart?: (data: TData) => Promise<void> | void;
|
|
24
|
+
/**
|
|
25
|
+
* callback triggered when no errors.
|
|
26
|
+
* @param resp
|
|
27
|
+
* @param data
|
|
28
|
+
* @returns
|
|
29
|
+
*/
|
|
8
30
|
onSuccess?: (resp: TResp, data: TData) => Promise<void> | void;
|
|
9
31
|
}
|
|
10
32
|
export interface Form<TData extends object, Tresp> {
|
|
@@ -30,7 +52,7 @@ export interface Form<TData extends object, Tresp> {
|
|
|
30
52
|
export type ClientStatusHandlers = Partial<Record<ErrorStatusCode, <TData extends object, TResp>(error: Error & {
|
|
31
53
|
response: Response;
|
|
32
54
|
}, form: TData & Form<TData, TResp>) => void | Promise<void>>>;
|
|
33
|
-
export interface UseFormOptions<TData extends object> {
|
|
55
|
+
export interface UseFormOptions<TData extends object, TResp> {
|
|
34
56
|
/**
|
|
35
57
|
* Headers to be sent along with the precognition request (e.g. for authentication purposes).
|
|
36
58
|
*/
|
|
@@ -81,7 +103,7 @@ export interface UseFormOptions<TData extends object> {
|
|
|
81
103
|
/**
|
|
82
104
|
* Any custom error parser that should specifically be used for this form instance when handling validation errors.
|
|
83
105
|
*/
|
|
84
|
-
clientErrorParsers?: ValidationErrorParser[];
|
|
106
|
+
clientErrorParsers?: ValidationErrorParser<TResp>[];
|
|
85
107
|
/**
|
|
86
108
|
* Handlers for specific client status codes.
|
|
87
109
|
*/
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Form, UseFormOptions } from './types/form.js';
|
|
2
|
-
export declare function useForm<TData extends object, TResp>(init: TData | (() => TData), cb: (form: TData, precognitiveHeaders: Headers) => Promise<TResp>, options?: UseFormOptions<TData>): TData & Form<TData, TResp>;
|
|
2
|
+
export declare function useForm<TData extends object, TResp>(init: TData | (() => TData), cb: (form: TData, precognitiveHeaders: Headers) => Promise<TResp>, options?: UseFormOptions<TData, TResp>): TData & Form<TData, TResp>;
|
|
3
3
|
export declare namespace useForm {
|
|
4
|
-
var create: <TData extends object, TResp>(_options?: UseFormOptions<TData>) => (init: TData | (() => TData), cb: (form: TData, precognitiveHeaders: Headers) => Promise<TResp>, options?: UseFormOptions<TData>) => TData & Form<TData, TResp>;
|
|
4
|
+
var create: <TData extends object, TResp>(_options?: UseFormOptions<TData, TResp>) => (init: TData | (() => TData), cb: (form: TData, precognitiveHeaders: Headers) => Promise<TResp>, options?: UseFormOptions<TData, TResp>) => TData & Form<TData, TResp>;
|
|
5
5
|
}
|
package/dist/runtime/useForm.js
CHANGED
|
@@ -60,6 +60,8 @@ export function useForm(init, cb, options) {
|
|
|
60
60
|
form.validating = false;
|
|
61
61
|
}
|
|
62
62
|
const resp = await cb(data, o?.headers ?? new Headers());
|
|
63
|
+
if (validator.responseParsers.length)
|
|
64
|
+
validator.responseParsers.forEach((p) => p(resp));
|
|
63
65
|
if (o?.onSuccess)
|
|
64
66
|
await o.onSuccess(resp, data);
|
|
65
67
|
} catch (error) {
|
|
@@ -2,9 +2,10 @@ import type { DebouncedFuncLeading } from 'lodash';
|
|
|
2
2
|
import type { NestedKeyOf } from './types/utils.js';
|
|
3
3
|
import type { ValidationErrorParser } from './types/core.js';
|
|
4
4
|
import type { ClientStatusHandlers, Form, UseFormOptions } from './types/form.js';
|
|
5
|
-
export declare function makeValidator<TData extends object, TResp>(cb: (data: TData, precognitiveHeaders: Headers) => Promise<TResp>, options?: UseFormOptions<TData>): {
|
|
5
|
+
export declare function makeValidator<TData extends object, TResp>(cb: (data: TData, precognitiveHeaders: Headers) => Promise<TResp>, options?: UseFormOptions<TData, TResp>): {
|
|
6
6
|
validate: DebouncedFuncLeading<(form: Form<TData, TResp>, ...keys: NestedKeyOf<TData>[]) => Promise<void>>;
|
|
7
|
-
errorParsers: ValidationErrorParser[];
|
|
7
|
+
errorParsers: ValidationErrorParser<TResp>[];
|
|
8
|
+
responseParsers: ((resp: TResp) => unknown)[];
|
|
8
9
|
setValidateFiles: (value: boolean) => void;
|
|
9
10
|
statusHandlers: ClientStatusHandlers;
|
|
10
11
|
};
|
|
@@ -14,6 +14,7 @@ export function makeValidator(cb, options) {
|
|
|
14
14
|
errorParsers.push(makeLaravelValidationErrorParser());
|
|
15
15
|
if (validateOptions.enableNuxtClientErrorParser)
|
|
16
16
|
errorParsers.push(makeNuxtValidationErrorParser());
|
|
17
|
+
const responseParsers = errorParsers.filter((p) => typeof p === "object").map((p) => p.responseParser);
|
|
17
18
|
const statusHandlers = { ...$precognition.statusHandlers, ...options?.statusHandlers };
|
|
18
19
|
const validate = debounce(
|
|
19
20
|
async function(form, ...keys) {
|
|
@@ -29,11 +30,13 @@ export function makeValidator(cb, options) {
|
|
|
29
30
|
await onValidationStart(data);
|
|
30
31
|
const clientValidation = validateOptions?.clientValidation ?? (() => Promise.resolve());
|
|
31
32
|
await clientValidation(data);
|
|
32
|
-
const backendValidation = validateOptions.backendValidation ? cb : () => Promise.resolve();
|
|
33
|
-
await backendValidation(
|
|
33
|
+
const backendValidation = validateOptions.backendValidation ? cb : () => Promise.resolve(void 0);
|
|
34
|
+
const resp = await backendValidation(
|
|
34
35
|
validateOptions.validateFiles ? data : withoutFiles(data),
|
|
35
36
|
headers
|
|
36
37
|
);
|
|
38
|
+
if (responseParsers.length)
|
|
39
|
+
responseParsers.forEach((p) => typeof resp === "undefined" ? void 0 : p(resp));
|
|
37
40
|
form.forgetErrors(...keys);
|
|
38
41
|
form.touch(...keys);
|
|
39
42
|
const onSuccess = validateOptions?.onValidationSuccess ?? (() => void 0);
|
|
@@ -64,6 +67,7 @@ export function makeValidator(cb, options) {
|
|
|
64
67
|
return {
|
|
65
68
|
validate,
|
|
66
69
|
errorParsers,
|
|
70
|
+
responseParsers,
|
|
67
71
|
statusHandlers,
|
|
68
72
|
setValidateFiles
|
|
69
73
|
};
|
package/package.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-precognition",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.4",
|
|
5
5
|
"description": "Nuxt module implementing Precognition protocol (inspired by official Laravel Precognition) for backend precognitive validation.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "sot1986",
|
|
8
8
|
"email": "sot@8dplus.com"
|
|
9
9
|
},
|
|
10
10
|
"license": "MIT",
|
|
11
|
-
"homepage": "https://
|
|
11
|
+
"homepage": "https://precognition.presot-studio.it",
|
|
12
12
|
"repository": {
|
|
13
13
|
"type": "git",
|
|
14
14
|
"url": "https://github.com/sot1986/nuxt-precognition"
|
|
@@ -17,7 +17,9 @@
|
|
|
17
17
|
"precognition",
|
|
18
18
|
"nuxt",
|
|
19
19
|
"laravel",
|
|
20
|
-
"zod"
|
|
20
|
+
"zod",
|
|
21
|
+
"appsync",
|
|
22
|
+
"validation"
|
|
21
23
|
],
|
|
22
24
|
"exports": {
|
|
23
25
|
".": {
|
|
@@ -55,6 +57,7 @@
|
|
|
55
57
|
"@nuxt/schema": "^3.11.2",
|
|
56
58
|
"@nuxt/test-utils": "^3.12.1",
|
|
57
59
|
"@tailwindcss/forms": "^0.5.7",
|
|
60
|
+
"@types/lodash": "^4.17.21",
|
|
58
61
|
"@types/lodash-es": "^4.17.12",
|
|
59
62
|
"@types/node": "^20.12.11",
|
|
60
63
|
"autoprefixer": "^10.4.19",
|