nuxt-precognition 0.0.3 → 0.0.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 +71 -7
- package/dist/module.json +1 -1
- package/dist/module.mjs +30 -19
- package/dist/runtime/server/definePrecognitiveEventHandler.mjs +2 -2
- package/dist/runtime/server/plugin.mjs +3 -5
- package/dist/runtime/types/eventHandler.d.ts +1 -1
- package/dist/runtime/useForm.d.ts +3 -0
- package/dist/runtime/useForm.mjs +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ const form = useForm(
|
|
|
31
31
|
)
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
-
This
|
|
34
|
+
This module comes with native __Nitro__ integration, but will work with other backend as weel, even properly configured _aws lambda_.
|
|
35
35
|
It supports any validation library (_who said [__Zod__](https://zod.dev/)??_) server or client side. You will need only to configure specific `Error parsers`.
|
|
36
36
|
|
|
37
37
|
- [✨ Release Notes](/CHANGELOG.md)
|
|
@@ -92,18 +92,20 @@ export default defineNuxtPlugin(() => {
|
|
|
92
92
|
```
|
|
93
93
|
From now on, everytime the `useForm` will catch the error, it will run our parses, and capture and assign any validation errors.
|
|
94
94
|
|
|
95
|
+
If you want to reuse same options over multiple pages, you can create your __custom composable__ by `useForm.create` factory function.
|
|
96
|
+
|
|
95
97
|
### How about server side
|
|
96
|
-
Same idea,
|
|
98
|
+
Same idea, creating a nitro plugin:
|
|
97
99
|
|
|
98
100
|
```ts
|
|
99
|
-
// server/
|
|
101
|
+
// server/plugins/precognition.ts
|
|
100
102
|
|
|
101
103
|
import { ZodError } from 'zod'
|
|
102
104
|
|
|
103
|
-
export
|
|
104
|
-
{
|
|
105
|
-
errorParsers
|
|
106
|
-
|
|
105
|
+
export default defineNitroPlugin((nitroApp) => {
|
|
106
|
+
nitroApp.hooks.hook('request', (event) => {
|
|
107
|
+
event.context.$precognition.errorParsers = [
|
|
108
|
+
(error) => {
|
|
107
109
|
if (error instanceof ZodError) {
|
|
108
110
|
const errors: Record<string, string[]> = {}
|
|
109
111
|
error.errors.forEach((e) => {
|
|
@@ -120,7 +122,46 @@ export const defineZodPrecognitiveEventHandler = definePrecognitiveEventHandler.
|
|
|
120
122
|
},
|
|
121
123
|
]
|
|
122
124
|
})
|
|
125
|
+
})
|
|
126
|
+
```
|
|
127
|
+
If you don't like hooking on every requests, you can create you custom eventHandler by `definePrecognitiveEventHandler.create` factory function.
|
|
128
|
+
|
|
129
|
+
Make your validation logic inside the `onRequest` handler of the `definePrecognitiveEventHandler`.
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
// server/api/login.post.ts
|
|
133
|
+
import { z } from 'zod'
|
|
134
|
+
import { definePrecognitiveEventHandler, readBody } from '#imports'
|
|
135
|
+
|
|
136
|
+
const loginSchema = z.object({
|
|
137
|
+
email: z.string().email().refine(_email => // Check for email uniqueness
|
|
138
|
+
true, { message: 'Email is already in use' },
|
|
139
|
+
),
|
|
140
|
+
password: z.string(),
|
|
141
|
+
}).refine((_data) => {
|
|
142
|
+
// Check for email and password match
|
|
143
|
+
// ...
|
|
144
|
+
return true
|
|
145
|
+
},
|
|
146
|
+
{ message: 'invalid credentials', path: ['email'] },
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
export default definePrecognitiveEventHandler({
|
|
150
|
+
async onRequest(event) {
|
|
151
|
+
const body = await readBody(event)
|
|
152
|
+
loginSchema.parse(body)
|
|
153
|
+
},
|
|
154
|
+
handler: () => {
|
|
155
|
+
return {
|
|
156
|
+
status: 200,
|
|
157
|
+
body: {
|
|
158
|
+
message: 'Success',
|
|
159
|
+
},
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
})
|
|
123
163
|
```
|
|
164
|
+
|
|
124
165
|
This time the error will be converted to `NuxtServerValidationError` and captured client side, if we enable the predefined parsers in the nuxt configuration file:
|
|
125
166
|
|
|
126
167
|
```ts
|
|
@@ -134,6 +175,29 @@ export default defineNuxtConfig({
|
|
|
134
175
|
}
|
|
135
176
|
})
|
|
136
177
|
```
|
|
178
|
+
__Remember to throw the `ValidationError` only in the `onRequest` handler (using the `object notation`)__.
|
|
179
|
+
Any logic in the base `handler` won't be process during `precognitiveRequests`.
|
|
180
|
+
|
|
181
|
+
* Each `event.context` include also a flag (`{ precognitive: boolean }`), indicating if request is precognitive or not, looking at presence of _Precognitive header_.
|
|
182
|
+
|
|
183
|
+
### Precognition Protocol
|
|
184
|
+
In case you need to define your own backend logic outside nitro (_AWS Lamba_), respect following list of requirements.
|
|
185
|
+
|
|
186
|
+
- Precognitive Requests must have:
|
|
187
|
+
1. Precognitive Header `{ 'Precognitive': 'true' }`
|
|
188
|
+
- 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' }`
|
|
189
|
+
- To validate the full Form the ValidateOnly Header should be omitted or define as an empty string.
|
|
190
|
+
- Successfull validation response must have:
|
|
191
|
+
1. Precognitive Header `{ 'Precognitive': 'true' }`
|
|
192
|
+
2. Precognitive Successfull Header `{ 'Precognition-Success': 'true' }`
|
|
193
|
+
3. Precognitve Successfull status code: `204`
|
|
194
|
+
- Error validation response must have:
|
|
195
|
+
1. Precognitive Header `{ 'Precognitive': 'true' }`
|
|
196
|
+
2. ValidationOnly header if needed `{ 'Precognition-Validate-Only': 'name,age,address.street,address.number' }`
|
|
197
|
+
3. Validation Error status code: `422`
|
|
198
|
+
4. Validation Errors and Message will be parsed as per your define logic, or using standard `errorParsers`:
|
|
199
|
+
- NuxtErrorParsers: `NuxtPrecognitiveErrorResponse`: `Response & { _data: { data: ValidationErrorsData }}`
|
|
200
|
+
- LaravelErrorParsers: `LaravelPrecognitiveErrorResponse`: `Response & { _data: ValidationErrorsData }`
|
|
137
201
|
|
|
138
202
|
|
|
139
203
|
## Quick Setup
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { defineNuxtModule, createResolver, addPlugin, addImports, addServerImports, addServerPlugin, addTemplate } from '@nuxt/kit';
|
|
1
|
+
import { defineNuxtModule, createResolver, addPlugin, addImports, addServerImports, addServerPlugin, addTypeTemplate, addTemplate } from '@nuxt/kit';
|
|
2
2
|
import defu from 'defu';
|
|
3
3
|
|
|
4
4
|
const module = defineNuxtModule({
|
|
@@ -45,31 +45,42 @@ const module = defineNuxtModule({
|
|
|
45
45
|
}
|
|
46
46
|
]);
|
|
47
47
|
addServerPlugin(resolver.resolve("./runtime/server/plugin"));
|
|
48
|
-
|
|
48
|
+
addTypeTemplate({
|
|
49
49
|
filename: "types/nuxt-precognition.d.ts",
|
|
50
50
|
getContents: () => `// Generated by nuxt-precognition
|
|
51
|
-
|
|
52
|
-
|
|
51
|
+
import type {ValidationErrorParser} from '${resolver.resolve("./runtime/types/core")}'
|
|
52
|
+
import type {ClientStatusHandlers} from '${resolver.resolve("./runtime/types/form")}'
|
|
53
53
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
54
|
+
interface NuxtPrecognition {
|
|
55
|
+
$precognition: {
|
|
56
|
+
errorParsers: ValidationErrorParser[],
|
|
57
|
+
statusHandlers: ClientStatusHandlers
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
declare module '#app' {
|
|
62
|
+
interface NuxtApp extends NuxtPrecognition {}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
declare module 'vue' {
|
|
66
|
+
interface ComponentCustomProperties extends NuxtPrecognition {}
|
|
67
|
+
}
|
|
60
68
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
69
|
+
export {}`
|
|
70
|
+
});
|
|
71
|
+
const nitroTemplate = addTemplate({
|
|
72
|
+
filename: "types/nuxt-precognition-server.d.ts",
|
|
73
|
+
getContents: () => `// Generated by nuxt-precognition
|
|
74
|
+
import type { PrecognitionEventContext } from '${resolver.resolve("./runtime/types/eventHandler")}'
|
|
64
75
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
76
|
+
declare module 'h3' {
|
|
77
|
+
interface H3EventContext extends PrecognitionEventContext {}
|
|
78
|
+
}
|
|
68
79
|
|
|
69
|
-
|
|
80
|
+
export {}`
|
|
70
81
|
});
|
|
71
|
-
nuxt.hook("
|
|
72
|
-
|
|
82
|
+
nuxt.hooks.hook("nitro:config", (config) => {
|
|
83
|
+
config.typescript?.tsConfig?.include?.push(nitroTemplate.dst);
|
|
73
84
|
});
|
|
74
85
|
}
|
|
75
86
|
});
|
|
@@ -42,13 +42,13 @@ function onPrecognitiveRequestWrapper(middleware, options) {
|
|
|
42
42
|
data: { message: "Unknown server error" }
|
|
43
43
|
});
|
|
44
44
|
}
|
|
45
|
-
const statusHandler = hasResponse(error) && options.statusHandlers ? options.statusHandlers[`${error.response.status}`] ?? event.context
|
|
45
|
+
const statusHandler = hasResponse(error) && options.statusHandlers ? options.statusHandlers[`${error.response.status}`] ?? event.context.$precognition.statusHandlers[`${error.response.status}`] : void 0;
|
|
46
46
|
if (statusHandler) {
|
|
47
47
|
return statusHandler(error, event);
|
|
48
48
|
}
|
|
49
49
|
setResponseHeader(event, "Content-Type", "application/json");
|
|
50
50
|
const errorsData = resolveValidationErrorData(error, [
|
|
51
|
-
...event.context
|
|
51
|
+
...event.context.$precognition.errorParsers,
|
|
52
52
|
...options.errorParsers
|
|
53
53
|
]);
|
|
54
54
|
if (!errorsData) {
|
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import { defineNitroPlugin } from "#imports";
|
|
2
2
|
export default defineNitroPlugin((nitroApp) => {
|
|
3
|
-
const errorParsers = [];
|
|
4
|
-
const statusHandlers = {};
|
|
5
3
|
nitroApp.hooks.hook("request", (event) => {
|
|
6
|
-
event.context
|
|
7
|
-
errorParsers,
|
|
8
|
-
statusHandlers
|
|
4
|
+
event.context.$precognition = {
|
|
5
|
+
errorParsers: [],
|
|
6
|
+
statusHandlers: {}
|
|
9
7
|
};
|
|
10
8
|
event.context.precognitive = event.headers.get("Precognition") === "true";
|
|
11
9
|
});
|
|
@@ -3,7 +3,7 @@ import type { ErrorStatusCode } from './utils';
|
|
|
3
3
|
import type { ValidationErrorParser } from './core';
|
|
4
4
|
export type ServerStatusHandlers = Partial<Record<ErrorStatusCode, <TRequest extends EventHandlerRequest>(error: Error, event: H3Event<TRequest>) => void | Promise<void>>>;
|
|
5
5
|
export interface PrecognitionEventContext {
|
|
6
|
-
precognition: {
|
|
6
|
+
$precognition: {
|
|
7
7
|
errorParsers: ValidationErrorParser[];
|
|
8
8
|
statusHandlers: ServerStatusHandlers;
|
|
9
9
|
};
|
|
@@ -1,2 +1,5 @@
|
|
|
1
1
|
import type { Form, UseFormOptions } from './types/form';
|
|
2
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>;
|
|
3
|
+
export declare namespace useForm {
|
|
4
|
+
var create: <TData extends object, TResp>(_options?: UseFormOptions<TData> | undefined) => (init: TData | (() => TData), cb: (form: TData, precognitiveHeaders: Headers) => Promise<TResp>, options?: UseFormOptions<TData> | undefined) => TData & Form<TData, TResp>;
|
|
5
|
+
}
|
package/dist/runtime/useForm.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-precognition",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.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",
|