Router Utilities
When you develop custom APIs in router.[js|ts]
files, you might need to use some utilities to standardize your responses, handle errors, and manage pagination. The following utilities are available to help you with these tasks.
Reply
create(
status
,detail
):ResponseObject
Creates a response object with the given status and detail.
Example
import { reply } from '@modular-rest/server';
// inside the router
const response = reply.create("s", { message: "Hello, world!" });
ctx.body = response;
ctx.status = 200;
Parameters
Parameter | Type | Description |
---|---|---|
status | ResponseStatus | The status of the response. Can be "s" for success, "f" for fail, or "e" for error. |
detail | Record <string , any > | The detail of the response. Can contain any additional information about the response. |
Returns
The response object with the given status and detail.
Paginator Maker
create(
count
,perPage
,page
):PaginationResult
Creates a pagination object based on the given parameters.
Example
import { paginator } from '@modular-rest/server';
const pagination = paginator.create(100, 10, 1);
// json response will be like this
// {
// pages: 10,
// page: 1,
// from: 0,
// to: 10,
// }
Parameters
Parameter | Type | Description |
---|---|---|
count | number | The total number of items to paginate. |
perPage | number | The number of items to display per page. |
page | number | The current page number. |
Returns
An object containing pagination information.
Auth Middleware
auth(
ctx
,next
):Promise
<void
>
Authentication middleware that secures routes by validating user tokens and managing access control.
This middleware performs several key functions:
- Validates that the incoming request contains an authorization token in the header
- Verifies the token is valid by checking against the user management service
- Retrieves the associated user object if the token is valid
- Attaches the authenticated User object on ctx.state.user for use in subsequent middleware/routes
- Throws appropriate HTTP errors (401, 412) if authentication fails
The middleware integrates with the permission system to enable role-based access control. The attached user object provides methods like hasPermission() to check specific permissions.
Common usage patterns:
- Protecting sensitive API endpoints
- Implementing role-based access control
- Getting the current authenticated user
- Validating user permissions before allowing actions
Example
// Inside the router.ts file
import { auth } from '@modular-rest/server';
import { Router } from 'koa-router';
const name = 'flowers';
const flowerRouter = new Router();
flowerRouter.get('/list', auth, (ctx) => {
// Get the authenticated user
const user = ctx.state.user;
// Then you can check the user's role and permission
if(user.hasPermission('get_flower')) {
ctx.body = 'This is a list of flowers: Rose, Lily, Tulip';
} else {
ctx.status = 403;
ctx.body = 'You are not authorized to access this resource';
}
});
module.exports.name = name;
module.exports.main = flowerRouter;
Parameters
Parameter | Type | Description |
---|---|---|
ctx | Context | Koa Context object containing request/response data |
next | Next | Function to invoke next middleware |
Returns
Promise
<void
>
Throws
401 - If no authorization header is present
Throws
412 - If token validation fails