yupinator
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

Yupinator

Yupinator is a powerful and flexible utility for validating query parameters using Yup schemas. Designed for use in frameworks like Next.js, Express, and other Node.js environments, it ensures clean and reliable parameter validation with minimal effort.


Features

  • Schema-based Validation: Use Yup schemas to define validation rules.
  • Error Handling: Provides detailed error messages for invalid inputs.
  • Simple Integration: Works seamlessly with URLSearchParams from new URL(req.url).

Installation

Install Yupinator via NPM:

npm install yupinator


Usage

Validate Query Parameters from new URL(req.url)

The validateQueryParams function extracts query parameters from URLSearchParams and validates them against a Yup schema.

Example:

import { validateQueryParams } from 'yupinator';
import * as Yup from 'yup';

const validationSchema = Yup.object({
  first_name: Yup.string().required('First name is required'),
  age: Yup.number().positive('Age must be positive').required('Age is required'),
});

async function handleRequest(req: Request) {
  const { searchParams } = new URL(req.url);

  const { isValid, data, errors } = await validateQueryParams(searchParams, validationSchema);

  if (isValid) {
    console.log('Validated data:', data);
    return new Response('Validation passed!', { status: 200 });
  } else {
    console.error('Validation errors:', errors);
    return new Response(JSON.stringify({ errors }), { status: 400, headers: { 'Content-Type': 'application/json' } });
  }
}

Parameters

validateQueryParams(searchParams: URLSearchParams, schema: Yup.ObjectSchema)

  • Parameter: searchParams - Type: URLSearchParams - Description: Extracted from new URL(req.url).
  • Parameter: schema - Type: Yup.ObjectSchema - Description: A Yup schema to validate the inputs.

Returns:

  • isValid: boolean - Indicates if the validation passed (true) or failed (false).
  • data: Record<string, any> - Validated query parameters (only available if isValid is true).
  • errors: Record<string, string> - Object containing error messages for each invalid parameter (if invalid).

Examples

Basic Example

import { validateQueryParams } from 'yupinator';
import * as Yup from 'yup';

const schema = Yup.object({
  first_name: Yup.string().required('First name is required'),
  last_name: Yup.string().required('Last name is required'),
});

const { searchParams } = new URL('http://example.com?first_name=John&last_name=Doe');

validateQueryParams(searchParams, schema).then(({ isValid, data, errors }) => {
  if (isValid) {
    console.log('Validated data:', data);
  } else {
    console.error('Validation errors:', errors);
  }
});

Real-World Example (Next.js API Route)

import { NextRequest } from 'next/server';
import { validateQueryParams } from 'yupinator';
import * as Yup from 'yup';

export async function GET(req: NextRequest) {
  const schema = Yup.object({
    first_name: Yup.string().required('First name is required'),
    age: Yup.number().positive('Age must be positive').required('Age is required'),
  });

  const { searchParams } = new URL(req.url);

  const { isValid, data, errors } = await validateQueryParams(searchParams, schema);

  if (!isValid) {
    return new Response(JSON.stringify({ errors }), { status: 400, headers: { 'Content-Type': 'application/json' } });
  }

  return new Response(JSON.stringify({ message: 'Success', data }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  });
}

Error Handling Example

import { validateQueryParams } from 'yupinator';
import * as Yup from 'yup';

const schema = Yup.object({
  email: Yup.string().email('Invalid email address').required('Email is required'),
  age: Yup.number().min(18, 'You must be at least 18 years old').required('Age is required'),
});

const { searchParams } = new URL('http://example.com?email=invalid-email');

validateQueryParams(searchParams, schema).then(({ isValid, data, errors }) => {
  if (!isValid) {
    console.log('Errors:', errors);
  }
});

FAQ

Why Use URLSearchParams?

URLSearchParams is a native browser and Node.js API that makes parsing query strings clean and consistent. It integrates seamlessly with new URL(req.url) in server-side frameworks like Next.js, Express, and more.

What Happens When Validation Fails?

When validation fails:

  • The isValid field will be false.
  • The errors field will contain an object mapping invalid parameters to their respective error messages.

Can I Use This for Other Input Validation?

While Yupinator is optimized for query parameters (URLSearchParams), the core logic can be adapted for any input that maps to a Record<string, any>.


License

MIT License

Package Sidebar

Install

npm i yupinator

Weekly Downloads

2

Version

1.0.0

License

ISC

Unpacked Size

14.2 kB

Total Files

8

Last publish

Collaborators

  • gpamfilis