@webexdx/koa-wrap
v1.5.1
Published
A wrapper package around koa framework
Readme
@webexdx/koa-wrap
A wrapper package around the Koa framework, providing a structured approach to building Koa servers with middleware, error handling, and routing utilities.
Features
- Typed Routing: Define routes and groups with TypeScript types.
- Middleware Support: Easily add global and route-specific middleware.
- JWT Authentication Middleware: Plug-and-play authentication using JSON Web Tokens.
- Centralized Error Handling: Standard error responses for API consumers.
- HTTP Status Codes: Enum for all standard HTTP status codes.
Installation
npm install @webexdx/koa-wrapUsage
1. Define Routes
import { HTTPMethod, RouteHandler, Router } from '@webexdx/koa-wrap';
const routes: Router = [
{
path: '/api',
children: [
{
path: '/hello',
method: HTTPMethod.GET,
handler: async (ctx) => {
ctx.body = { message: 'Hello, world!' };
},
},
],
},
];2. Create and Start the Server
import { Server } from '@webexdx/koa-wrap';
import { errorMiddleware } from '@webexdx/koa-wrap/middlewares';
const server = new Server({
port: 3000,
routes,
middlewares: [errorMiddleware],
onStartCb: () => {
console.log('Server started on port 3000');
},
});
server.start();3. JWT Authentication Middleware
import { authMiddleware } from '@webexdx/koa-wrap/middlewares';
const jwtMiddleware = authMiddleware({
secret: 'your_jwt_secret',
payloadTransform: payload => ({ id: payload.sub }),
});API
Server
See Server for constructor options.
Middleware
authMiddleware: JWT authentication.errorMiddleware: Error handling.
Errors
Custom error classes:
HTTP Status Codes
See HttpStatusCode for all available codes.
Development
- Build:
npm run build - Lint:
npm run lint - Format: Prettier and ESLint are enforced.
- Tests: (Add your tests in
test/and run with your preferred runner.)
License
ISC
© Sarin Alexander
