UNPKG

validlyjs

Version:

A high-performance Laravel-inspired validation library for TypeScript/JavaScript

15 lines (14 loc) 2.35 kB
"use strict" var r=require("validlyjs"),e=require("fastify-plugin") class s{constructor(r={}){this.options={sources:["body","query","params"],errorStatus:422,errorFormat:"laravel",...r}}validate(e,s){const t={...this.options,...s} return async(s,a)=>{var o,i,u,d try{const n={};(null===(o=t.sources)||void 0===o?void 0:o.includes("body"))&&Object.assign(n,s.body),(null===(i=t.sources)||void 0===i?void 0:i.includes("query"))&&Object.assign(n,s.query),(null===(u=t.sources)||void 0===u?void 0:u.includes("params"))&&Object.assign(n,s.params),(null===(d=t.sources)||void 0===d?void 0:d.includes("headers"))&&Object.assign(n,s.headers) const c=new r.Validator(e,t),l=await c.validate(n) if(!l.isValid)return t.onError?void t.onError(l.errors,s,a):a.code(t.errorStatus||422).send({message:"Validation failed",errors:l.errors}) s.validatedData=l.data}catch(r){throw r}}}body(r,e){return this.validate(r,{...e,sources:["body"]})}query(r,e){return this.validate(r,{...e,sources:["query"]})}params(r,e){return this.validate(r,{...e,sources:["params"]})}}const t=e(async function(r,e){const t=new s(e) r.decorate("validate",t.validate.bind(t)),r.decorate("validateBody",t.body.bind(t)),r.decorate("validateQuery",t.query.bind(t)),r.decorate("validateParams",t.params.bind(t))},{fastify:"5.x",name:"validly-plugin"}) exports.ExpressValidator=class{constructor(r={}){this.options={sources:["body","query","params"],errorStatus:422,errorFormat:"laravel",...r}}validate(e,s){const t={...this.options,...s} return async(s,a,o)=>{var i,u,d,n try{const c={};(null===(i=t.sources)||void 0===i?void 0:i.includes("body"))&&Object.assign(c,s.body),(null===(u=t.sources)||void 0===u?void 0:u.includes("query"))&&Object.assign(c,s.query),(null===(d=t.sources)||void 0===d?void 0:d.includes("params"))&&Object.assign(c,s.params),(null===(n=t.sources)||void 0===n?void 0:n.includes("headers"))&&Object.assign(c,s.headers) const l=new r.Validator(e,t),v=await l.validate(c) v.isValid?(s.validatedData=v.data,o()):t.onError?t.onError(v.errors,s,a):a.status(t.errorStatus||422).json({message:"Validation failed",errors:v.errors})}catch(r){o(r)}}}body(r,e){return this.validate(r,{...e,sources:["body"]})}query(r,e){return this.validate(r,{...e,sources:["query"]})}params(r,e){return this.validate(r,{...e,sources:["params"]})}},exports.FastifyValidator=s,exports.validlyPlugin=t