Skip to content

Response Classes

LightTs provides HttpResponse, DataResponse, and MessageResponse to standardize API success responses. Generated by lts add responses, these classes ensure clean, consistent output using native Node.js and Express, keeping your API lightweight.

The lts add responses command adds the following to src/core/responses/, using kebab-case for file names:

  • Directorysrc/
    • Directorycore/
      • Directoryresponses/
        • data.response.ts
        • message.response.ts
        • index.ts

These classes use camelCase for methods and variables, providing flexible response formatting.

src/core/responses/index.ts
import { Response } from 'express';
export class HttpResponse {
public readonly statusCode: number;
public readonly message: string | undefined;
public readonly data: any;
public readonly meta?: any;
constructor(
res: Response,
{
statusCode = 200,
message,
data = null,
meta
}: {
statusCode?: number;
message?: string;
data?: any;
meta?: any;
}
) {
this.statusCode = statusCode;
this.message = message;
this.data = data;
this.meta = meta;
let options = {};
options['statusCode'] = this.statusCode;
if (this.message) options['message'] = this.message;
if (this.data) options['data'] = this.data;
if (this.meta) options['meta'] = this.meta;
res.status(statusCode).json(options);
}
}

Use DataResponse for data-heavy responses and MessageResponse for simple success messages, paired with a simple controller (Express Router).

src/modules/user/user.service.ts
import { DataResponse } from '@/core/responses/data.response';
import { MessageResponse } from '@/core/responses/message.response';
import { Request, Response } from 'express';
export default {
getUsers: async (req: Request, res: Response) => {
const users = [{ id: 1, name: 'John Doe' }];
return new DataResponse(res, {
data: users,
message: 'Users fetched!',
statusCode: 200,
});
},
createUser: async (req: Request, res: Response) => {
return new MessageResponse(res, { message: 'User created!', statusCode: 201 });
},
};
  • Customization: Extend HttpResponse in src/core/responses/ for custom response types.
  • Naming Conventions: Files use kebab-case (e.g., data.response.ts), classes and methods use camelCase (e.g., DataResponse, getUsers).
  • Usage: Use DataResponse for endpoints with data, MessageResponse for simple confirmations.