Skip to content

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

typescript
import { reply } from '@modular-rest/server';

// inside the router
const response = reply.create("s", { message: "Hello, world!" });
ctx.body = response;
ctx.status = 200;

Parameters

ParameterTypeDescription
statusResponseStatusThe status of the response. Can be "s" for success, "f" for fail, or "e" for error.
detailRecord<string, any>The detail of the response. Can contain any additional information about the response.

Returns

ResponseObject

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

typescript
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

ParameterTypeDescription
countnumberThe total number of items to paginate.
perPagenumberThe number of items to display per page.
pagenumberThe current page number.

Returns

PaginationResult

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:

  1. Validates that the incoming request contains an authorization token in the header
  2. Verifies the token is valid by checking against the user management service
  3. Retrieves the associated user object if the token is valid
  4. Attaches the authenticated User object on ctx.state.user for use in subsequent middleware/routes
  5. 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

typescript
// 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

ParameterTypeDescription
ctxContextKoa Context object containing request/response data
nextNextFunction to invoke next middleware

Returns

Promise<void>

Throws

401 - If no authorization header is present

Throws

412 - If token validation fails