lambda-precognition
v0.0.4
Published
Event handler implementing Laravel precognition protocol and perform backend validation.
Downloads
6
Maintainers
Readme
Serveless Precognition Validation
Light package for adding precognition validation. Inspired by Laravel Precognition, this package implements runtime validation. It works great with Nuxt-Precognition.
How use it
- Install it in your package.json:
npm install lambda-precognition
- Import the definePrecognitiveHandler from the package, and use it as main handler:
import { definePrecognitiveHandler } from 'lambda-precognition'
export const handler = definePrecognitiveHandler({
before: async (event) => {
// request body validation handler
},
main: async (event) => {
// main logic handler
},
after: async (event) => {
// after response handler
},
}, [/* ValidationParsers */])
Notice that there are three "lifecycle hooks".
before
: put here validation logic. It runs before the main handler. In case of precognitive request, it will be the only function to be triggered.main
: standard function where writing business logic.after
: in case you need to trigger some other behaviours, you can leverage this hook,, that runs as final handler.
What are validationParsers
ValidationParsers are simple functions that accept an Error as input parameter, and return ValidationErrorsData object (if any).
export type ValidationErrors = Record<string, string | string[]>
export interface ValidationErrorsData {
message: string
errors: ValidationErrors
}
export type ValidationErrorParser = (error: Error) => ValidationErrorsData | undefined | null
User can define any parser, based on the validation library used.
To simplify usage, ZodErrorParser
is already defined, and it can be used like that:
export const handler = definePrecognitiveHandler({
before: async (event) => {
body = JSON.parse(event.body!)
schema.parse(body)
},
main: async (event) => {
// main logic handler
}
}, ['ZOD_ERROR_PARSER'])
For more details please refer to (this repo)[https://github.com/sot1986/nuxt-precognition]