Files
MinglarBackendNestJS/src/modules/host/handlers/Host_Admin/onboarding/updateBankDetails.ts

78 lines
2.8 KiB
TypeScript
Raw Normal View History

2025-11-12 19:59:54 +05:30
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
import { safeHandler } from '../../../../../common/utils/handlers/safeHandler';
import { prismaClient } from '../../../../../common/database/prisma.lambda.service';
import { HostService } from '../../../services/host.service';
import ApiError from '../../../../../common/utils/helper/ApiError';
import { verifyHostToken } from '../../../../../common/middlewares/jwt/authForHost';
import { hostBankDetailsSchema } from '../../../../../common/utils/validation/host/addPaymentDetails.validation';
2025-11-12 19:59:54 +05:30
const hostService = new HostService(prismaClient);
2025-11-12 19:59:54 +05:30
export const handler = safeHandler(async (
event: APIGatewayProxyEvent,
context?: Context
): Promise<APIGatewayProxyResult> => {
// Extract token from headers
const token = event.headers['x-auth-token'] || event.headers['X-Auth-Token']
if (!token) {
throw new ApiError(400, 'This is a protected route. Please provide a valid token.');
}
// Authenticate user using the shared authForHost function
const userInfo = await verifyHostToken(token);
const hostId = userInfo.id;
if (Number.isNaN(hostId)) {
throw new ApiError(400, 'Host id must be a number');
}
2025-11-14 14:08:47 +05:30
const host = await hostService.getHostIdByUserXid(hostId);
if (!host) {
throw new ApiError(404, 'Host not found');
}
2025-11-12 19:59:54 +05:30
// Parse request body
let body: { bankXid?: number; bankBranchXid?: number; accountNumber?: string; confirmAccountNumber?: string; accountHolderName?: string; currencyXid?: number };
2025-11-12 19:59:54 +05:30
try {
body = event.body ? JSON.parse(event.body) : {};
} catch (error) {
throw new ApiError(400, 'Invalid JSON in request body');
}
// ✅ Validate payload using Zod
const validationResult = hostBankDetailsSchema.safeParse({
...(body as object),
hostXid: host.host.id, // inject hostId from token (not from user input)
2025-11-12 19:59:54 +05:30
});
if (!validationResult.success) {
const errorMessages = validationResult.error.issues.map(e => e.message).join(', ');
throw new ApiError(400, `Validation failed: ${errorMessages}`);
}
const validatedData = validationResult.data;
// Fetch IFSC code from bank branch
const bankBranch = await hostService.getBankBranchById(validatedData.bankBranchXid);
if (!bankBranch) {
throw new ApiError(404, 'Bank branch not found');
}
await hostService.addPaymentDetails({
...validatedData,
ifscCode: bankBranch.ifscCode,
});
2025-11-12 19:59:54 +05:30
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify({
success: true,
message: 'Payment details added successfully',
}),
};
});