npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@wishdoor/server-utils

v1.3.0

Published

Server-side utility functions for API development including pagination and object utilities

Readme

@wishdoor/server-utils

Server-side utility functions for API development including pagination, validation, and object utilities.

Installation

npm install @wishdoor/server-utils

Pagination

generateWhereClause

Generates Prisma-compatible where, orderBy, and pagination parameters from query params.

import { generateWhereClause } from "@wishdoor/server-utils";

const { where, orderBy, skip, limit, page } = generateWhereClause({
	query: { page: 2, limit: 10, sortBy: "name", sortOrder: "asc" },
	defaultSort: { key: "createdAt", value: "desc" },
	defaultWhere: { status: "ACTIVE" },
});

const users = await prisma.user.findMany({ where, orderBy, skip, take: limit });

generatePagination

Generates pagination metadata for API responses.

import { generatePagination } from "@wishdoor/server-utils";

const pagination = generatePagination({ total: 150, page: 3, limit: 20 });
// { total, currentPage, pageSize, totalPages, hasNextPage, hasPreviousPage }

createPaginatedResponse

Combines data array with pagination metadata.

import { createPaginatedResponse } from "@wishdoor/server-utils";

const users = await prisma.user.findMany({ where, orderBy, skip, take: limit });
const total = await prisma.user.count({ where });

return createPaginatedResponse(users, total, page, limit);
// { data: [...], pagination: { total, currentPage, pageSize, totalPages, ... } }

Validation

validateMiddleware

Express middleware for validating request body, query, and params using Zod.

Schema structure:

{
  body?: ZodSchema,
  query?: ZodSchema,
  params?: ZodSchema
}
import { z } from "zod";
import { validateMiddleware } from "@wishdoor/server-utils";

const createUserSchema = z.object({
	body: z.object({
		name: z.string().min(2),
		email: z.string().email(),
	}),
	query: z.object({
		redirect: z.string().optional(),
	}),
	params: z.object({
		orgId: z.string(),
	}),
});

router.post(
	"/orgs/:orgId/users",
	validateMiddleware(createUserSchema),
	createUser
);

On validation error, throws ValidationError with statusCode: 400 and errors: [{ field, message }].

validate

Standalone validation function (not middleware).

import { z } from "zod";
import { validate } from "@wishdoor/server-utils";

const userSchema = z.object({
	name: z.string().min(2),
	email: z.string().email(),
});

const result = validate(userSchema, { name: "John", email: "invalid" });

if (result.success) {
	console.log(result.data);
} else {
	console.log(result.errors); // [{ field: 'email', message: 'Invalid email' }]
}

Utils

sanitizeObject

Removes unwanted values from an object (undefined, null, empty strings, etc).

import { sanitizeObject } from "@wishdoor/server-utils";

const obj = { a: 1, b: null, c: "", d: undefined, e: 0 };

sanitizeObject(obj);
// { a: 1, b: null, c: '', e: 0 } - removes undefined by default

sanitizeObject(obj, { removeNull: true, removeEmptyString: true });
// { a: 1, e: 0 }

sanitizeObject(obj, { removeNull: true, excludeKeys: ["b"] });
// { a: 1, b: null, c: '', e: 0 } - keeps excluded keys

Options:

  • removeUndefined - default: true
  • removeNull - default: false
  • removeEmptyString - default: false
  • removeZero - default: false
  • removeNaN - default: false
  • excludeKeys - keys to skip
  • includeKeys - only process these keys

buildQueryString

Builds a query string from key-value pairs.

import { buildQueryString } from "@wishdoor/server-utils";

buildQueryString({ page: 1, limit: 10 });
// "page=1&limit=10"

buildQueryString({ tags: ["a", "b"], active: true });
// "tags=a&tags=b&active=true"

buildQueryString({ page: 1, search: undefined });
// "page=1" - undefined/null values are skipped

generateUrl

Generates a complete API URL from base URL, path, and query params.

import { generateUrl } from "@wishdoor/server-utils";

// Uses process.env.API_URL as base
generateUrl("/users");
// "https://api.example.com/users"

generateUrl("/users", { page: 1, limit: 10 });
// "https://api.example.com/users?page=1&limit=10"

// With custom base URL
generateUrl("/users/123", undefined, "https://custom-api.com");
// "https://custom-api.com/users/123"

buildUrl

Builds a URL with path parameters replaced.

import { buildUrl } from "@wishdoor/server-utils";

buildUrl("/users/:id", { id: "123" });
// "https://api.example.com/users/123"

buildUrl(
	"/orgs/:orgId/users/:userId",
	{ orgId: "abc", userId: "123" },
	{ active: true }
);
// "https://api.example.com/orgs/abc/users/123?active=true"

Additional Functions

Pagination

| Function | Description | | ------------------------------------------- | ----------------------------------------- | | paginateArray(items, page, limit) | Paginate an in-memory array | | getDisplayRange(page, limit, total) | Get { from, to } for "Showing X-Y of Z" | | generatePageNumbers(current, total, max?) | Generate page numbers for UI |

Utils

| Function | Description | | ---------------------- | ---------------------------- | | removeUndefined(obj) | Remove only undefined values | | removeNullish(obj) | Remove null and undefined | | removeFalsy(obj) | Remove all falsy values | | pick(obj, keys) | Pick specific keys | | omit(obj, keys) | Omit specific keys | | isPlainObject(value) | Check if plain object | | deepClone(obj) | Deep clone via JSON | | isEmpty(obj) | Check if object has no keys |

Validation

| Function | Description | | ------------------------------- | ------------------------------------------ | | validateAsync(schema, data) | Async version of validate | | validateOrThrow(schema, data) | Validate and throw on error | | validateRequest | Alias for validateMiddleware | | ValidationError | Error class thrown by middleware | | parseZodError(error) | Convert ZodError to { field, message }[] |


Types

import type {
	// Pagination
	PaginationQuery, // { page?, limit?, search?, sortBy?, sortOrder? }
	PaginationMeta, // { total, currentPage, pageSize, totalPages, ... }
	PaginatedResponse, // { data: T[], pagination: PaginationMeta }
	DefaultSort, // { key: string, value: 'asc' | 'desc' }
	WhereClauseResult, // { where, orderBy, page, skip, limit }
	SortDirection, // 'asc' | 'desc'

	// Validation
	ValidationResult, // { success, data } | { success, errors }
	ValidationErrorItem, // { field, message }

	// Utils
	SanitizeObjectOptions,
	QueryParamsObject, // Record<string, string | number | boolean | ...>
} from "@wishdoor/server-utils";

Module Imports

import { generateWhereClause } from "@wishdoor/server-utils/pagination";
import { sanitizeObject } from "@wishdoor/server-utils/utils";
import { validateMiddleware } from "@wishdoor/server-utils/validation";

License

MIT