93 lines
2.5 KiB
TypeScript
93 lines
2.5 KiB
TypeScript
import {
|
|
APIGatewayProxyEvent,
|
|
APIGatewayProxyResult,
|
|
Context,
|
|
} from 'aws-lambda';
|
|
import { prismaClient } from '../../../../common/database/prisma.lambda.service';
|
|
import { verifyUserToken } from '../../../../common/middlewares/jwt/authForUser';
|
|
import { safeHandler } from '../../../../common/utils/handlers/safeHandler';
|
|
import ApiError from '../../../../common/utils/helper/ApiError';
|
|
import { UserService } from '../../services/user.service';
|
|
|
|
const userService = new UserService(prismaClient);
|
|
|
|
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 verifyUserToken
|
|
const userInfo = await verifyUserToken(token);
|
|
const userId = userInfo.id;
|
|
|
|
if (Number.isNaN(userId)) {
|
|
throw new ApiError(400, 'User id must be a number');
|
|
}
|
|
|
|
const user = await userService.getUserById(userId);
|
|
if (!user) {
|
|
throw new ApiError(404, 'User not found');
|
|
}
|
|
|
|
// Parse request body
|
|
let body: {
|
|
countryName?: string;
|
|
stateName?: string;
|
|
cityName?: string;
|
|
pinCode?: string;
|
|
latitude?: number;
|
|
longitude?: number;
|
|
locationName?: string;
|
|
locationAddress?: string;
|
|
};
|
|
|
|
try {
|
|
body = event.body ? JSON.parse(event.body) : {};
|
|
} catch (error) {
|
|
throw new ApiError(400, 'Invalid JSON in request body');
|
|
}
|
|
|
|
const { countryName, stateName, cityName, pinCode, latitude, longitude, locationName, locationAddress } = body;
|
|
|
|
// Validate required fields
|
|
if (!countryName || !stateName || !cityName) {
|
|
throw new ApiError(400, 'Country name, state name, and city name are required');
|
|
}
|
|
|
|
// Set the location details
|
|
await userService.setUserLocationDetails(
|
|
userId,
|
|
countryName,
|
|
stateName,
|
|
cityName,
|
|
pinCode,
|
|
latitude,
|
|
longitude,
|
|
locationName,
|
|
locationAddress,
|
|
);
|
|
|
|
return {
|
|
statusCode: 200,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Access-Control-Allow-Origin': '*',
|
|
},
|
|
body: JSON.stringify({
|
|
success: true,
|
|
message: 'Location details set successfully',
|
|
}),
|
|
};
|
|
},
|
|
);
|