npm.io
1.0.0-rc.2 • Published 1 month ago

@coherent.js/api

Licence
MIT
Version
1.0.0-rc.2
Deps
0
Size
391 kB
Vulns
0
Weekly
0
Stars
2

@coherent.js/api

npm version license: MIT Node >= 20

API framework utilities for Coherent.js (routing, validation, serialization, security).

  • ESM-only, Node 20+
  • Build APIs with an object-first approach
  • Batteries-included: validation, error handling, auth helpers, and serialization

For a high-level overview and repository-wide instructions, see the root README: ../../README.md

Installation

pnpm add @coherent.js/api

Requirements:

  • Node.js >= 20
  • ESM module system

Quick start

JavaScript (ESM):

import { createRouter, withValidation, ApiError } from '@coherent.js/api';

const router = createRouter({
  'GET /health': () => ({ status: 'ok' }),
  'POST /echo': withValidation({ body: { message: 'string' } }, ({ body }) => ({ message: body.message }))
});

// router.handle(req) -> { statusCode, headers, body }

TypeScript:

import { createRouter, withValidation, ApiError } from '@coherent.js/api';

type EchoBody = { message: string };

const router = createRouter({
  'GET /health': () => ({ status: 'ok' }),
  'POST /echo': withValidation<{ body: EchoBody }>({ body: { message: 'string' } }, ({ body }) => ({ message: body.message }))
});

Exports overview (selected)

  • Routing
    • createRouter
  • Errors & handlers
    • ApiError, ValidationError, AuthenticationError, AuthorizationError, NotFoundError, ConflictError
    • withErrorHandling, createErrorHandler
  • Validation
    • validateAgainstSchema, validateField, withValidation, withQueryValidation, withParamsValidation
  • Serialization
    • serializeDate, deserializeDate, serializeMap, deserializeMap, serializeSet, deserializeSet, withSerialization, serializeForJSON
  • Security
    • withAuth, withRole, hashPassword, verifyPassword, generateToken, withInputValidation

Tip: Combine withValidation, withAuth, and withErrorHandling to build robust endpoints.

Development

Run tests for this package:

pnpm --filter @coherent.js/api run test

Watch mode:

pnpm --filter @coherent.js/api run test:watch

Type check:

pnpm --filter @coherent.js/api run typecheck

Build:

pnpm --filter @coherent.js/api run build

License

MIT Coherent.js Team