diff --git a/packages/validations/src/validations/openAIRoutesValidator.ts b/packages/validations/src/validations/openAIRoutesValidator.ts index d19daa4fb..a703930fd 100644 --- a/packages/validations/src/validations/openAIRoutesValidator.ts +++ b/packages/validations/src/validations/openAIRoutesValidator.ts @@ -10,3 +10,10 @@ export const getUserChats = z.object({ userId: z.string(), itemTypeId: z.string(), }); + + +export const getAISuggestions = z.object({ + userId: z.string(), + itemTypeId: z.string(), + type: z.string(), +}); diff --git a/server/src/controllers/auth/checkCode.ts b/server/src/controllers/auth/checkCode.ts index 529926121..70f8a32a9 100644 --- a/server/src/controllers/auth/checkCode.ts +++ b/server/src/controllers/auth/checkCode.ts @@ -1,22 +1,16 @@ import { publicProcedure } from '../../trpc'; -import { InvalidCodeError } from '../../helpers/errors'; -import { responseHandler } from '../../helpers/responseHandler'; import * as validator from '@packrat/validations'; import { checkCodeService } from '../../services/user/checkCodeService'; -// /** -// * Checks the provided code against the user's email in the database. -// * @param {Object} req - the request object -// * @param {Object} res - the response object -// * @return {Promise} - a promise that resolves to void -// */ -// export const checkCode = async (req: any, res: any, next) => { -// const user: any = await checkCodeService(req.body); -// if (user.length) { -// responseHandler(res); -// } else { -// next(InvalidCodeError); -// } -// }; + +export const checkCode = async (c) => { + const { email, code } = await c.req.parseBody(); + try { + const response = await checkCodeService(email, code); + return c.json({ response }, 200); + } catch (error) { + return c.json({ error: error.message }, 500); + } +}; export function checkCodeRoute() { return publicProcedure.input(validator.checkCode).mutation(async (opts) => { diff --git a/server/src/controllers/auth/emailExists.ts b/server/src/controllers/auth/emailExists.ts index dc1912132..5c9ff56a4 100644 --- a/server/src/controllers/auth/emailExists.ts +++ b/server/src/controllers/auth/emailExists.ts @@ -1,12 +1,22 @@ import { publicProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; import { emailExistsService } from '../../services/user/emailExistsService'; -/** - * Check if the provided email exists in the database. - * @param {object} req - The request object. - * @param {object} res - The response object. - * @return {Promise} - A promise that resolves to nothing. - */ + +export const emailExists = async (c) => { + try { + const { email } = await c.req.json(); + + const emailExists = await emailExistsService({ + sendGridApiKey: c.env.SEND_GRID_API_KEY, + smtpEmail: c.env.STMP_EMAIL, + email, + }); + console.log('emailExists', emailExists) + return c.json({ emailExists }, 200); + } catch (error) { + return c.json({ error: `Failed to delete user: ${error.message}` }, 404); + } +}; export function emailExistsRoute() { return publicProcedure.input(validator.emailExists).mutation(async (opts) => { diff --git a/server/src/controllers/auth/updatePassword.ts b/server/src/controllers/auth/updatePassword.ts index 4ede1d868..86649f37f 100644 --- a/server/src/controllers/auth/updatePassword.ts +++ b/server/src/controllers/auth/updatePassword.ts @@ -1,46 +1,20 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { findUserAndUpdate } from '../../services/user/user.service'; import * as validator from '@packrat/validations'; import { hashPassword } from '../../utils/user'; -// import { prisma } from '../../prisma'; - -/** - * Updates the password for a user. - * @param {object} req - The request object. - * @param {object} res - The response object. - * @return {Promise} - A promise that resolves to nothing. - */ -// export const updatePassword = async (req, res, next) => { -// try { -// let { email, oldPassword, newPassword } = req.body; - -// const user = await prisma.user.findFirst({ -// where: { -// email, -// }, -// }); - -// if (!user) throw new Error('Unable to verify'); - -// const isMatch = await bcrypt.compare(oldPassword, user.password); - -// if (!isMatch) throw new Error('Incorrect password'); - -// const salt = await bcrypt.genSalt(parseInt(JWT_SECRET)); - -// newPassword = await bcrypt.hash(newPassword, salt); - -// const val = await findUserAndUpdate(email, newPassword, 'password'); - -// if (val) { -// responseHandler(res); -// } else { -// next(UnableTouUpdatePasswordError); -// } -// } catch (error) { -// next(UnableTouUpdatePasswordError); -// } -// }; +import { type Context } from 'hono'; + +export const updatePassword = async (c: Context) => { + try { + const { email, password } = await c.req.json(); + const JWT_SECRET = c.env.JWT_SECRET; + const hashedPassword = await hashPassword(JWT_SECRET, password); + const user = await findUserAndUpdate(email, hashedPassword, 'password'); + return c.json({ user }, 200); + } catch (error) { + return c.json({ error: `Email Doesnt Exist: ${error.message}` }, 404); + } +}; export function updatePasswordRoute() { return protectedProcedure diff --git a/server/src/controllers/favorite/addToFavorite.ts b/server/src/controllers/favorite/addToFavorite.ts index 6bada1314..a4ec98102 100644 --- a/server/src/controllers/favorite/addToFavorite.ts +++ b/server/src/controllers/favorite/addToFavorite.ts @@ -1,32 +1,17 @@ +import { type Context } from 'hono'; import { addToFavoriteService } from '../../services/favorite/favorite.service'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; -// import { prisma } from '../../prisma'; -/** - * Adds or removes a pack from a user's favorites list and updates the corresponding pack's favorited_by array. - * @param {Object} req - The request object containing the packId and userId properties in the body. - * @param {Object} res - The response object used to send the HTTP response. - * @return {Object} The updated user object in the response body. - */ -// export const addToFavorite = async (req, res, next) => { -// const { packId, userId } = req.body; -// await addToFavoriteService(packId, userId); -// const user = await prisma.user.findUnique({ -// where: { -// id: userId, // Assuming userId is the user's ID -// }, -// select: { -// // Exclude the 'password' field -// id: true, -// email: true, -// name: true, // Include other fields you want -// }, -// }); -// if (!user) next(UserNotFoundError); -// res.locals.data = user; -// responseHandler(res); -// }; +export const addToFavorite = async (c: Context) => { + try { + const { packId, userId } = await c.req.json(); + const response = await addToFavoriteService(packId, userId); + return c.json({ response }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function addToFavoriteRoute() { return protectedProcedure diff --git a/server/src/controllers/favorite/getFavoritePacksByUser.ts b/server/src/controllers/favorite/getFavoritePacksByUser.ts index d35b53ec8..18a8e7a01 100644 --- a/server/src/controllers/favorite/getFavoritePacksByUser.ts +++ b/server/src/controllers/favorite/getFavoritePacksByUser.ts @@ -1,20 +1,17 @@ import { z } from 'zod'; import { getFavoritePacksByUserService } from '../../services/favorite/favorite.service'; import { publicProcedure, protectedProcedure } from '../../trpc'; +import { type Context } from 'hono'; -// /** -// * Retrieves favorite packs for a user. -// * @param {Object} req - The request object. -// * @param {Object} res - The response object. -// * @return {Promise} - The favorite packs of the user. -// */ -// export const getFavoritePacksByUser = async (req, res, next) => { -// const { userId } = req.body; -// const packs = await getFavoritePacksByUserService(userId); -// if (!packs) next(PackNotFoundError); -// res.locals.data = packs; -// responseHandler(res); -// }; +export const getFavoritePacksByUser = async (c: Context) => { + try { + const { userId } = await c.req.json(); + const packs = await getFavoritePacksByUserService(userId); + return c.json({ packs }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getFavoritePacksByUserRoute() { return protectedProcedure diff --git a/server/src/controllers/favorite/getUserFavorites.ts b/server/src/controllers/favorite/getUserFavorites.ts index b5addfc5e..84346df30 100644 --- a/server/src/controllers/favorite/getUserFavorites.ts +++ b/server/src/controllers/favorite/getUserFavorites.ts @@ -1,21 +1,17 @@ import { z } from 'zod'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { getUserFavoritesService } from '../../services/favorite/favorite.service'; +import { type Context } from 'hono'; -// import { prisma } from '../../prisma'; -/** - * Retrieves the favorite items of a user. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @returns {Array} An array of favorite items belonging to the user. - */ -// export const getUserFavorites = async (req, res, next) => { -// const { userId } = req.params; -// const favorites = await getUserFavoritesService(userId, next); -// if (!favorites) next(UserFavoritesNotFoundError); -// res.locals.data = favorites; -// responseHandler(res); -// }; +export const getUserFavorites = async (c: Context) => { + try { + const { userId } = await c.req.json(); + const favorites = await getUserFavoritesService(userId); + return c.json({ favorites }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getUserFavoritesRoute() { return protectedProcedure diff --git a/server/src/controllers/geoCode/getGeoCode.ts b/server/src/controllers/geoCode/getGeoCode.ts index 896fbe67a..ca51c232b 100644 --- a/server/src/controllers/geoCode/getGeoCode.ts +++ b/server/src/controllers/geoCode/getGeoCode.ts @@ -1,27 +1,23 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { ErrorFetchingGeoCodeError } from '../../helpers/errors'; -import { responseHandler } from '../../helpers/responseHandler'; -import { oneEntity } from '../../utils/oneEntity'; -// import * as validators from '@packrat/validations'; import { geoCodeService } from '../../services/geocode/geoCodeService'; -// /** -// * Retrieves the geocode for a given address array. -// * @param {Object} req - The request object. -// * @param {Object} req.query - The query parameters. -// * @param {string} req.query.addressArray - The address array to retrieve the geocode for. -// * @param {Object} res - The response object. -// * @return {Promise} - A promise that resolves when the geocode is retrieved and the response is sent. -// */ -// export const getGeoCode = async (req, res, next) => { -// const result: any = await geoCodeService(req.query); -// if (result.message === 'ok') { -// res.locals.data = result.result; -// responseHandler(res); -// } else { -// next(ErrorFetchingGeoCodeError); -// } -// }; +export const getGeoCode = async (c) => { + try { + const { addressArray } = await c.req.json(); + const result: any = await geoCodeService({ + addressArray, + geoCodeUri: c.env.GEO_CODE_URL, + geoapifyKey: c.env.GEOAPIFY_KEY, + }); + if (result.message === 'ok') { + return c.json({ result: result.result }, 200); + } + return c.json({ error: ErrorFetchingGeoCodeError.message }, 500); + } catch (error) { + return c.json({ error: `Failed to get GeoCode: ${error.message}` }, 500); + } +}; export function getGeoCodeRoute() { return protectedProcedure.query(async (opts) => { diff --git a/server/src/controllers/getOsm/getDestination.ts b/server/src/controllers/getOsm/getDestination.ts index 5b7e744b0..7e92943dc 100644 --- a/server/src/controllers/getOsm/getDestination.ts +++ b/server/src/controllers/getOsm/getDestination.ts @@ -1,27 +1,17 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; -import { NoDestinationFoundWithThatIDError } from '../../helpers/errors'; -import { responseHandler } from '../../helpers/responseHandler'; +import { protectedProcedure } from '../../trpc'; import { getDestinationService } from '../../services/osm/osm.service'; import { z } from 'zod'; +import { type Context } from 'hono'; -// /** -// * Retrieves the destination based on the given ID. -// * @param {object} req - The request object. -// * @param {object} res - The response object. -// * @return {object} The retrieved destination. -// */ -// export const getDestination = async (req, res, next) => { -// const id = req.params.id; - -// const destination = await getDestinationService(id); - -// if (!destination) { -// next(NoDestinationFoundWithThatIDError); -// } - -// res.locals.data = destination; -// responseHandler(res); -// }; +export const getDestination = async (c: Context) => { + try { + const { id } = await c.req.json(); + const destination = await getDestinationService(id); + return c.json({ destination }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getDestinationRoute() { return protectedProcedure diff --git a/server/src/controllers/getOsm/getNominatimDetails.ts b/server/src/controllers/getOsm/getNominatimDetails.ts index e6f8212f2..0868aeb99 100644 --- a/server/src/controllers/getOsm/getNominatimDetails.ts +++ b/server/src/controllers/getOsm/getNominatimDetails.ts @@ -3,16 +3,9 @@ import { ErrorRetrievingNominatimError, InvalidRequestParamsError, } from '../../helpers/errors'; -import { responseHandler } from '../../helpers/responseHandler'; -/** - * Retrieves Nominatim details based on the provided latitude, longitude, or place ID. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @returns {Promise} - Returns nothing. - */ -export const getNominatimDetails = async (req, res, next) => { - const { lat, lon, place_id } = req.query; +export const getNominatimDetails = async (c) => { + const { lat, lon, place_id } = c.req.query(); let nominatimUrl = ''; @@ -21,19 +14,17 @@ export const getNominatimDetails = async (req, res, next) => { } else if (lat && lon) { nominatimUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lon}&zoom=18&addressdetails=1`; } else { - next(InvalidRequestParamsError); + c.next(InvalidRequestParamsError); } try { const response = await fetch(nominatimUrl); if (response.ok) { - res.locals.data = await response.json(); - responseHandler(res); + c.json({ response }, 200); } else { - console.log(response.status, response.statusText); - next(ErrorProcessingNominatimError); + c.next(ErrorProcessingNominatimError); } } catch (error) { - next(ErrorRetrievingNominatimError); + c.next(ErrorRetrievingNominatimError); } }; diff --git a/server/src/controllers/getOsm/getOsm.ts b/server/src/controllers/getOsm/getOsm.ts index 9c3f2252d..0809b4f8c 100644 --- a/server/src/controllers/getOsm/getOsm.ts +++ b/server/src/controllers/getOsm/getOsm.ts @@ -1,32 +1,22 @@ -import osmtogeojson from 'osmtogeojson'; -import { - ErrorProcessingOverpassError, - ErrorRetrievingOverpassError, - InvalidRequestParamsError, -} from '../../helpers/errors'; -import { responseHandler } from '../../helpers/responseHandler'; -import { publicProcedure, protectedProcedure } from '../../trpc'; -import * as validators from '@packrat/validations'; +import { ErrorRetrievingOverpassError } from '../../helpers/errors'; +import { protectedProcedure } from '../../trpc'; import { getOsmService } from '../../services/osm/getOsmService'; import { z } from 'zod'; -/** - * Retrieves OpenStreetMap data based on the provided activity type, start point, and end point. - * @param {Object} req - The request object containing the activity type, start point, and end point. - * @param {Object} res - The response object used to send the retrieved OpenStreetMap data. - * @return {Promise} - A promise that resolves when the OpenStreetMap data is successfully retrieved and sent. - */ -// export const getOsm = async (req, res, next) => { -// console.log('req', req); // log the request body to see what it looks like -// try { -// const { activityType, startPoint, endPoint } = req.body; -// const result = await getOsmService({ activityType, startPoint, endPoint }); -// res.locals.data = result; -// responseHandler(res); -// } catch (error) { -// next(ErrorRetrievingOverpassError); -// } -// }; +export const getOsm = async (c) => { + try { + const { activityType, startPoint, endPoint } = await c.req.json(); + const route = await getOsmService({ + activityType, + startPoint, + endPoint, + osmURI: c.env.OSM_URI, + }); + return c.json({ route }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getOsmRoute() { return protectedProcedure @@ -48,7 +38,6 @@ export function getOsmRoute() { osmURI: env.OSM_URI, }); } catch (error) { - // throw ErrorRetrievingOverpassError; return ErrorRetrievingOverpassError; } }); diff --git a/server/src/controllers/getOsm/getParksOSM.ts b/server/src/controllers/getOsm/getParksOSM.ts index f5f692913..aab9efadc 100644 --- a/server/src/controllers/getOsm/getParksOSM.ts +++ b/server/src/controllers/getOsm/getParksOSM.ts @@ -1,35 +1,17 @@ +import { type Context } from 'hono'; import { getParksOSMService } from '../../services/osm/getParksOSMService'; -import { - ErrorRetrievingParksOSMError, - InvalidRequestParamsError, -} from '../../helpers/errors'; -import { responseHandler } from '../../helpers/responseHandler'; -import { publicProcedure, protectedProcedure } from '../../trpc'; -import { z } from 'zod'; -// import * as validators from '@packrat/validations'; +import { protectedProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; -/** - * Retrieves parks data from OpenStreetMap based on the provided latitude, longitude, and radius. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} The response object containing the parks data. - */ -// export const getParksOSM = async (req, res, next) => { -// try { -// const { lat = 45.5231, lon = -122.6765, radius = 50000 } = req.query; - -// if (!lat || !lon || !radius) { -// next(InvalidRequestParamsError); -// } -// const result = await getParksOSMService(lat, lon, radius); -// res.locals.data = result; -// responseHandler(res); -// } catch (error) { -// console.error(error); -// next(ErrorRetrievingParksOSMError); -// } -// }; +export const getParksOSM = async (c: Context) => { + try { + const { lat, lon, radius } = await c.req.json(); + const parks = await getParksOSMService(lat, lon, radius, c.env.OSM_URI); + return c.json({ parks }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getParksOSMRoute() { return protectedProcedure.input(validator.getParksOSM).query(async (opts) => { diff --git a/server/src/controllers/getOsm/getPhotonDetails.ts b/server/src/controllers/getOsm/getPhotonDetails.ts index 409cb5d44..c54e1e25a 100644 --- a/server/src/controllers/getOsm/getPhotonDetails.ts +++ b/server/src/controllers/getOsm/getPhotonDetails.ts @@ -1,31 +1,19 @@ -import { - InvalidRequestParamsError, - RetrievingPhotonDetailsError, -} from '../../helpers/errors'; import { responseHandler } from '../../helpers/responseHandler'; import { z } from 'zod'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { getPhotonDetailsService } from '../../services/osm/getPhotonDetailsService'; +import type { Context } from 'hono'; -/** - * Retrieves Photon details based on the provided ID and type. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} The function does not return anything. - */ -// export const getPhotonDetails = async (req, res, next) => { -// const { id, type } = req.params; -// if (!id || !type) { -// next(InvalidRequestParamsError); -// } -// try { -// const result = await getPhotonDetailsService(id, type); -// res.locals.data = result; -// responseHandler(res); -// } catch (error) { -// next(RetrievingPhotonDetailsError); -// } -// }; +export async function getPhotonDetails(ctx: Context) { + try { + const { id, type } = await ctx.req.param(); + const { env }: any = ctx; + const response = await getPhotonDetailsService(id, type, env.OSM_URI); + return ctx.json({ response }, 200); + } catch (error) { + return ctx.json({ error: error.message }, 500); + } +} export function getPhotonDetailsRoute() { return protectedProcedure diff --git a/server/src/controllers/getOsm/getPhotonResults.ts b/server/src/controllers/getOsm/getPhotonResults.ts index a4baece7b..7fb287954 100644 --- a/server/src/controllers/getOsm/getPhotonResults.ts +++ b/server/src/controllers/getOsm/getPhotonResults.ts @@ -1,33 +1,18 @@ import { getPhotonResultsService } from '../../services/osm/getPhotonResultsService'; -import { - InvalidRequestParamsError, - RetrievingPhotonDetailsError, -} from '../../helpers/errors'; import { responseHandler } from '../../helpers/responseHandler'; -import { publicProcedure, protectedProcedure } from '../../trpc'; -import { z } from 'zod'; -// import * as validators from '@packrat/validations'; +import { protectedProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; +import { type Context } from 'hono'; -/** - * Retrieves Photon results based on a search string. - * @param {object} req - The request object. - * @param {object} res - The response object. - * @return {undefined} There is no explicit return value. - */ -// export const getPhotonResults = async (req, res, next) => { -// const { searchString } = req.query; -// if (!searchString) { -// next(InvalidRequestParamsError); -// } -// try { -// const resultsArray = await getPhotonResultsService(searchString); -// res.locals.data = resultsArray.data.features; -// responseHandler(res); -// } catch (error) { -// next(RetrievingPhotonDetailsError); -// } -// }; +export async function getPhotonResults(ctx: Context) { + try { + const { searchString } = await ctx.req.query(); + const response = await getPhotonResultsService(searchString); + return ctx.json(response.features, 200) + } catch (error) { + return ctx.json({error: error.message}, 500) + } +} export function getPhotonResultsRoute() { return protectedProcedure diff --git a/server/src/controllers/getOsm/getTrailsOSM.ts b/server/src/controllers/getOsm/getTrailsOSM.ts index df4f1ec0a..75fab4de7 100644 --- a/server/src/controllers/getOsm/getTrailsOSM.ts +++ b/server/src/controllers/getOsm/getTrailsOSM.ts @@ -1,34 +1,23 @@ import { getTrailsOsmService } from '../../services/osm/getTrailsOSMService'; -import { - InvalidRequestParamsError, - RetrievingTrailsOSMError, -} from '../../helpers/errors'; import { responseHandler } from '../../helpers/responseHandler'; -import { publicProcedure, protectedProcedure } from '../../trpc'; -import * as z from 'zod'; -// import * as validators from '@packrat/validations'; +import { protectedProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; +import { type Context } from 'hono'; -/** - * Retrieves trails data from OpenStreetMap (OSM) based on the provided latitude, longitude, and radius. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} - Resolves with the geojsonData of trails retrieved from OSM. - */ -// export const getTrailsOSM = async (req, res, next) => { -// try { -// const { lat = 45.5231, lon = -122.6765, radius = 50000 } = req.query; - -// if (!lat || !lon || !radius) { -// next(InvalidRequestParamsError); -// } -// const geojsonData = await getTrailsOsmService(lat, lon, radius); -// res.locals.data = geojsonData; -// responseHandler(res); -// } catch (error) { -// next(RetrievingTrailsOSMError); -// } -// }; +export async function getTrailsOSM(ctx: Context) { + try { + const { + lat = 45.5231, + lon = -122.6765, + radius = 50000, + } = await ctx.req.json(); + const { env }: any = ctx; + const response = await getTrailsOsmService(env.OSM_URI, lat, lon, radius); + return ctx.json(response, 200); + } catch (error) { + return ctx.json({ error: error.message }, 500); + } +} export function getTrailsOSMRoute() { return protectedProcedure diff --git a/server/src/controllers/getOsm/postSingleGeoJSON.ts b/server/src/controllers/getOsm/postSingleGeoJSON.ts index 0104bbe77..9446971bc 100644 --- a/server/src/controllers/getOsm/postSingleGeoJSON.ts +++ b/server/src/controllers/getOsm/postSingleGeoJSON.ts @@ -1,22 +1,18 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { responseHandler } from '../../helpers/responseHandler'; import { postSingleGeoJSONService } from '../../services/osm/osm.service'; import { z } from 'zod'; +import { type Context } from 'hono'; -/** - * Handles the POST request for a single GeoJSON. - * @param {Object} req - the request object - * @param {Object} res - the response object - * @return {void} - does not return a value - */ -// export const postSingleGeoJSON = async (req, res) => { -// console.log('in postSingleGeoJSON'); -// const geojson = req.body; - -// const result = await postSingleGeoJSONService(geojson); -// res.locals.data = result; -// responseHandler(res); -// }; +export async function postSingleGeoJSON(ctx: Context) { + try { + const { geojson } = await ctx.req.json(); + const response = await postSingleGeoJSONService(geojson); + return ctx.json({ response }, 200); + } catch (error) { + return ctx.json({ error: error.message }, 500); + } +} export function postSingleGeoJSONRoute() { return protectedProcedure diff --git a/server/src/controllers/getParks/getParks.ts b/server/src/controllers/getParks/getParks.ts index f71ca7258..38b730e3e 100644 --- a/server/src/controllers/getParks/getParks.ts +++ b/server/src/controllers/getParks/getParks.ts @@ -2,6 +2,7 @@ import { publicProcedure, protectedProcedure } from '../../trpc'; import { responseHandler } from '../../helpers/responseHandler'; import * as validators from '@packrat/validations'; import { getParksService } from '../../services/parks/getParksService'; +import { type Context } from 'hono'; /** * Retrieves a list of parks based on the specified state code. @@ -15,6 +16,22 @@ import { getParksService } from '../../services/parks/getParksService'; // responseHandler(res); // }; +export async function getParks(ctx: Context) { + try { + const { abbrState } = await ctx.req.json(); + const { env }: any = ctx; + const response = await getParksService({ + abbrStates: abbrState, + rapidApiKey: env.X_RAPIDAPI_KEY, + npsApi: env.NPS_API, + parksHost: env.PARKS_HOST, + }); + return ctx.json(response, 200); + } catch (error) { + return ctx.json({ error: error.message }, 400); + } +} + export function getParksRoute() { return protectedProcedure.input(validators.getParks).query(async (opts) => { const { abbrState } = opts.input; diff --git a/server/src/controllers/getTrail/getTrails.ts b/server/src/controllers/getTrail/getTrails.ts index c1a68da61..4e3e009eb 100644 --- a/server/src/controllers/getTrail/getTrails.ts +++ b/server/src/controllers/getTrail/getTrails.ts @@ -1,37 +1,37 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { responseHandler } from '../../helpers/responseHandler'; -import * as validators from '@packrat/validations'; import { getTrailsService } from '../../services/trails/getTrailsService'; import { z } from 'zod'; +import type { Context } from 'hono'; -/** - * Retrieves trails based on the provided parameters. - * @param {Object} req - The request object containing the parameters. - * @param {Object} res - The response object. - * @return {Promise} A promise that resolves with the retrieved trail data or an error message. - */ -// export const getTrails = async (req, res, next) => { -// const radiusParams = 25; -// const activityParams = true; -// const { -// administrative_area_level_1, -// country, -// locality, -// latitude, -// longitude, -// } = req.body; -// const response = await getTrailsService( -// administrative_area_level_1, -// country, -// locality, -// latitude, -// longitude, -// radiusParams, -// activityParams, -// ); -// res.locals.data = response; -// responseHandler(res); -// }; +export async function getTrails(ctx: Context) { + try { + const radiusParams = 25; + const activityParams = true; + const { + administrative_area_level_1, + country, + locality, + latitude, + longitude, + } = await ctx.req.json(); + const { env }: any = ctx; + const response = await getTrailsService({ + trailRootUrl: env.GET_TRAIL_ROOT_URL, + xRapidapiKey: env.X_RAPIDAPI_KEY, + administrative_area_level_1, + country, + locality, + latitude, + longitude, + radiusParams, + activityParams, + }); + return ctx.json(response, 200); + } catch (error) { + return ctx.json({ error: error.message }, 400); + } +} export function getTrailsRoute() { return protectedProcedure diff --git a/server/src/controllers/item/addGlobalItemToPack.ts b/server/src/controllers/item/addGlobalItemToPack.ts index dc338a764..989210782 100644 --- a/server/src/controllers/item/addGlobalItemToPack.ts +++ b/server/src/controllers/item/addGlobalItemToPack.ts @@ -1,26 +1,20 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { addGlobalItemToPackService } from '../../services/item/item.service'; import { z } from 'zod'; +import { type Context } from 'hono'; -/** - * Adds a global item to a pack. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} The updated item. - */ -// export const addGlobalItemToPack = async (req, res, next) => { -// try { -// const { packId } = req.params; -// const { itemId, ownerId } = req.body; - -// const result = await addGlobalItemToPackService(packId, itemId, ownerId); - -// res.locals.data = result; -// responseHandler(res); -// } catch (error) { -// next(ItemNotFoundError); -// } -// }; +export const addGlobalItemToPack = async (c: Context) => { + try { + const { packId, itemId, ownerId } = await c.req.json(); + const item = await addGlobalItemToPackService(packId, itemId, ownerId); + return c.json({ item }, 200); + } catch (error) { + return c.json( + { error: `${error.message}` }, + 500, + ); + } +}; export function addGlobalItemToPackRoute() { return protectedProcedure diff --git a/server/src/controllers/item/addItem.ts b/server/src/controllers/item/addItem.ts index 966c114b3..23d07a72c 100644 --- a/server/src/controllers/item/addItem.ts +++ b/server/src/controllers/item/addItem.ts @@ -1,33 +1,26 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { addItemService } from '../../services/item/item.service'; import * as validator from '@packrat/validations'; -/** - * Adds an item to the database based on the provided request body. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} The updated item and pack ID. - */ -// export const addItem = async (req, res, next) => { -// try { -// const { name, weight, quantity, unit, packId, type, ownerId } = req.body; +export const addItem = async (c) => { + try { + const { name, weight, quantity, unit, packId, type, ownerId } = + await c.req.json(); -// const result = await addItemService( -// name, -// weight, -// quantity, -// unit, -// packId, -// type, -// ownerId, -// ); - -// res.locals.data = { newItem: result.newItem, packId: result.packId }; -// responseHandler(res); -// } catch (error) { -// next(UnableToAddItemError); -// } -// }; + const result = await addItemService( + name, + weight, + quantity, + unit, + packId, + type, + ownerId, + ); + return c.json({ result }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function addItemRoute() { return protectedProcedure.input(validator.addItem).mutation(async (opts) => { diff --git a/server/src/controllers/item/addItemGlobal.ts b/server/src/controllers/item/addItemGlobal.ts index 04ebbb569..4fbe4d594 100644 --- a/server/src/controllers/item/addItemGlobal.ts +++ b/server/src/controllers/item/addItemGlobal.ts @@ -1,32 +1,26 @@ +import { type Context } from 'hono'; import { addItemGlobalService } from '../../services/item/item.service'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; -/** - * Adds an item globally. - * @param {object} req - The request object. - * @param {object} res - The response object. - * @return {object} The added item. - */ +export const addItemGlobal = async (c: Context) => { + try { + const { name, weight, quantity, unit, type, ownerId } = + await c.req.json(); -// export const addItemGlobal = async (req, res, next) => { -// try { -// const { name, weight, quantity, unit, type } = req.body; - -// const newItem = await addItemGlobalService( -// name, -// weight, -// quantity, -// unit, -// type, -// ); - -// res.locals.data = newItem; -// responseHandler(res); -// } catch (error) { -// next(UnableToAddItemError); -// } -// }; + const item = await addItemGlobalService( + name, + weight, + quantity, + unit, + type, + ownerId, + ); + return c.json({ item }, 200); + } catch (error) { + return c.json({ error: `Failed to add item: ${error.message}` }, 500); + } +}; export function addItemGlobalRoute() { return protectedProcedure diff --git a/server/src/controllers/item/deleteGlobalItem.ts b/server/src/controllers/item/deleteGlobalItem.ts index 929d9ae00..0b11dc705 100644 --- a/server/src/controllers/item/deleteGlobalItem.ts +++ b/server/src/controllers/item/deleteGlobalItem.ts @@ -1,25 +1,19 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { deleteGlobalItemService } from '../../services/item/item.service'; import { z } from 'zod'; -/** - * Deletes a global item. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} - Returns a promise that resolves to void. - */ -// export const deleteGlobalItem = async (req, res, next) => { -// try { -// const { itemId } = req.params; - -// const itemDeleted = await deleteGlobalItemService(itemId); - -// res.locals.data = itemDeleted; -// responseHandler(res); -// } catch (error) { -// next(UnableToDeleteItemError); -// } -// }; +export const deleteGlobalItem = async (c) => { + try { + const { itemId } = await c.req.json(); + const itemDeleted = await deleteGlobalItemService(itemId); + return c.json({ itemDeleted }, 200); + } catch (error) { + return c.json( + { error: `Failed to delete global item: ${error.message}` }, + 500, + ); + } +}; export function deleteGlobalItemRoute() { return protectedProcedure diff --git a/server/src/controllers/item/deleteItem.ts b/server/src/controllers/item/deleteItem.ts index fac345058..6aefa4d03 100644 --- a/server/src/controllers/item/deleteItem.ts +++ b/server/src/controllers/item/deleteItem.ts @@ -1,27 +1,16 @@ import { deleteItemService } from '../../services/item/item.service'; import * as validator from '@packrat/validations'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; -/** - * Deletes an item from the database. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} The deleted item. - */ - -// export const deleteItem = async (req, res, next) => { -// try { -// const { itemId, packId } = req.body; - -// const itemDeleted = await deleteItemService(itemId, packId); - -// res.locals.data = itemDeleted; -// responseHandler(res); -// } catch (error) { -// console.error(error); -// next(UnableToDeleteItemError); -// } -// }; +export const deleteItem = async (c) => { + try { + const { itemId, packId } = await c.req.parseBody(); + const itemDeleted = await deleteItemService(itemId, packId); + return c.json({ itemDeleted }, 200); + } catch (error) { + return c.json({ error: `Failed to delete item: ${error.message}` }, 500); + } +}; export function deleteItemRoute() { return protectedProcedure diff --git a/server/src/controllers/item/editGlobalItemAsDuplicate.ts b/server/src/controllers/item/editGlobalItemAsDuplicate.ts index 20185a6a6..c448b4431 100644 --- a/server/src/controllers/item/editGlobalItemAsDuplicate.ts +++ b/server/src/controllers/item/editGlobalItemAsDuplicate.ts @@ -1,43 +1,30 @@ import { editGlobalItemAsDuplicateService } from '../../services/item/item.service'; import { z } from 'zod'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; -/** - * Edit a global item by duplicating it with new changes. - * @param {Object} req - The request object. - * @param {Object} req.params - The parameters object. - * @param {string} req.params.itemId - The ID of the item to edit. - * @param {Object} req.body - The request body object. - * @param {string} req.body.packId - The ID of the pack. - * @param {string} req.body.name - The name of the item. - * @param {number} req.body.weight - The weight of the item. - * @param {number} req.body.quantity - The quantity of the item. - * @param {string} req.body.unit - The unit of the item. - * @param {string} req.body.type - The type of the item. - * @param {Object} res - The response object. - * @return {Object} The updated item. - */ -// export const editGlobalItemAsDuplicate = async (req, res, next) => { -// try { -// const { itemId } = req.params; -// const { packId, name, weight, quantity, unit, type } = req.body; +export const editGlobalItemAsDuplicate = async (c) => { + try { + const { itemId } = await c.req.param(); + const { packId, name, weight, quantity, unit, type } = + await c.req.parseBody(); -// const newItem = await editGlobalItemAsDuplicateService( -// itemId, -// packId, -// name, -// weight, -// quantity, -// unit, -// type, -// ); - -// res.locals.data = newItem; -// responseHandler(res); -// } catch (error) { -// next(UnableToDeleteItemError); -// } -// }; + const item = await editGlobalItemAsDuplicateService( + itemId, + packId, + name, + weight, + quantity, + unit, + type, + ); + return c.json({ item }, 200); + } catch (error) { + return c.json( + { error: `Failed to edit item as duplicate: ${error.message}` }, + 500, + ); + } +}; export function editGlobalItemAsDuplicateRoute() { return protectedProcedure diff --git a/server/src/controllers/item/editItem.ts b/server/src/controllers/item/editItem.ts index 29d954d23..7342079fb 100644 --- a/server/src/controllers/item/editItem.ts +++ b/server/src/controllers/item/editItem.ts @@ -1,26 +1,17 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { editItemService } from '../../services/item/item.service'; import * as validator from '@packrat/validations'; -// export const editItem = async (req, res, next) => { -// try { -// const { id, name, weight, unit, quantity, type } = req.body; +export const editItem = async (c) => { + try { + const { id, name, weight, unit, quantity, type } = await c.req.json(); -// const newItem = await editItemService( -// id, -// name, -// weight, -// unit, -// quantity, -// type, -// ); - -// res.locals.data = newItem; -// responseHandler(res); -// } catch (error) { -// next(UnableToEditItemError); -// } -// }; + const item = await editItemService(id, name, weight, unit, quantity, type); + return c.json({ item }, 200); + } catch (error) { + return c.json({ error: `Failed to edit item: ${error.message}` }, 500); + } +}; export function editItemRoute() { return protectedProcedure.input(validator.editItem).mutation(async (opts) => { diff --git a/server/src/controllers/item/getItemById.ts b/server/src/controllers/item/getItemById.ts index 572959546..96bef32de 100644 --- a/server/src/controllers/item/getItemById.ts +++ b/server/src/controllers/item/getItemById.ts @@ -1,26 +1,17 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { getItemByIdService } from '../../services/item/item.service'; import * as validator from '@packrat/validations'; +import { type Context } from 'hono'; -/** - * Retrieves an item by its ID. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @param {string} req.body.id - The ID of the item to retrieve. - * @return {Object} The retrieved item. - */ -// export const getItemById = async (req, res, next) => { -// try { -// const { id } = req.body; - -// const item = await getItemByIdService(id); - -// res.locals.data = item; -// responseHandler(res); -// } catch (error) { -// next(ItemNotFoundError); -// } -// }; +export const getItemById = async (c: Context) => { + try { + const { id } = await c.req.param(); + const item = await getItemByIdService(id); + return c.json({ item }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getItemByIdRoute() { return protectedProcedure.input(validator.getItemById).query(async (opts) => { diff --git a/server/src/controllers/item/getItems.ts b/server/src/controllers/item/getItems.ts index 1dfbd1eab..97cf45bb8 100644 --- a/server/src/controllers/item/getItems.ts +++ b/server/src/controllers/item/getItems.ts @@ -1,26 +1,16 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { getItemsService } from '../../services/item/item.service'; import * as validator from '@packrat/validations'; -/** - * Retrieves a list of items associated with a pack. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @param {string} req.params.packId - The ID of the pack to retrieve items for. - * @return {Object} An array of items associated with the pack. - */ -// export const getItems = async (req, res, next) => { -// try { -// const { packId } = req.params; - -// const items = await getItemsService(packId); - -// res.locals.data = items; -// responseHandler(res); -// } catch (error) { -// next(ItemNotFoundError); -// } -// }; +export const getItems = async (c) => { + try { + const { packId } = c.req.param(); + const items = await getItemsService(packId || null); + return c.json({ items }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getItemsRoute() { return protectedProcedure.input(validator.getItems).query(async (opts) => { diff --git a/server/src/controllers/item/getItemsGlobally.ts b/server/src/controllers/item/getItemsGlobally.ts index 259851e11..bce638ddf 100644 --- a/server/src/controllers/item/getItemsGlobally.ts +++ b/server/src/controllers/item/getItemsGlobally.ts @@ -1,13 +1,16 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { getItemsGloballyService } from '../../services/item/item.service'; import { z } from 'zod'; -/** - * Retrieves globally available items. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} The items, page, and total pages. - */ +export const getItemsGlobally = async (c) => { + try { + const { limit, page, searchString } = await c.req.json(); + const result = await getItemsGloballyService(limit, page, searchString); + return c.json({ ...result, items: result.items }, 200); + } catch (error) { + return c.json({ error: `Failed to get items: ${error.message}` }, 500); + } +}; export function getItemsGloballyRoute() { return protectedProcedure diff --git a/server/src/controllers/item/searchItemsByName.ts b/server/src/controllers/item/searchItemsByName.ts index 2aa5beeed..b83998514 100644 --- a/server/src/controllers/item/searchItemsByName.ts +++ b/server/src/controllers/item/searchItemsByName.ts @@ -1,29 +1,18 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { searchItemsByNameService } from '../../services/item/item.service'; import { z } from 'zod'; +import { type Context } from 'hono'; -/** - * Searches for items by name. - * @param {Object} req - The request object. - * @param {Object} req.query - The query string parameters. - * @param {string} req.query.name - The name to search for. - * @param {Object} res - The response object. - * @return {Array} An array of items matching the search criteria. - */ -// const JoiObjectId = (message: any = 'valid id'): z.ZodString => -// z.string().regex(/^[0-9a-fA-F]{24}$/, { message }); - -// export const searchItemsByName = async (req, res, next) => { -// try { -// const { name, packId } = req.query; - -// const items = await searchItemsByNameService(name, packId); - -// res.status(200).json(items); -// } catch (error) { -// next(ItemNotFoundError); -// } -// }; +export const searchItemsByName = async (c: Context) => { + try { + const { name } = await c.req.query(); + + const items = await searchItemsByNameService(name); + return c.json({ items }, 200); + } catch (error) { + return c.json({ error: `Failed to get items: ${error.message}` }, 500); + } +}; export function searchItemsByNameRoute() { return protectedProcedure diff --git a/server/src/controllers/mapPreview/index.ts b/server/src/controllers/mapPreview/index.ts index 1e3145185..812eb66ac 100644 --- a/server/src/controllers/mapPreview/index.ts +++ b/server/src/controllers/mapPreview/index.ts @@ -1,21 +1,13 @@ // import { MAPBOX_ACCESS_TOKEN } from '../../config'; -import { MapPreviewError } from '../../helpers/errors'; -import { type Context, type Next } from 'hono'; - -/** - * Responds with map preview image from mapbox api - * - * @param {Request} req - Request object - * @param {Response} res - Respone object - * @param {NextFunction} next - The next middleware - * @returns {Promise} - Resolves with the preview image - */ -const getMapPreview = async (ctx: Context, next: Next) => { +import { type Context } from 'hono'; +import { responseHandler } from '../../helpers/responseHandler'; + +const getMapPreview = async (ctx: Context) => { try { const { env }: any = ctx; const { MAPBOX_ACCESS_TOKEN } = env; - const queryParams = Object.entries(ctx.req.query).reduce( + const queryParams = Object.entries(await ctx.req.query).reduce( (acc, [key, val], i, arr) => `${acc}${key}=${val}${i == arr.length - 1 ? '' : '&'}`, '', @@ -43,9 +35,11 @@ const getMapPreview = async (ctx: Context, next: Next) => { console.log('newResponse', newResponse); - return newResponse; + // return newResponse; + return ctx.json(newResponse, 200); } catch (error) { console.log(error); + return ctx.json({ error: error.message }, 400); // next(MapPreviewError); } }; diff --git a/server/src/controllers/openAi/getAIResponse.ts b/server/src/controllers/openAi/getAIResponse.ts index c0c565c8e..71d040d6b 100644 --- a/server/src/controllers/openAi/getAIResponse.ts +++ b/server/src/controllers/openAi/getAIResponse.ts @@ -2,13 +2,26 @@ import { getAIResponseService } from '../../services/openAi/openAi.service'; import { publicProcedure, protectedProcedure } from '../../trpc'; import { z } from 'zod'; -/** - * Retrieves an AI response based on user input and conversation history. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} The AI response and updated conversation object. - */ +interface AIResponseServiceResult { + aiResponse: any; + conversation: any; +} +export const getAIResponse = async (c) => { + try { + const { userId, userInput, itemTypeId, type } = await c.req.json(); + const { aiResponse, conversation } = (await getAIResponseService( + userId, + itemTypeId, + userInput, + type, + c.env.OPENAI_API_KEY, + )) as AIResponseServiceResult; + return c.json({ aiResponse, conversation }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getAIResponseRoute() { return protectedProcedure .input( diff --git a/server/src/controllers/openAi/getAISuggestions.ts b/server/src/controllers/openAi/getAISuggestions.ts index e7566753c..b98667a3f 100644 --- a/server/src/controllers/openAi/getAISuggestions.ts +++ b/server/src/controllers/openAi/getAISuggestions.ts @@ -1,13 +1,29 @@ import { getAISuggestionService } from '../../services/openAi/openAi.service'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { z } from 'zod'; -/** - * Retrieves an AI response based on user input and conversation history. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} The AI response and updated conversation object. - */ +interface AIResponseServiceResult { + aiResponse: any; + refined: any; +} + +export const getAISuggestions = async (c) => { + try { + const { userId, itemTypeId, type } = await c.req.json(); + const { aiResponse, refined } = (await getAISuggestionService( + userId, + itemTypeId, + type, + c.env.OPENAI_API_KEY, + )) as AIResponseServiceResult; + return c.json({ aiResponse, refined }); + } catch (error) { + return c.json( + { error: `Failed to get AI response: ${error.message}` }, + 500, + ); + } +}; export function getAISuggestionsRoute() { return protectedProcedure diff --git a/server/src/controllers/openAi/getUserChats.ts b/server/src/controllers/openAi/getUserChats.ts index ae25769b7..4b4ba0204 100644 --- a/server/src/controllers/openAi/getUserChats.ts +++ b/server/src/controllers/openAi/getUserChats.ts @@ -1,27 +1,16 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; -import { FailedToRetrieveUserChats } from '../../helpers/errors'; -import { responseHandler } from '../../helpers/responseHandler'; +import { protectedProcedure } from '../../trpc'; import { getUserChatsService } from '../../services/openAi/openAi.service'; import { z } from 'zod'; -/** - * Retrieves the chats of a user. - * @param {string} req.params.userId - The ID of the user. - * @param {string} req.params.itemTypeId - The ID of the pack or trip. - * @returns {object} The conversations of the user. - */ -// export const getUserChats = async (req, res, next) => { -// try { -// const { userId, itemTypeId } = req.params; - -// const result = await getUserChatsService(userId, itemTypeId); - -// res.locals.data = result; -// responseHandler(res); -// } catch (error) { -// next(FailedToRetrieveUserChats); -// } -// }; +export const getUserChats = async (c) => { + try { + const { userId, itemTypeId } = await c.req.json(); + const conversations = getUserChatsService(userId, itemTypeId); + return c.json({ conversations }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getUserChatsRoute() { return protectedProcedure diff --git a/server/src/controllers/pack/addPack.ts b/server/src/controllers/pack/addPack.ts index 51f6cd877..a3bba63ee 100644 --- a/server/src/controllers/pack/addPack.ts +++ b/server/src/controllers/pack/addPack.ts @@ -1,19 +1,16 @@ import { addPackService } from '../../services/pack/pack.service'; import * as validator from '@packrat/validations'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; -/** - * Adds a new pack to the database. - * @param {Object} req - The HTTP request object. - * @param {Object} res - The HTTP response object. - * @return {Promise} A promise that resolves to the created pack. - */ - -// export const addPack = async (req, res) => { -// const { name, owner_id, is_public } = req.body; -// const result = await addPackService(name, owner_id, is_public); -// res.status(200).json({ msg: 'success', ...result }); -// }; +export const addPack = async (c) => { + try { + const { name, owner_id, is_public } = await c.req.json(); + const pack = await addPackService(name, owner_id, is_public); + return c.json({ pack }, 200); + } catch (error) { + return c.json({ error: `Failed to add pack: ${error.message}` }, 500); + } +}; export function addPackRoute() { return protectedProcedure.input(validator.addPack).mutation(async (opts) => { diff --git a/server/src/controllers/pack/deletePack.ts b/server/src/controllers/pack/deletePack.ts index b99dea8ba..56168583d 100644 --- a/server/src/controllers/pack/deletePack.ts +++ b/server/src/controllers/pack/deletePack.ts @@ -1,23 +1,16 @@ import { deletePackService } from '../../services/pack/pack.service'; import * as validator from '@packrat/validations'; -import { publicProcedure, protectedProcedure } from '../../trpc'; -/** - * Deletes a pack. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} A promise that resolves with the deletion result. - */ -// export const deletePack = async (req, res, next) => { -// try { -// const { packId } = req.body; +import { protectedProcedure } from '../../trpc'; -// await deletePackService(packId); - -// res.status(200).json({ msg: 'pack was deleted successfully' }); -// } catch (error) { -// next(UnableToDeletePackError); -// } -// }; +export const deletePack = async (c) => { + try { + const { packId } = await c.req.json(); + await deletePackService(packId); + return c.json({ msg: 'pack was deleted successfully' }, 200); + } catch (error) { + return c.json({ error: `Failed to delete pack: ${error.message}` }, 500); + } +}; export function deletePackRoute() { return protectedProcedure diff --git a/server/src/controllers/pack/duplicatePublicPack.ts b/server/src/controllers/pack/duplicatePublicPack.ts index 81049b6b0..3d73b3ce7 100644 --- a/server/src/controllers/pack/duplicatePublicPack.ts +++ b/server/src/controllers/pack/duplicatePublicPack.ts @@ -1,27 +1,19 @@ import { duplicatePublicPackService } from '../../services/pack/pack.service'; import * as validator from '@packrat/validations'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; -/** - * Duplicates a public pack. - * @param {Object} req - the request object - * @param {Object} res - the response object - * @return {Promise} - a promise that resolves with the duplicated pack - */ -// export const duplicatePublicPack = async (req, res, next) => { -// try { -// const { packId, ownerId, items } = req.body; - -// const result = await duplicatePublicPackService(packId, ownerId, items); - -// res.status(200).json({ -// msg: 'pack was duplicated successfully', -// data: result.pack, -// }); -// } catch (error) { -// next(UnableToDuplicatePackError); -// } -// }; +export const duplicatePublicPack = async (c) => { + try { + const { packId, ownerId, items } = await c.req.json(); + const result = await duplicatePublicPackService(packId, ownerId, items); + return c.json({ result }, 200); + } catch (error) { + return c.json( + { error: `Failed to duplicate public pack: ${error.message}` }, + 500, + ); + } +}; export function duplicatePublicPackRoute() { return protectedProcedure diff --git a/server/src/controllers/pack/editPack.ts b/server/src/controllers/pack/editPack.ts index 7fbece236..e8c011404 100644 --- a/server/src/controllers/pack/editPack.ts +++ b/server/src/controllers/pack/editPack.ts @@ -1,28 +1,16 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; -import { UnableToEditPackError } from '../../helpers/errors'; -import { responseHandler } from '../../helpers/responseHandler'; +import { protectedProcedure } from '../../trpc'; import { editPackService } from '../../services/pack/pack.service'; import * as validator from '@packrat/validations'; -/** - * Edits a pack in the database. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} The updated pack. - */ - -// export const editPack = async (req, res, next) => { -// try { -// const { id } = req.body; - -// const newPack = await editPackService(id, req.body); - -// res.locals.data = newPack; -// responseHandler(res); -// } catch (error) { -// next(UnableToEditPackError); -// } -// }; +export const editPack = async (c) => { + try { + const packData = await c.req.json(); + const pack = await editPackService(packData); + return c.json({ pack }, 200); + } catch (error) { + return c.json({ error: `Failed to edit pack: ${error.message}` }, 500); + } +}; export function editPackRoute() { return protectedProcedure.input(validator.editPack).mutation(async (opts) => { diff --git a/server/src/controllers/pack/getPackById.ts b/server/src/controllers/pack/getPackById.ts index a2b725863..d17fc1ac2 100644 --- a/server/src/controllers/pack/getPackById.ts +++ b/server/src/controllers/pack/getPackById.ts @@ -1,25 +1,16 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { getPackByIdService } from '../../services/pack/pack.service'; import * as validator from '@packrat/validations'; -/** - * Retrieves a pack by its ID and returns it as a JSON response. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} The pack object as a JSON response. - */ -// export const getPackById = async (req, res, next) => { -// try { -// const { packId } = req.params; - -// const pack = await getPackByIdService(packId); - -// res.locals.data = pack; -// responseHandler(res); -// } catch (error) { -// next(PackNotFoundError); -// } -// }; +export const getPackById = async (c) => { + try { + const { packId } = await c.req.param(); + const pack = await getPackByIdService(packId); + return c.json({ pack }, 200); + } catch (error) { + return c.json({ error: `Failed to get pack: ${error.message}` }, 500); + } +}; export function getPackByIdRoute() { return protectedProcedure.input(validator.getPackById).query(async (opts) => { diff --git a/server/src/controllers/pack/getPacks.ts b/server/src/controllers/pack/getPacks.ts index f9a81757f..791fcf4ca 100644 --- a/server/src/controllers/pack/getPacks.ts +++ b/server/src/controllers/pack/getPacks.ts @@ -1,28 +1,16 @@ import { getPacksService } from '../../services/pack/pack.service'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; -/** - * Retrieves packs associated with a specific owner. - * @param {Object} req - Express request object. - * @param {Object} res - Express response object. - * @return {Promise} - Array of packs. - */ -// export const getPacks = async (req, res, next) => { -// try { -// const { ownerId } = req.params; -// const { queryBy } = req.query; - -// const packs = await getPacksService(ownerId, queryBy); - -// res.locals.data = packs; - -// const message = 'Packs retrieved successfully'; -// responseHandler(res, message); -// } catch (error) { -// next(PackNotFoundError); -// } -// }; +export const getPacks = async (c) => { + try { + const { ownerId, queryBy } = await c.req.param(); + const packs = await getPacksService(ownerId, queryBy || null); + return c.json({ packs, message: 'Packs retrieved successfully' }, 200); + } catch (error) { + return c.json({ error: `Failed to get packs: ${error.message}` }, 500); + } +}; export function getPacksRoute() { return protectedProcedure.input(validator.getPacks).query(async (opts) => { diff --git a/server/src/controllers/pack/getPublicPacks.ts b/server/src/controllers/pack/getPublicPacks.ts index 9d935ef59..e01e8b12b 100644 --- a/server/src/controllers/pack/getPublicPacks.ts +++ b/server/src/controllers/pack/getPublicPacks.ts @@ -1,25 +1,23 @@ import { publicProcedure, protectedProcedure } from '../../trpc'; import { getPublicPacksService } from '../../services/pack/pack.service'; import { z } from 'zod'; +import { type Context } from 'hono'; -/** - * Retrieves public packs based on the given query parameter. - * @param {Object} req - the request object - * @param {Object} res - the response object - * @return {Promise} - a promise that resolves with the retrieved public packs - */ -// export const getPublicPacks = async (req, res, next) => { -// try { -// const { queryBy } = req.query; - -// const publicPacks = await getPublicPacksService(queryBy); - -// res.locals.data = publicPacks; -// responseHandler(res); -// } catch (error) { -// next(PackNotFoundError); -// } -// }; +export const getPublicPacks = async (c: Context) => { + try { + const { queryBy } = await c.req.query(); + const packs = await getPublicPacksService(queryBy); + return c.json( + { packs, message: 'Public packs retrieved successfully' }, + 200, + ); + } catch (error) { + return c.json( + { error: `Failed to get public packs: ${error.message}` }, + 500, + ); + } +}; export function getPublicPacksRoute() { return protectedProcedure diff --git a/server/src/controllers/pack/scorePack.ts b/server/src/controllers/pack/scorePack.ts index 2f2da42e3..3617813b4 100644 --- a/server/src/controllers/pack/scorePack.ts +++ b/server/src/controllers/pack/scorePack.ts @@ -1,26 +1,16 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { scorePackService } from '../../services/pack/pack.service'; import * as validator from '@packrat/validations'; -/** - * Scores a pack by calculating its score and updating the pack object in the database. - * @param {Object} req - The request object containing the packId parameter. - * @param {Object} res - The response object used to send the response. - * @return {Promise} A promise that resolves to the updated pack object or an error message. - */ -// export const scorePack = async (req, res, next) => { -// try { -// const { packId } = req.params; - -// const updatedPack = await scorePackService(packId); - -// console.log('updatedPack', updatedPack); - -// res.status(200).json({ msg: 'Pack was scored successfully', updatedPack }); -// } catch (error) { -// next(UnableToScorePackError); -// } -// }; +export const scorePack = async (c) => { + try { + const { packId } = await c.req.param(); + const pack = await scorePackService(packId); + return c.json({ pack }, 200); + } catch (error) { + return c.json({ error: `Failed to score pack: ${error.message}` }, 500); + } +}; export function scorePackRoute() { return protectedProcedure diff --git a/server/src/controllers/passport/signInGoogle.ts b/server/src/controllers/passport/signInGoogle.ts index 352095a55..89ef917b2 100644 --- a/server/src/controllers/passport/signInGoogle.ts +++ b/server/src/controllers/passport/signInGoogle.ts @@ -1,168 +1,97 @@ -// integrate passport js for email/passport sign in and google sign in - -// import passport from 'passport'; -// import { Strategy as LocalStrategy } from 'passport-local'; - -import bcrypt from 'bcryptjs'; import * as jwt from 'hono/jwt'; -import { sendWelcomeEmail, resetEmail } from '../../utils/accountEmail'; -// import { prisma } from '../../prisma'; -// import { User } from '../../prisma/methods'; - -// import { -// GOOGLE_CLIENT_ID, -// GOOGLE_CLIENT_SECRET, -// REDIRECT_URL, -// SERVER_ROOT_URI, -// } from '../../config'; - -// import { OAuth2Client } from 'google-auth-library'; +import { sendWelcomeEmail } from '../../utils/accountEmail'; + import utilsService from '../../utils/utils.service'; -import { responseHandler } from '../../helpers/responseHandler'; import { publicProcedure } from '../../trpc'; import z from 'zod'; import { User } from '../../drizzle/methods/User'; import { and, eq } from 'drizzle-orm'; import { user as UserTable } from '../../db/schema'; -// const client = new OAuth2Client( -// GOOGLE_CLIENT_ID, -// GOOGLE_CLIENT_SECRET, -// `${SERVER_ROOT_URI}/user/${REDIRECT_URL}`, -// ); - -// Passport Configuration -// Local Strategy -// passport.use( -// new LocalStrategy( -// { -// usernameField: 'email', -// passwordField: 'password', -// }, -// async (email, password, done) => { -// try { -// const user = await prisma.user.findUnique({ -// where: { -// email: email, -// }, -// }); -// if (!user) { -// return done(null, false, { message: 'Incorrect email.' }); -// } - -// const validPassword = await bcrypt.compare(password, user.password); - -// if (!validPassword) { -// return done(null, false, { message: 'Incorrect passwordsss.' }); -// } - -// return done(null, user); -// } catch (err) { -// return done(err); -// } -// }, -// ), -// ); - -// /** -// * Sign in with Google. -// * @param {Object} req - The request object. -// * @param {Object} req.body - The request body. -// * @param {string} req.body.idToken - The Google ID token. -// * @param {Object} res - The response object. -// * @return {Promise} The function does not return anything. -// */ -// export const signInGoogle = async (req, res) => { -// try { -// const { idToken } = req.body; - -// const decodedToken: any = jwt.decode(idToken); - -// if (!decodedToken) { -// throw new Error('Invalid ID token'); -// } - -// const { email, name, sub: googleId } = decodedToken; - -// const alreadyGoogleSignin = await prisma.user.findUnique({ -// where: { -// email: email, -// googleId: googleId, -// }, -// }); -// if (!alreadyGoogleSignin) { -// const isLocalLogin = await prisma.user.findUnique({ -// where: { -// email: email, -// }, -// }); - -// if (isLocalLogin) { -// throw new Error('Already user registered on that email address'); -// } - -// const randomPassword = utilsService.randomPasswordGenerator(8); -// const username = utilsService.randomUserNameCode(email, 4); -// const user = await prisma.user.create({ -// data: { -// email, -// name, -// password: randomPassword, -// googleId, -// username, -// }, -// }); - -// const userWithMethods = User(user); -// await userWithMethods.generateAuthToken(); - -// sendWelcomeEmail(user.email, user.name); - -// res.locals.data = { user }; -// responseHandler(res); -// } else { -// if (!alreadyGoogleSignin.password) { -// alreadyGoogleSignin.password = utilsService.randomPasswordGenerator(8); -// } - -// alreadyGoogleSignin.googleId = googleId; -// await prisma.user.update({ -// where: { -// email: alreadyGoogleSignin.email, -// }, -// data: { -// googleId: googleId, -// }, -// }); - -// const userWithMethods = User(alreadyGoogleSignin); -// await userWithMethods.generateAuthToken(); - -// res.locals.data = { user: alreadyGoogleSignin }; -// responseHandler(res); -// } -// } catch (err) { -// res.status(400).send({ message: err.message }); -// } -// }; - -// passport.serializeUser((user, done) => { -// done(null, user.id); -// }); - -// passport.deserializeUser((id, done) => { -// prisma.user -// .findUnique({ -// where: { -// id: id, -// }, -// }) -// .then((user) => { -// done(null, user); -// }) -// .catch((err) => { -// done(err, null); -// }); -// }); +import { type Context } from 'hono'; + +export const signInGoogle = async (c: Context) => { + try { + const { idToken } = await c.req.json(); + + const decodedToken: any = jwt.decode(idToken); + if (!decodedToken) { + throw new Error('Invalid ID token'); + } + console.log('decodedToken', decodedToken) + const { + payload: { email, name, sub: googleId }, + } = decodedToken; + + const userClass = new User(); + const alreadyGoogleSignin = await userClass.findUnique({ + where: { + email, + googleId, + }, + }); + + if (!alreadyGoogleSignin) { + const isLocalLogin = await userClass.findUnique({ + where: { + email, + }, + }); + + if (isLocalLogin) { + throw new Error('Already user registered on that email address'); + } + + const randomPassword = utilsService.randomPasswordGenerator(8); + const username = utilsService.randomUserNameCode(email, 4); + + const user = await userClass.create({ + email, + name, + password: randomPassword, + googleId, + username, + }); + + await userClass.generateAuthToken(c.env.JWT_SECRET, user.id); + + sendWelcomeEmail( + user.email, + user.name, + c.env.STMP_EMAIL, + c.env.SEND_GRID_API_KEY, + ); + return user; + } else { + if (!alreadyGoogleSignin.password) { + alreadyGoogleSignin.password = utilsService.randomPasswordGenerator(8); + } + + await userClass.generateAuthToken( + c.env.JWT_SECRET, + alreadyGoogleSignin.id, + ); + + if (!alreadyGoogleSignin.googleId) { + throw new Error('Google ID is missing'); + } + + const updatedUser = await userClass.update( + { + googleId, + }, + and( + eq(UserTable.id, alreadyGoogleSignin.id), + eq(UserTable.googleId, alreadyGoogleSignin.googleId), + eq(UserTable.email, alreadyGoogleSignin.email), + ), + ); + return c.json(updatedUser?.[0], 200); + } + } catch (err) { + return c.json({ message: err.message }); + // throw new Error(`Google Signin failed: ${err.message}`); + } +}; export function googleSigninRoute() { return publicProcedure diff --git a/server/src/controllers/passwordReset/handlePasswordReset.ts b/server/src/controllers/passwordReset/handlePasswordReset.ts index bed13dacf..6dcd8fdee 100644 --- a/server/src/controllers/passwordReset/handlePasswordReset.ts +++ b/server/src/controllers/passwordReset/handlePasswordReset.ts @@ -3,6 +3,40 @@ import { publicProcedure } from '../../trpc'; import { hashPassword, verifyPasswordResetToken } from '../../utils/user'; import { User } from '../../drizzle/methods/User'; +export const handlePasswordReset = async (c) => { + try { + const token = c.req.params.token; + const { password } = await c.req.parseBody(); + const { env } = c; + const userClass = new User(); + const email = await verifyPasswordResetToken(token, env.JWT_SECRET); + const hashedPassword = await hashPassword(env.JWT_SECRET, password); + const user = await userClass.findUser({ email }); + + if (!user) { + return { error: 'No user found with this email address' }; + } + + if (!user.passwordResetTokenExpiration) { + return { error: 'Password reset token expiration is not defined' }; + } + + if (Date.now() > user.passwordResetTokenExpiration.getTime()) { + return { error: 'Password reset token has expired' }; + } + await userClass.update({ + id: user.id, + password: hashedPassword, + passwordResetToken: null, + passwordResetTokenExpiration: null, + }); + + return c.json({ message: 'Password reset successful' }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; + export function handlePasswordResetRoute() { return publicProcedure .input(z.object({ token: z.string(), password: z.string() })) diff --git a/server/src/controllers/passwordReset/requestPasswordReset.ts b/server/src/controllers/passwordReset/requestPasswordReset.ts index 4e0ded705..b66b6edaf 100644 --- a/server/src/controllers/passwordReset/requestPasswordReset.ts +++ b/server/src/controllers/passwordReset/requestPasswordReset.ts @@ -3,12 +3,32 @@ import { z } from 'zod'; import { resetEmail } from '../../utils/accountEmail'; import { User } from '../../drizzle/methods/User'; -/** - * Sends a password reset email to the user and updates the user's password reset token. - * @param {Object} req - The HTTP request object. - * @param {Object} res - The HTTP response object. - * @return {Object} The HTTP response object with a success message or an error message. - */ +export const requestPasswordResetEmailAndToken = async (c) => { + try { + const { email } = await c.req.json(); + const userClass = new User(); + const jwtSecret = c.env.JWT_SECRET; + const clientUrl = c.env.CLIENT_URL; + const user = await userClass.findUser({ email }); + if (!user) { + return { error: 'No user found with this email address' }; + } + const resetUrl = await userClass.generateResetToken( + jwtSecret, + clientUrl, + user.id, + ); + await resetEmail( + email, + resetUrl, + c.env.STMP_EMAIL, + c.env.SEND_GRID_API_KEY, + ); + return c.json({ message: 'Password reset email sent successfully' }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function requestPasswordResetEmailAndTokenRoute() { return publicProcedure diff --git a/server/src/controllers/template/addTemplate.ts b/server/src/controllers/template/addTemplate.ts index c3280bbe9..b62753c0c 100644 --- a/server/src/controllers/template/addTemplate.ts +++ b/server/src/controllers/template/addTemplate.ts @@ -3,32 +3,21 @@ import { UserNotFoundError } from '../../helpers/errors'; import { addTemplateService } from '../../services/template/template.service'; import { User } from '../../drizzle/methods/User'; import * as validator from '@packrat/validations'; - -// import { prisma } from '../../prisma'; -/** - * Adds a template to the database. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} The created template. - */ -// export const addTemplate = async (req, res, next) => { -// const { type, templateId, isGlobalTemplate, createdBy } = req.body; - -// const user = await prisma.user.findUnique({ -// where: { -// id: createdBy, -// }, -// }); - -// if (!user) { -// next(UserNotFoundError); -// } - -// await addTemplateService(type, templateId, isGlobalTemplate, createdBy); - -// res.locals.data = { message: 'Template added successfully' }; -// responseHandler(res); -// }; +export const addTemplate = async (c) => { + try { + const { type, templateId, isGlobalTemplate, createdBy } = + await c.req.json(); + const userClass = new User(); + const user = await userClass.findUser({ userId: createdBy }); + if (!user) { + throw new Error(UserNotFoundError.message); + } + await addTemplateService(type, templateId, isGlobalTemplate, createdBy); + return c.json({ message: 'Template added successfully' }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function addTemplateRoute() { return protectedProcedure diff --git a/server/src/controllers/template/deleteTemplate.ts b/server/src/controllers/template/deleteTemplate.ts index 6425ae341..48279c903 100644 --- a/server/src/controllers/template/deleteTemplate.ts +++ b/server/src/controllers/template/deleteTemplate.ts @@ -3,33 +3,21 @@ import { TemplateNotFoundError } from '../../helpers/errors'; import * as validator from '@packrat/validations'; import { Template } from '../../drizzle/methods/template'; -// import { prisma } from '../../prisma'; - -/** - * Deletes a template. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} A Promise that resolves when the template is deleted. - */ -// export const deleteTemplate = async (req, res, next) => { -// const { templateId } = req.params; -// const template = await prisma.template.findUnique({ -// where: { -// id: templateId, -// }, -// }); - -// if (template) { -// await prisma.template.delete({ -// where: { -// id: templateId, -// }, -// }); -// res.json({ message: 'Template removed' }); -// } else { -// next(TemplateNotFoundError); -// } -// }; +export const deleteTemplate = async (c) => { + try { + const { templateId } = await c.req.json(); + const templateClass = new Template(); + const template = await templateClass.findTemplate(templateId); + if (template) { + await templateClass.delete(templateId); + return c.json({ message: 'Template removed' }, 200); + } else { + return c.json({ error: TemplateNotFoundError.message }, 404); + } + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function deleteTemplateRoute() { const templateClass = new Template(); diff --git a/server/src/controllers/template/editTemplate.ts b/server/src/controllers/template/editTemplate.ts index c9f73a7c4..42fe525d5 100644 --- a/server/src/controllers/template/editTemplate.ts +++ b/server/src/controllers/template/editTemplate.ts @@ -1,25 +1,20 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { editTemplateService } from '../../services/template/template.service'; -import { z } from 'zod'; import * as validator from '@packrat/validations'; -/** - * Edits a template. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} - A promise that resolves when the template is edited. - */ -// export const editTemplate = async (req, res) => { -// const { templateId } = req.params; -// const { type, isGlobalTemplate } = req.body; -// const updatedTemplate = await editTemplateService( -// templateId, -// type, -// isGlobalTemplate, -// ); -// res.locals.data = updatedTemplate; -// responseHandler(res); -// }; +export const editTemplate = async (c) => { + try { + const { templateId, type, isGlobalTemplate } = await c.req.json(); + const updatedTemplate = await editTemplateService( + templateId, + type, + isGlobalTemplate, + ); + return c.json({ updatedTemplate }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function editTemplateRoute() { return protectedProcedure diff --git a/server/src/controllers/template/getTemplateById.ts b/server/src/controllers/template/getTemplateById.ts index efc9b52e7..310e82fa7 100644 --- a/server/src/controllers/template/getTemplateById.ts +++ b/server/src/controllers/template/getTemplateById.ts @@ -1,38 +1,18 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { TemplateNotFoundError } from '../../helpers/errors'; -// import { responseHandler } from '../../helpers/responseHandler'; import * as validator from '@packrat/validations'; import { Template } from '../../drizzle/methods/template'; -// import { prisma } from '../../prisma'; -/** - * Retrieves a template by its ID. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} A promise that resolves with the template or rejects with an error. - */ -// export const getTemplateById = async (req, res, next) => { -// const { templateId } = req.params; - -// const template = await prisma.template.findUnique({ -// where: { -// id: templateId, -// }, -// include: { -// createdBy: { -// select: { -// username: true, -// }, -// }, -// } as never, -// }); -// if (template) { -// res.locals.data = template; -// responseHandler(res); -// } else { -// next(TemplateNotFoundError); -// } -// }; +export const getTemplateById = async (c) => { + try { + const { templateId } = await c.req.param(); + const templateClass = new Template(); + const template = await templateClass.findTemplate(templateId, true); + return c.json({ template }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getTemplateByIdRoute() { const templateClass = new Template(); diff --git a/server/src/controllers/template/getTemplates.ts b/server/src/controllers/template/getTemplates.ts index f5f89230f..1f58439cc 100644 --- a/server/src/controllers/template/getTemplates.ts +++ b/server/src/controllers/template/getTemplates.ts @@ -1,25 +1,16 @@ +import { type Context } from 'hono'; import { Template } from '../../drizzle/methods/template'; -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; -// import { prisma } from '../../prisma'; -/** - * Retrieves templates from the database and sends them as a JSON response. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} - The templates retrieved from the database. - */ -// export const getTemplates = async (req, res) => { -// const templates = await prisma.template.findMany({ -// include: { -// createdBy: { -// select: { -// username: true, -// }, -// }, -// }, -// }); -// res.json(templates); -// }; +export const getTemplates = async (c: Context) => { + try { + const templateClass = new Template(); + const templates = await templateClass.findMany(); + return c.json(templates, 200); + } catch (error) { + return c.json({ error: error.message }, 400); + } +}; export function getTemplatesRoute() { const templateClass = new Template(); diff --git a/server/src/controllers/trip/addTrip.ts b/server/src/controllers/trip/addTrip.ts index b21a705f8..7b94e4413 100644 --- a/server/src/controllers/trip/addTrip.ts +++ b/server/src/controllers/trip/addTrip.ts @@ -1,50 +1,16 @@ import { publicProcedure, protectedProcedure } from '../../trpc'; import { addTripService } from '../../services/trip/addTripService'; import * as validator from '@packrat/validations'; -/** - * Adds a trip to the database. - * @param {Object} req - The request object containing the trip details. - * @param {Object} res - The response object. - * @return {Promise} A promise that resolves to a success message or rejects with an error message. - */ -// export const addTrip = async (req, res, next) => { -// try { -// const { -// name, -// description, -// duration, -// weather, -// start_date, -// end_date, -// destination, -// geoJSON, -// owner_id, -// packs, -// is_public, -// } = req.body; -// const tripDetails = { -// name, -// description, -// duration, -// weather, -// start_date, -// end_date, -// destination, -// geoJSON, -// owner_id, -// packs, -// is_public, -// }; - -// const result = await addTripService(tripDetails); - -// res.locals.data = result; -// responseHandler(res); -// } catch (error) { -// next(UnableToAddTripError); -// } -// }; +export const addTrip = async (c) => { + try { + const tripData = await c.req.json(); + const trip = await addTripService(tripData); + return c.json(trip, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function addTripRoute() { return protectedProcedure.input(validator.addTrip).mutation(async (opts) => { diff --git a/server/src/controllers/trip/deleteTrip.ts b/server/src/controllers/trip/deleteTrip.ts index af736d240..85127236b 100644 --- a/server/src/controllers/trip/deleteTrip.ts +++ b/server/src/controllers/trip/deleteTrip.ts @@ -2,25 +2,16 @@ import { publicProcedure, protectedProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; import { Trip } from '../../drizzle/methods/trip'; -// import { prisma } from '../../prisma'; -/** - * Deletes a trip from the database. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} A promise that resolves to a JSON object containing a success message if the trip was deleted successfully, or an error message if the trip could not be deleted. - */ -// export const deleteTrip = async (req, res, next) => { -// try { -// const { tripId } = req.body; - -// await prisma.trip.delete({ -// where: { id: tripId }, // Assuming tripId is the ID of the trip to delete -// }); -// res.status(200).json({ msg: 'trip was deleted successfully' }); -// } catch (error) { -// next(UnableToDeleteTripError); -// } -// }; +export const deleteTrip = async (c) => { + try { + const { tripId } = await c.req.json(); + const tripClass = new Trip(); + await tripClass.delete(tripId); + return c.json({ message: 'trip was deleted successfully' }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function deleteTripRoute() { return protectedProcedure diff --git a/server/src/controllers/trip/editTrip.ts b/server/src/controllers/trip/editTrip.ts index d4ba51a6d..a509c8391 100644 --- a/server/src/controllers/trip/editTrip.ts +++ b/server/src/controllers/trip/editTrip.ts @@ -1,34 +1,17 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; -import { UnableToEditTripError } from '../../helpers/errors'; -import { responseHandler } from '../../helpers/responseHandler'; - -// import { prisma } from '../../prisma'; +import { protectedProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; import { Trip } from '../../drizzle/methods/trip'; -/** - * Edits a trip by updating the trip details. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} The updated trip object. - */ -// export const editTrip = async (req, res, next) => { -// try { -// const { id } = req.body; -// const newTrip = await prisma.trip.update({ -// where: { id: id }, // Assuming id is the ID of the trip to update -// data: req.body, -// include: { -// packs: true, // Fetch associated packs -// }, -// }); - -// res.locals.data = newTrip; -// responseHandler(res); -// } catch (error) { -// next(UnableToEditTripError); -// } -// }; +export const editTrip = async (c) => { + try { + const tripData = await c.req.json(); + const tripClass = new Trip(); + const trip = await tripClass.update(tripData); + return c.json({ trip }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function editTripRoute() { return protectedProcedure.input(validator.editTrip).mutation(async (opts) => { diff --git a/server/src/controllers/trip/getPublicTrips.ts b/server/src/controllers/trip/getPublicTrips.ts index bd75c95a8..16e28d960 100644 --- a/server/src/controllers/trip/getPublicTrips.ts +++ b/server/src/controllers/trip/getPublicTrips.ts @@ -1,26 +1,17 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; +import { protectedProcedure } from '../../trpc'; import { getPublicTripsService } from '../../services/trip/getPublicTripService'; -import * as validator from '@packrat/validations'; import { z } from 'zod'; +import { type Context } from 'hono'; -/** - * Retrieves public trips based on the given query parameter. - * @param {object} req - The request object. - * @param {object} res - The response object. - * @return {object} The public trips as a JSON response. - */ -// export const getPublicTrips = async (req, res, next) => { -// try { -// const { queryBy } = req.query; - -// const publicTrips = await getPublicTripsService(queryBy); - -// res.locals.data = publicTrips; -// responseHandler(res); -// } catch (error) { -// next(TripNotFoundError); -// } -// }; +export const getPublicTrips = async (c: Context) => { + try { + const { queryBy } = await c.req.json(); + const trips = await getPublicTripsService(queryBy); + return c.json({ trips }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getPublicTripsRoute() { return protectedProcedure diff --git a/server/src/controllers/trip/getTrip.ts b/server/src/controllers/trip/getTrip.ts index acb0ee75e..5c1bbc7dc 100644 --- a/server/src/controllers/trip/getTrip.ts +++ b/server/src/controllers/trip/getTrip.ts @@ -2,24 +2,15 @@ import { publicProcedure, protectedProcedure } from '../../trpc'; import { getTripsService } from '../../services/trip/getTripsService'; import * as validator from '@packrat/validations'; -/** - * Retrieves trips belonging to a specific owner. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} The trips owned by the specified owner. - */ -// export const getTrips = async (req, res, next) => { -// try { -// const { ownerId } = req.params; - -// const trips = await getTripsService(ownerId); - -// res.locals.data = trips; -// responseHandler(res); -// } catch (error) { -// next(TripNotFoundError); -// } -// }; +export const getTrips = async (c) => { + try { + const { owner_id } = await c.req.parseParams(); + const trips = await getTripsService(owner_id); + return c.json({ trips }, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getTripsRoute() { return protectedProcedure.input(validator.getTrips).query(async (opts) => { diff --git a/server/src/controllers/trip/getTripById.ts b/server/src/controllers/trip/getTripById.ts index 1aa7e2c21..f26a4f357 100644 --- a/server/src/controllers/trip/getTripById.ts +++ b/server/src/controllers/trip/getTripById.ts @@ -1,24 +1,16 @@ import { publicProcedure, protectedProcedure } from '../../trpc'; import { getTripByIdService } from '../../services/trip/getTripByIdService'; import * as validator from '@packrat/validations'; -/** - * Retrieves a trip by its ID and returns the trip details. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} A promise that resolves to the trip details. - */ -// export const getTripById = async (req, res, next) => { -// try { -// const { tripId } = req.params; -// const tripDetails = await getTripByIdService(tripId); - -// res.locals.data = tripDetails; -// responseHandler(res); -// } catch (error) { -// next(TripNotFoundError); -// } -// }; +export const getTripById = async (c) => { + try { + const { tripId } = await c.req.param(); + const trip = await getTripByIdService(tripId); + return c.json(trip, 200); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getTripByIdRoute() { return protectedProcedure.input(validator.getTripById).query(async (opts) => { diff --git a/server/src/controllers/user/deleteUser.ts b/server/src/controllers/user/deleteUser.ts index f76b58d7e..56c376757 100644 --- a/server/src/controllers/user/deleteUser.ts +++ b/server/src/controllers/user/deleteUser.ts @@ -2,28 +2,16 @@ import { publicProcedure, protectedProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; import { User } from '../../drizzle/methods/User'; -/** - * Deletes a user from the database. - * @param {Object} req - The request object containing the user ID. - * @param {Object} res - The response object. - * @return {Promise} A promise that resolves to the message "user was deleted successfully" if the user is deleted, or rejects with an error message if there is an error. - */ -// export const deleteUser = async (req, res, next) => { -// try { -// const { userId } = req.body; - -// await prisma.user.delete({ -// where: { -// id: userId, -// }, -// }); - -// res.locals.data = { message: 'User deleted successfully' }; -// responseHandler(res); -// } catch (error) { -// next(UnableToEditUserError); -// } -// }; +export const deleteUser = async (c) => { + try { + const { userId } = await c.req.json(); + const user = new User(); + await user.delete(userId); + return c.json({ message: 'User deleted successfully' }, 200); + } catch (error) { + return c.json({ error: `Failed to delete user: ${error.message}` }, 500); + } +}; export function deleteUserRoute() { return protectedProcedure diff --git a/server/src/controllers/user/editUser.ts b/server/src/controllers/user/editUser.ts index 29a6d7f40..c03e4a145 100644 --- a/server/src/controllers/user/editUser.ts +++ b/server/src/controllers/user/editUser.ts @@ -2,36 +2,46 @@ import { publicProcedure, protectedProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; import { User } from '../../drizzle/methods/User'; import { hashPassword } from '../../utils/user'; -import bcrypt from 'bcryptjs'; -/** - * Edits a user. - * @param {Object} req - The request object. - * @param {Object} req.body - The body of the request. - * @param {string} req.body.userId - The ID of the user to edit. - * @param {Object} res - The response object. - * @return {Promise} A promise that resolves to the edited user. - */ -// export const editUser = async (req, res, next) => { -// try { -// const { userId } = req.body; - -// const editedUser = await prisma.user.update({ -// where: { -// id: userId, -// }, -// data: req.body, -// select: { -// favorites: true, -// }, -// }); +export const editUser = async (c) => { + try { + let { + id, + name, + email, + code, + role, + username, + profileImage, + preferredWeather, + preferredWeight, + password, + } = await c.req.json(); -// res.locals.data = editedUser; -// responseHandler(res); -// } catch (error) { -// next(UnableToEditUserError); -// } -// }; + const JWT_SECRET = c.env.JWT_SECRET; + const userClass = new User(); + if (password) { + password = await hashPassword(JWT_SECRET, password); + } + const data = { + id, + ...(name && { name }), + ...(password && { password }), + ...(email && { email }), + ...(code && { code }), + ...(role && { role }), + ...(username && { username }), + ...(profileImage && { profileImage }), + ...(preferredWeather && { preferredWeather }), + ...(preferredWeight && { preferredWeight }), + }; + const editedUser = await userClass.update(data); + return c.json({ editedUser }, 200); + } catch (error) { + console.error('Error editing user:', error); + return c.json({ error: 'Internal Server Error' }, 500); + } +}; export function editUserRoute() { return protectedProcedure.input(validator.editUser).mutation(async (opts) => { diff --git a/server/src/controllers/user/getGoogleAuthUrl.ts b/server/src/controllers/user/getGoogleAuthUrl.ts index 4cbd879c4..d513cb4ae 100644 --- a/server/src/controllers/user/getGoogleAuthUrl.ts +++ b/server/src/controllers/user/getGoogleAuthUrl.ts @@ -1,41 +1,28 @@ -import { google } from 'googleapis'; -// import { -// GOOGLE_CLIENT_ID, -// GOOGLE_CLIENT_SECRET, -// SERVER_ROOT_URI, -// REDIRECT_URL, -// UI_ROOT_URI, -// JWT_SECRET, -// } from '../../config'; +import { type Context } from 'hono'; import { publicProcedure } from '../../trpc'; -// const oauth2Client = new google.auth.OAuth2( -// GOOGLE_CLIENT_ID, -// GOOGLE_CLIENT_SECRET, -// `${SERVER_ROOT_URI}/user/${REDIRECT_URL}`, -// ); +export const getGoogleAuthURL = async (c: Context) => { + try { + const scopes = [ + 'https://www.googleapis.com/auth/userinfo.profile', + 'https://www.googleapis.com/auth/userinfo.email', + ]; -/** - * Retrieves the Google authentication URL. - * @param {object} req - The request object. - * @param {object} res - The response object. - * @return {object} The Google authentication URL and status. - */ -// export const getGoogleAuthURL = async (req, res) => { -// const scopes = [ -// 'https://www.googleapis.com/auth/userinfo.profile', -// 'https://www.googleapis.com/auth/userinfo.email', -// ]; -// return res.status(200).send({ -// googleUrl: oauth2Client.generateAuthUrl({ -// access_type: 'offline', -// prompt: 'consent', -// scope: scopes, -// }), -// status: 'success', -// statusCode: 200, -// }); -// }; + const scope = scopes.join(' '); + const clientId = c.env.GOOGLE_CLIENT_ID; + const clientSecret = c.env.GOOGLE_CLIENT_SECRET; + const redirectUri = `${c.env.SERVER_ROOT_URI}/user/${c.env.REDIRECT_URL}`; + + const googleUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&access_type=offline&prompt=consent&client_secret=${clientSecret}`; + + return c.json({ googleUrl, status: 'success' }, 200); + } catch (error) { + return c.json( + { error: `Failed to get Google Auth URL: ${error.message}` }, + 500, + ); + } +}; export function getGoogleAuthURLRoute() { const scopes = [ diff --git a/server/src/controllers/user/getMe.ts b/server/src/controllers/user/getMe.ts index 6843434f0..77f49663d 100644 --- a/server/src/controllers/user/getMe.ts +++ b/server/src/controllers/user/getMe.ts @@ -1,22 +1,16 @@ +import type { Context } from 'hono'; import { getUserByTokenService } from '../../services/user/getUserByToken'; import { protectedProcedure } from '../../trpc'; -/** - * Retrieves the user information and sends it as a response. - * @param {object} req - The request object. - * @param {object} res - The response object. - * @return {object} The user information. - */ -// export const getMe = async (req, res) => { -// try { -// const authHeader = req.headers.authorization; -// const token = authHeader.split(' ')[1]; -// const user = await getUserByTokenService(token); -// res.status(200).send(user); -// } catch (err) { -// res.status(401).send({ message: err.message }); -// } -// }; +export const getMe = async (c: Context) => { + try { + const { user } = await c.req.json(); + console.log('user ', user) + return c.json({ user }, 200); + } catch (error) { + return c.json({ error: `Failed to get user: ${error.message}` }, 500); + } +}; export function getMeRoute() { return protectedProcedure.query(async (opts) => { diff --git a/server/src/controllers/user/getUserById.ts b/server/src/controllers/user/getUserById.ts index d151b14d4..2557b2b2f 100644 --- a/server/src/controllers/user/getUserById.ts +++ b/server/src/controllers/user/getUserById.ts @@ -1,24 +1,27 @@ import { publicProcedure, protectedProcedure } from '../../trpc'; import { getUserByIdService } from '../../services/user/getUserByIdService'; import * as validator from '@packrat/validations'; -/** - * Retrieves a user by their ID from the database and returns the user object as a JSON response. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Object} The user object as a JSON response. - */ -// export const getUserById = async (req, res, next) => { -// try { -// const { userId } = req.params; +import { responseHandler } from '../../helpers/responseHandler'; +import { type Context } from 'hono'; -// const user = await getUserByIdService(userId); +export const getUserById = async (ctx: Context) => { + try { + // Correctly accessing route parameters in Hono + const { userId } = await ctx.req.param(); + const user = await getUserByIdService(userId); -// res.locals.data = user; -// responseHandler(res); -// } catch (error) { -// next(UserNotFoundError); -// } -// }; + // if (!c.locals) c.locals = {}; + // c.locals.data = user; + // return responseHandler(c); + + ctx.set('data', user); + return await responseHandler(ctx); + } catch (error) { + ctx.set('error', error.message); + return await responseHandler(ctx); + // return c.json({ error: `Failed to get user: ${error.message}` }, 500); + } +}; export function getUserByIdRoute() { return protectedProcedure.input(validator.getUserById).query(async (opts) => { diff --git a/server/src/controllers/user/getUsers.ts b/server/src/controllers/user/getUsers.ts index b8a25d180..6721b0655 100644 --- a/server/src/controllers/user/getUsers.ts +++ b/server/src/controllers/user/getUsers.ts @@ -1,40 +1,16 @@ -import { publicProcedure, protectedProcedure } from '../../trpc'; -import { UserNotFoundError } from '../../helpers/errors'; +import { protectedProcedure } from '../../trpc'; import { responseHandler } from '../../helpers/responseHandler'; import { User } from '../../drizzle/methods/User'; -// Middleware to check if user is authenticated -// export const isAuthenticated = async (req, res, next) => { -// const token = req.headers.authorization.split(" ")[1]; -// try { -// const decodedToken = await firebaseAdmin.auth().verifyIdToken(token); -// req.userData = decodedToken; -// next(); -// } catch (error) { -// res.status(401).json({ error: "Unauthorized" }); -// } -// }; - -/** - * Get all users from the database and send a JSON response. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} The JSON response containing the users. - */ -// export const getUsers = async (req, res, next) => { -// try { -// const users = await prisma.user.findMany({ -// include: { -// favorites: true, -// }, -// }); - -// res.locals.data = users; -// responseHandler(res); -// } catch (error) { -// next(UserNotFoundError); -// } -// }; +export const getUsers = async (c) => { + try { + const userClass = new User(); + const users = await userClass.findMany(); + return c.json(users, 200); + } catch (error) { + return c.json({ error: `Failed to get users: ${error.message}` }, 500); + } +}; export function getUsersRoute() { return protectedProcedure.query(async (opts) => { diff --git a/server/src/controllers/user/resetPassword.ts b/server/src/controllers/user/resetPassword.ts index a99c1808c..caf372713 100644 --- a/server/src/controllers/user/resetPassword.ts +++ b/server/src/controllers/user/resetPassword.ts @@ -2,29 +2,23 @@ import { publicProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; import { User } from '../../drizzle/methods/User'; import { hashPassword } from '../../utils/user'; -/** - * Resets the user's password. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} A promise that resolves when the password is successfully reset. - */ -// export const resetPassword = async (req, res) => { -// const { resetToken, password } = req.body; -// const user = await prisma.user.validateResetToken(resetToken); - -// await prisma.user.update({ -// where: { id: user.id }, -// data: { -// password: password, -// }, -// }); -// res.status(200).send({ -// message: 'Successfully reset password', -// status: 'success', -// statusCode: 200, -// }); -// }; +export const resetPassword = async (c) => { + try { + const { resetToken, password } = await c.req.json(); + const JWT_SECRET = c.env.JWT_SECRET; + const userClass = new User(); + const user = await userClass.validateResetToken(resetToken, JWT_SECRET); + if (!user) { + throw new Error('Invalid reset token'); + } + const hashedPassword = await hashPassword(JWT_SECRET, password); + await userClass.update({ id: user.id, password: hashedPassword }); + return c.json({ message: 'Successfully reset password' }, 200); + } catch (error) { + return c.json({ error: `Failed to reset password: ${error.message}` }, 500); + } +}; export function resetPasswordRoute() { return publicProcedure diff --git a/server/src/controllers/user/sentEmail.ts b/server/src/controllers/user/sentEmail.ts index 49aa51513..5dc66884f 100644 --- a/server/src/controllers/user/sentEmail.ts +++ b/server/src/controllers/user/sentEmail.ts @@ -2,33 +2,37 @@ import { publicProcedure } from '../../trpc'; import { resetEmail } from '../../utils/accountEmail'; import * as validator from '@packrat/validations'; import { User } from '../../drizzle/methods/User'; +import { responseHandler } from '../../helpers/responseHandler'; +import { type Context } from 'hono'; -/** - * Sends an email to the specified email address. - * @param {Object} req - The request object. - * @param {Object} res - The response object. - * @return {Promise} - A promise that resolves when the email is sent. - */ -// export const sentEmail = async (req, res) => { -// try { -// const { email } = req.body; +export const sentEmail = async (c: Context) => { + try { + const { email } = await c.req.json(); + console.log('email ', c.env.SEND_GRID_API_KEY) + const STMP_EMAIL = c.env.STMP_EMAIL; + const SEND_GRID_API_KEY = c.env.SEND_GRID_API_KEY; + const JWT_SECRET = c.env.JWT_SECRET; + const CLIENT_URL = c.env.CLIENT_URL; -// const user = await prisma.user.findUnique({ where: { email } }); -// const userWithMethods = User(user); -// if (!user) { -// throw new Error('User not found'); -// } -// const resetUrl = await userWithMethods.generateResetToken(); -// resetEmail(userWithMethods.email, resetUrl); -// res.status(200).send({ -// message: 'Reset Token has been sent successfully', -// status: 'success', -// statusCode: 200, -// }); -// } catch (err) { -// res.status(400).send({ message: err.message }); -// } -// }; + const userClass = new User(); + const user = await userClass.findUser({ email }); + if (!user) { + throw new Error('User not found'); + } + + const resetUrl = await userClass.generateResetToken( + JWT_SECRET, + CLIENT_URL, + user.id, + ); + await resetEmail(user.email, resetUrl, STMP_EMAIL, SEND_GRID_API_KEY); + c.set('data', { message: 'Reset Token has been sent successfully' }); + return await responseHandler(c); + } catch (error) { + c.set('error', error.message); + return await responseHandler(c); + } +}; export function sentEmailRoute() { return publicProcedure.input(validator.sentEmail).mutation(async (opts) => { diff --git a/server/src/controllers/user/userSignIn.ts b/server/src/controllers/user/userSignIn.ts index b73f93e63..9386d8c05 100644 --- a/server/src/controllers/user/userSignIn.ts +++ b/server/src/controllers/user/userSignIn.ts @@ -2,21 +2,17 @@ import { publicProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; import { User } from '../../drizzle/methods/User'; -// /** -// * Sign in a user. -// * @param {Object} req - The request object. -// * @param {Object} res - The response object. -// * @return {Object} The user object. -// */ -// export const userSignIn = async (req, res) => { -// const { email, password } = req.body; -// const user = await prisma.user.findByCredentials({ -// email, -// password, -// }); -// await User(user).generateAuthToken(); -// res.status(200).send({ user }); -// }; +export const userSignIn = async (c) => { + try { + const { email, password } = await c.req.json(); + const userClass = new User(); + const user = await userClass.findByCredentials(email, password); + await userClass.generateAuthToken(c.env.JWT_SECRET, user.id); + return c.json({ user }, 200); + } catch (error) { + return c.json({ error: `Failed to sign in: ${error.message}` }, 500); + } +}; export function userSignInRoute() { return publicProcedure.input(validator.userSignIn).mutation(async (opts) => { diff --git a/server/src/controllers/user/userSignUp.ts b/server/src/controllers/user/userSignUp.ts index fa166c5c3..5d0869d27 100644 --- a/server/src/controllers/user/userSignUp.ts +++ b/server/src/controllers/user/userSignUp.ts @@ -4,21 +4,39 @@ import { publicProcedure } from '../../trpc'; import * as validator from '@packrat/validations'; import { User } from '../../drizzle/methods/User'; import { hashPassword } from '../../utils/user'; -// export const userSignup = async (req: Request, res: Response) => { -// const { email } = req.body; -// console.log(`the request body received is ${JSON.stringify(req.body)}`); -// await userClass.alreadyLogin(email); -// const salt = await bcrypt.genSalt(parseInt(JWT_SECRET)); -// req.body.password = await bcrypt.hash(req.body.password, salt); -// const newUser = await userClass.create({ -// data: req.body, -// }); -// const userWithMethods = User(newUser); -// await userWithMethods.generateAuthToken(); -// sendWelcomeEmail(newUser.email, newUser.name); -// res.status(201).send({ user: newUser }); -// }; +export const userSignup = async (c) => { + try { + let { email, password, name, username } = await c.req.json(); + const userClass = new User(); + const userExists = await userClass.findUser({ email }); + if (userExists) { + throw new Error('Email already registered'); + } + + const STMP_EMAIL = c.env.STMP_EMAIL; + const SEND_GRID_API_KEY = c.env.SEND_GRID_API_KEY; + const JWT_SECRET = c.env.JWT_SECRET; + password = await hashPassword(JWT_SECRET, password); + const user = await userClass.create({ + email, + username, + password, + name, + }); + + await userClass.generateAuthToken(JWT_SECRET, user.id); + await sendWelcomeEmail( + user.email, + user.name, + STMP_EMAIL, + SEND_GRID_API_KEY, + ); + return c.json({ user }, 201); + } catch (error) { + return c.json({ error: `Failed to sign up: ${error.message}` }, 500); + } +}; export function signUpRoute() { return publicProcedure.input(validator.userSignUp).mutation(async (opts) => { diff --git a/server/src/controllers/weather/getWeather.ts b/server/src/controllers/weather/getWeather.ts index d4dd29bce..897045560 100644 --- a/server/src/controllers/weather/getWeather.ts +++ b/server/src/controllers/weather/getWeather.ts @@ -1,25 +1,21 @@ +import { type Context } from 'hono'; import { getWeatherService } from '../../services/weather/getWeatherService'; -import { RetrievingWeatherFromOpenWeatherError } from '../../helpers/errors'; -import { responseHandler } from '../../helpers/responseHandler'; import { publicProcedure } from '../../trpc'; import { z } from 'zod'; -// /** -// * Retrieves weather data from OpenWeather API based on latitude and longitude. -// * @param {Object} req - The request object. -// * @param {Object} res - The response object. -// * @return {Object} The weather data retrieved from OpenWeather API. -// */ -// export const getWeather = async (req, res, next) => { -// try { -// const response = await getWeatherService(req.query.lat, req.query.lon); -// res.locals.data = response.data; -// responseHandler(res); -// } catch (error) { -// // send back error message -// next(RetrievingWeatherFromOpenWeatherError); -// } -// }; +export const getWeather = async (c: Context) => { + try { + const { lat, lon } = await c.req.json(); + return await getWeatherService( + c.env.WEATHER_URL, + c.env.OPENWEATHER_KEY, + lat, + lon, + ); + } catch (error) { + return c.json({ error: `${error.message}` }, 500); + } +}; export function getWeatherRoute() { return publicProcedure diff --git a/server/src/drizzle/methods/User.ts b/server/src/drizzle/methods/User.ts index dadd38b7b..8b389ab12 100644 --- a/server/src/drizzle/methods/User.ts +++ b/server/src/drizzle/methods/User.ts @@ -256,7 +256,7 @@ export class User { } async findUnique(query: { - where: { email?: string; googleId?: string }; + where: { email?: string; googleId?: string; id?: string; token?: string }; with?: { favoriteDocuments?: boolean; id?: boolean; username?: boolean }; }) { try { @@ -267,6 +267,12 @@ export class User { if (query.where.googleId) { conditions.push(eq(UserTable.googleId, query.where.googleId)); } + if (query.where.id && query.where.token) { + conditions.push( + eq(UserTable.id, query.where.id), + eq(UserTable.token, query.where.token), + ); + } const user = await DbClient.instance .select() .from(UserTable) diff --git a/server/src/helpers/responseHandler.ts b/server/src/helpers/responseHandler.ts index 7be20bc46..f5088ad87 100644 --- a/server/src/helpers/responseHandler.ts +++ b/server/src/helpers/responseHandler.ts @@ -1,17 +1,21 @@ -import type express from 'express'; +// Assuming responseHandler is a function intended to set headers and send a response in Hono +import { type Context } from 'hono'; -export function responseHandler( - res: express.Response, +export async function responseHandler( + ctx: Context, message: string = 'Success', ) { - const data = res.locals?.data ?? { message: 'Success' }; + const data = ctx.get('data'); + const error = ctx.get('error'); - // Set the custom header - res.setHeader('X-Response-Message', message); + ctx.header('X-Response-Message', message); + ctx.header('Access-Control-Expose-Headers', 'X-Response-Message'); - res.setHeader('Access-Control-Expose-Headers', 'X-Response-Message'); + console.log('message', message, data, error); - console.log('message', message); - - return res.status(200).json(data); + if (error) { + return await ctx.json({ error }, 400); + } else { + return await ctx.json(data ?? { message: 'Success' }, 200); + } } diff --git a/server/src/helpers/tryCatchWrapper.ts b/server/src/helpers/tryCatchWrapper.ts index 4e5a32d98..7b2c8d7ce 100644 --- a/server/src/helpers/tryCatchWrapper.ts +++ b/server/src/helpers/tryCatchWrapper.ts @@ -3,9 +3,9 @@ import { type Context, type Next } from 'hono'; export function tryCatchWrapper(fn) { return async (ctx: Context, next: Next) => { try { - await fn(ctx, next); + return await fn(ctx, next); } catch (error: any) { - next(); + return ctx.json({ error: 'Internal Server Error' }, 500); } }; } diff --git a/server/src/index.ts b/server/src/index.ts index 4c5089ac7..31492c067 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1,24 +1,21 @@ import { Hono } from 'hono'; -import { cors } from 'hono/cors'; -import { logger } from 'hono/logger'; import { fetchHandler } from 'trpc-playground/handlers/fetch'; -import { CORS_METHODS } from './config'; -import { enforceHttps } from './middleware/enforceHttps'; -import { securityHeaders } from './middleware/securityHeaders'; -import { queue } from './queue'; -import router from './routes'; import { appRouter } from './routes/trpcRouter'; import { honoTRPCServer } from './trpc/server'; +import { cors } from 'hono/cors'; +import { securityHeaders } from './middleware/securityHeaders'; +import { enforceHttps } from './middleware/enforceHttps'; +import router from './routes'; +import { CORS_METHODS } from './config'; +import { httpDBContext } from './trpc/httpDBContext'; -export interface Bindings { +interface Bindings { [key: string]: any; DB: IDBDatabase; JWT_VERIFICATION_KEY: string; APP_URL: string; CORS_ORIGIN: string; MAPBOX_ACCESS_TOKEN: string; - readonly ETL_QUEUE: Queue; - readonly ETL_BUCKET: R2Bucket; } const TRPC_API_ENDPOINT = '/api/trpc'; @@ -52,7 +49,8 @@ app.use('*', async (c, next) => { }); // SETUP LOGGING -app.use('*', logger()); +// tRPC is already logging requests, but you can add your own middleware +// app.use('*', logger()); // SETUP TRPC SERVER app.use(`${TRPC_API_ENDPOINT}/*`, honoTRPCServer({ router: appRouter })); @@ -67,15 +65,8 @@ app.use(TRPC_PLAYGROUND_ENDPOINT, async (c, next) => { return handler(c.req.raw); }); -// SET UP HTTP ROUTES -app.route(`${HTTP_ENDPOINT}`, router); - -// SETUP CLOUDFLARE WORKER WITH EVENT HANDLERS -const worker = { - ...app, - fetch: app.fetch, - queue, -}; +// A middleware to initiate db connection and add it to the context +app.use(`${HTTP_ENDPOINT}/*`, httpDBContext); +app.route(`${HTTP_ENDPOINT}/`, router); -// EXPORT WORKER -export default worker; +export default app; diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts index f198076bb..68d91cc5b 100644 --- a/server/src/middleware/auth.ts +++ b/server/src/middleware/auth.ts @@ -1,47 +1,18 @@ -import jwt, { type JwtPayload } from 'jsonwebtoken'; -import { JWT_SECRET } from '../config'; -import { type Request, type Response, type NextFunction } from 'express'; -import { middleware } from '../trpc'; -import { TRPCError } from '@trpc/server'; -import { z, ZodError } from 'zod'; +import * as jwt from 'hono/jwt'; +import { ZodError } from 'zod'; import { TokenSchema } from './validators/authTokenValidator'; - -declare global { - namespace Express { - interface Request { - user: any; - token: string; - } - } -} - -// export const authMiddleware = middleware(async (opts) => { -// const ctx = opts.ctx; -// try { -// const token: any = ctx.input.header('Authorization')?.replace('Bearer ', ''); -// const decoded: any = jwt.verify(token, JWT_SECRET ?? ''); -// const user: any = await User.findOne({ -// id: decoded.id, -// token, -// }); -// if (!user) throw new Error(); -// ctx.set('token', token); -// ctx.set('user', user); -// return opts.next() // Call the next middleware or procedure -// } catch (err) { -// console.error(err); -// throw new TRPCError({ code: 'UNAUTHORIZED' }); -// } -// }); +import { type Context, type Next } from 'hono'; +import { User } from '../drizzle/methods/User'; /** * Extracts the token from the request header. - * @param {Request} req - The express request object. + * @param {Context} c - The Hono context object. * @returns {string} - The extracted token. * @throws {Error} If token is not found. */ -const extractToken = (req: Request): string => { - const token = req.header('Authorization')?.replace('Bearer ', ''); +const extractTokenHTTP = async (c: Context): Promise => { + const { authorization } = c.req.header(); + const token = authorization?.replace('Bearer ', ''); if (!token) throw new Error('Token missing from Authorization header.'); return token; }; @@ -52,9 +23,9 @@ const extractToken = (req: Request): string => { * @returns {JwtPayload} - The decoded JWT payload. * @throws {ZodError} If token structure is invalid. */ -const verifyToken = (token: string): JwtPayload => { - const decoded: JwtPayload = jwt.verify(token, JWT_SECRET ?? '') as JwtPayload; - const parsedToken = TokenSchema.parse(decoded); // Will throw if invalid +const verifyTokenHTTP = async (secret: string, token: string) => { + const decoded = await jwt.verify(token, secret ?? ''); + const parsedToken = TokenSchema.parse(decoded); return parsedToken; }; @@ -65,53 +36,51 @@ const verifyToken = (token: string): JwtPayload => { * @returns {Promise} - The user associated with the token. * @throws {Error} If user is not found. */ -// const findUser = async (decoded: JwtPayload, token: string): Promise => { -const findUser = async (decoded: JwtPayload, token: string): Promise => { - // const user: any = await prisma.user.findUnique({ - // where: { - // id: decoded.id, - // token, - // }, - // }); - const user = null; +const findUserHTTP = async (decoded, token: string): Promise => { + const userClass = new User(); + const user: any = await userClass.findUnique({ + where: { + id: decoded.id, + token, + }, + }); if (!user) throw new Error('User associated with this token not found.'); return user; }; /** - * Authenticates the user based on the provided token and adds the user information to the request object. - * @param {Request} req - The express request object. - * @param {Response} res - The express response object. - * @param {NextFunction} next - The express next function. + * Authenticates the user based on the provided token and adds the user information to the context. + * @param {Context} c - The Hono context object. + * @param {Next} next - The Hono next function. */ -const auth = async (req: Request, res: Response, next: NextFunction) => { +const authMiddlewareHTTP = async (c: Context, next: Next) => { try { - const token = extractToken(req); - const decoded = verifyToken(token); - const user = await findUser(decoded, token); - - req.token = token; - req.user = user; + const token = await extractTokenHTTP(c); + const decoded = verifyTokenHTTP(c.env.JWT_SECRET, token); + const user = await findUserHTTP(decoded, token); + c.set('token', token); + c.set('user', user); - next(); + await next(); } catch (err) { - handleError(err, res); + return await handleErrorHTTP(err, c); + // return c.json('error', err.message) } }; /** * Handles authentication errors. * @param {Error} err - The error object. - * @param {Response} res - The express response object. + * @param {Context} c - The Hono context object. */ -const handleError = (err: Error, res: Response) => { +const handleErrorHTTP = (err: Error, c: Context) => { if (err instanceof ZodError) { - console.error('Invalid token structure:', err.errors); - res.status(400).send({ error: 'Invalid token structure.' }); + console.error('Invalid token structure:', err.message); + return c.json({ error: 'Invalid token structure.' }, 400); } else { console.error(err.message); - res.status(401).send({ error: 'Not authorized to access this resource.' }); + return c.json({ error: 'Not authorized to access this resource.' }, 401); } }; -export default auth; +export default authMiddlewareHTTP; diff --git a/server/src/middleware/checkRole.ts b/server/src/middleware/checkRole.ts index b3609c0e5..079335140 100644 --- a/server/src/middleware/checkRole.ts +++ b/server/src/middleware/checkRole.ts @@ -1,34 +1,47 @@ -import { type Request, type Response, type NextFunction } from 'express'; +import type { Context, Next } from 'hono'; import { RoleSchema } from './validators/roleValidator'; import { ZodError } from 'zod'; -// import { type User } from '@prisma/client/edge'; + +// Extend the Context type to include the user property in the request and the next method. +// interface ExtendedContext extends Context { +// req: Context['req'] & { user?: { role: string } }; +// next: () => Next; +// } /** * Middleware to check if the user has a certain role. * @param {string[]} roles - The roles to check against. - * @returns {Function} - Express middleware function. + * @returns {Function} - Hono middleware function. */ const checkRole = (roles: string[]) => { - return (req: Request, res: Response, env: Env, next: NextFunction) => { - const user: any = req.user; - + return async (c: Context, next: Next) => { try { + const { user } = await c.req.json(); + + console.log('user', user.role, roles); + if (!user) { + throw new Error('User Data Not Provided'); + } + // Make sure all roles are valid. roles.forEach((role) => RoleSchema.parse(role)); // Check if user's role is in the allowed roles list. - if (!roles.includes(user.role)) { - return res.status(403).send({ error: 'Insufficient permissions' }); + if (!user || !roles.includes(user.role)) { + // Use the appropriate method to send a JSON response. + return c.json({ error: 'Insufficient permissions' }, 403); } - next(); + // Proceed to the next middleware or route handler. + await next(); } catch (err) { + console.log('error', err) if (err instanceof ZodError) { console.error('Invalid role provided:', err.errors); - res.status(400).send({ error: 'Invalid role provided.' }); + return c.json({ error: 'Invalid role provided.' }, 400); } else { console.error(err.message); - res.status(500).send({ error: 'Internal server error' }); + return c.json({ error: `Internal server error ${err.message}` }, 500); } } }; diff --git a/server/src/middleware/isAdmin.ts b/server/src/middleware/isAdmin.ts index b93fdf792..b8145d57f 100644 --- a/server/src/middleware/isAdmin.ts +++ b/server/src/middleware/isAdmin.ts @@ -1,20 +1,12 @@ -import { type NextFunction, type Request, type Response } from 'express'; - -/** - * Checks if the user making the request is an admin. - * - * @param {Request} req - The request object. - * @param {Response} res - The response object. - * @param {NextFunction} next - The next function to be called in the middleware chain. - * @return {void} This function does not return anything. - */ -export function isAdmin(req: Request, res: Response, next: NextFunction) { - // Your user object might be different. This is just a sample. - if (req.user && req.user.role === 'admin') { - next(); // pass control to the next handler +export function isAdmin(c) { + if (c.req.user && c.req.user.role === 'admin') { + c.next(); } else { - res.status(403).send({ - message: 'Admin access is required to perform this action', - }); + c.json( + { + message: 'Admin access is required to perform this action', + }, + 403, + ); } } diff --git a/server/src/middleware/validators/zodParser.ts b/server/src/middleware/validators/zodParser.ts index 86883df69..50e057c22 100644 --- a/server/src/middleware/validators/zodParser.ts +++ b/server/src/middleware/validators/zodParser.ts @@ -1,12 +1,27 @@ -import { type NextFunction } from 'express'; -import { type z } from 'zod'; +import type { Context, Hono, Next } from 'hono'; +import type { z, ZodSchema } from 'zod'; +import { responseHandler } from '../../helpers/responseHandler'; -type ZodParserFunction = ( - schema: z.ZodSchema, - input: any, - next: NextFunction, -) => any; -export const zodParser: ZodParserFunction = (schema, input, next) => { - schema.parse(input); - next(); +// Define the Zod parser function as middleware +export const zodParser = ( + schema: ZodSchema, + location: 'body' | 'query' | 'params', +) => { + return async (c: Context, next: Next) => { + try { + let input: any; + if (location === 'body') { + input = await c.req.json(); + } else if (location === 'query') { + input = c.req.query(); + } else if (location === 'params') { + input = c.req.param(); + } + schema.parse(input); + return await next(); + } catch (error) { + c.set('error', error.message); + return await responseHandler(c); + } + }; }; diff --git a/server/src/routes/favoriteRoutes.ts b/server/src/routes/favoriteRoutes.ts index 5f28fec29..25b137000 100644 --- a/server/src/routes/favoriteRoutes.ts +++ b/server/src/routes/favoriteRoutes.ts @@ -1,9 +1,9 @@ import { Hono } from 'hono'; import * as validator from '@packrat/validations'; import { - addToFavoriteRoute as addToFavorite, - getFavoritePacksByUserRoute as getFavoritePacksByUser, - getUserFavoritesRoute as getUserFavorites, + addToFavorite, + getFavoritePacksByUser, + getUserFavorites, } from '../controllers/favorite/index'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; import authTokenMiddleware from '../middleware/auth'; @@ -11,93 +11,24 @@ import checkRole from '../middleware/checkRole'; import { zodParser } from '../middleware/validators/zodParser'; const router = new Hono(); - -/** - * @swagger - * /favorite: - * post: - * summary: Add to favorite - * tags: [Favorite] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * packId: - * type: string - * userId: - * type: string - * responses: - * '200': - * description: Successful response adding to favorite - * '400': - * description: Invalid request parameters - * '500': - * description: Error adding to favorite - */ router.post( '/', - authTokenMiddleware as any, - ((req, res, next) => - zodParser(validator.addToFavorite, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.addToFavorite, 'body'), tryCatchWrapper(addToFavorite), ); -/** - * @swagger - * /favorite/user/{userId}: - * get: - * summary: Get favorites of a user - * tags: [Favorite] - * parameters: - * - in: path - * name: userId - * schema: - * type: string - * required: true - * description: ID of the user - * responses: - * '200': - * description: Successful response with user's favorites - * '400': - * description: Invalid request parameters - * '500': - * description: Error retrieving favorites - */ router.get( '/user/:userId', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getUserFavorites), ); -/** - * @swagger - * /favorite/user/{userId}/packs: - * get: - * summary: Get favorite packs of a user - * tags: [Favorite] - * parameters: - * - in: path - * name: userId - * schema: - * type: string - * required: true - * description: ID of the user - * responses: - * '200': - * description: Successful response with user's favorite packs - * '400': - * description: Invalid request parameters - * '500': - * description: Error retrieving favorite packs - */ router.get( '/user/:userId/packs', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getFavoritePacksByUser), ); diff --git a/server/src/routes/geoCodeRoutes.ts b/server/src/routes/geoCodeRoutes.ts index 5daf73ecd..8c535316a 100644 --- a/server/src/routes/geoCodeRoutes.ts +++ b/server/src/routes/geoCodeRoutes.ts @@ -1,5 +1,5 @@ import { Hono } from 'hono'; -import { getGeoCodeRoute as getGeoCode } from '../controllers/geoCode/index'; +import { getGeoCode } from '../controllers/geoCode/index'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; import authTokenMiddleware from '../middleware/auth'; import checkRole from '../middleware/checkRole'; @@ -8,8 +8,8 @@ const router = new Hono(); router.get( '/', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getGeoCode), ); diff --git a/server/src/routes/getParkRoutes.ts b/server/src/routes/getParkRoutes.ts index ab292ee9d..ea09f76bc 100644 --- a/server/src/routes/getParkRoutes.ts +++ b/server/src/routes/getParkRoutes.ts @@ -1,6 +1,6 @@ import { Hono } from 'hono'; import * as validator from '@packrat/validations'; -import { getParksRoute as getParks } from '../controllers/getParks/index'; +import { getParks } from '../controllers/getParks/index'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; import authTokenMiddleware from '../middleware/auth'; import checkRole from '../middleware/checkRole'; @@ -10,9 +10,9 @@ const router = new Hono(); router.get( '/', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - ((req, res, next) => zodParser(validator.getParks, req.body, next)) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + zodParser(validator.getParks, 'body'), tryCatchWrapper(getParks), ); diff --git a/server/src/routes/getTrailRoutes.ts b/server/src/routes/getTrailRoutes.ts index a765117d6..fb40dbf5b 100644 --- a/server/src/routes/getTrailRoutes.ts +++ b/server/src/routes/getTrailRoutes.ts @@ -1,6 +1,6 @@ import { Hono } from 'hono'; import * as validator from '@packrat/validations'; -import { getTrailsRoute as getTrails } from '../controllers/getTrail/index'; +import { getTrails } from '../controllers/getTrail/index'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; import authTokenMiddleware from '../middleware/auth'; import checkRole from '../middleware/checkRole'; @@ -10,9 +10,9 @@ const router = new Hono(); router.post( '/', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - ((req, res, next) => zodParser(validator.getTrails, req.body, next)) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + zodParser(validator.getTrails, 'body'), tryCatchWrapper(getTrails), ); diff --git a/server/src/routes/healthRoutes.ts b/server/src/routes/healthRoutes.ts index b48bea5d0..34f312e5c 100644 --- a/server/src/routes/healthRoutes.ts +++ b/server/src/routes/healthRoutes.ts @@ -2,28 +2,6 @@ import { Hono } from 'hono'; const router = new Hono(); -/** - * @swagger - * tags: - * name: Health - * description: Health routes - */ - -/** - * @swagger - * /health: - * get: - * tags: - * - Health - * summary: Get health status - * responses: - * 200: - * description: Successful response - * content: - * application/json: - * schema: - * type: object - */ router.get('/', (c) => { return c.json({ status: 'ok' }); }); diff --git a/server/src/routes/index.ts b/server/src/routes/index.ts index a14675011..38944ac30 100644 --- a/server/src/routes/index.ts +++ b/server/src/routes/index.ts @@ -1,22 +1,21 @@ -// import express, { type Request, type Response } from 'express'; // import path from 'path'; // import csrf from 'csurf'; -// import packRoutes from './packRoutes'; -// import itemRoutes from './itemRoutes'; -// import tripRoutes from './tripRoutes'; -// import weatherRoutes from './weatherRoutes'; -// import geoCodeRoutes from './geoCodeRoutes'; -// import getParkRoutes from './getParkRoutes'; -// import getTrailRoutes from './getTrailRoutes'; -// import osmRoutes from './osmRoutes'; -// import passwordResetRoutes from './passwordResetRoutes'; -// import openAiRoutes from './openAiRoutes'; -// // import templateRoutes from './templateRoutes'; -// import favoriteRouters from './favoriteRoutes'; -// import userRoutes from './userRoutes'; +import packRoutes from './packRoutes'; +import itemRoutes from './itemRoutes'; +import tripRoutes from './tripRoutes'; +import weatherRoutes from './weatherRoutes'; +import geoCodeRoutes from './geoCodeRoutes'; +import getParkRoutes from './getParkRoutes'; +import getTrailRoutes from './getTrailRoutes'; +import osmRoutes from './osmRoutes'; +import passwordResetRoutes from './passwordResetRoutes'; +import openAiRoutes from './openAiRoutes'; +import templateRoutes from './templateRoutes'; +import favoriteRouters from './favoriteRoutes'; +import userRoutes from './userRoutes'; import mapPreviewRouter from './mapPreviewRouter'; import healthRoutes from './healthRoutes'; -import { type Context, Hono, type Next } from 'hono'; +import { Hono } from 'hono'; const router = new Hono(); @@ -45,45 +44,44 @@ const router = new Hono(); // } // use routes -// router.use('/user', userRoutes); -// router.use('/pack', packRoutes); -// router.use('/item', itemRoutes); -// router.use('/trip', tripRoutes); -// router.use('/weather', weatherRoutes); -// router.use('/geocode', geoCodeRoutes); -// router.use('/getparks', getParkRoutes); -// router.use('/gettrails', getTrailRoutes); -// router.use('/osm', osmRoutes); -// router.use('/password-reset', passwordResetRoutes); -// router.use('/openai', openAiRoutes); -// router.use('/template', templateRoutes); -// router.use('/favorite', favoriteRouters); -// router.use('/openai', openAiRoutes); +router.route('/user', userRoutes); +router.route('/pack', packRoutes); +router.route('/item', itemRoutes); +router.route('/trip', tripRoutes); +router.route('/weather', weatherRoutes); +router.route('/geocode', geoCodeRoutes); +router.route('/getparks', getParkRoutes); +router.route('/gettrails', getTrailRoutes); +router.route('/osm', osmRoutes); +router.route('/password-reset', passwordResetRoutes); +router.route('/openai', openAiRoutes); +router.route('/template', templateRoutes); +router.route('/favorite', favoriteRouters); router.route('/mapPreview', mapPreviewRouter); router.route('/health', healthRoutes); const helloRouter = new Hono(); -helloRouter.get('/', (c: Context, next: Next) => { +helloRouter.get('/', (c) => { return c.text('Hello, world!'); }); router.route('/hello', helloRouter); // Also listen to /api for backwards compatibility -// router.use('/api/user', userRoutes); -// router.use('/api/pack', packRoutes); -// router.use('/api/item', itemRoutes); -// router.use('/api/trip', tripRoutes); -// router.use('/api/weather', weatherRoutes); -// router.use('/api/geocode', geoCodeRoutes); -// router.use('/api/getparks', getParkRoutes); -// router.use('/api/gettrails', getTrailRoutes); -// router.use('/api/osm', osmRoutes); -// router.use('/api/password-reset', passwordResetRoutes); -// router.use('/api/openai', openAiRoutes); -// router.use('/api/template', templateRoutes); -// router.use('/api/favorite', favoriteRouters); -// router.use('/api/openai', openAiRoutes); -// router.use('/api/mapPreview', mapPreviewRouter); +router.route('/api/user', userRoutes); +router.route('/api/pack', packRoutes); +router.route('/api/item', itemRoutes); +router.route('/api/trip', tripRoutes); +router.route('/api/weather', weatherRoutes); +router.route('/api/geocode', geoCodeRoutes); +router.route('/api/getparks', getParkRoutes); +router.route('/api/gettrails', getTrailRoutes); +router.route('/api/osm', osmRoutes); +router.route('/api/password-reset', passwordResetRoutes); +router.route('/api/openai', openAiRoutes); +router.route('/api/template', templateRoutes); +router.route('/api/favorite', favoriteRouters); +router.route('/api/openai', openAiRoutes); +router.route('/api/mapPreview', mapPreviewRouter); // // Static routes for serving the React Native Web app // if (process.env.NODE_ENV === 'production') { diff --git a/server/src/routes/itemRoutes.ts b/server/src/routes/itemRoutes.ts index 1e7e86116..1cddf04c3 100644 --- a/server/src/routes/itemRoutes.ts +++ b/server/src/routes/itemRoutes.ts @@ -1,16 +1,16 @@ import { Hono } from 'hono'; import { - getItemsRoute as getItems, - getItemByIdRoute as getItemById, - addItemRoute as addItem, - addItemGlobalRoute as addItemGlobal, - editItemRoute as editItem, - deleteItemRoute as deleteItem, - searchItemsByNameRoute as searchItemsByName, - getItemsGloballyRoute as getItemsGlobally, - addGlobalItemToPackRoute as addGlobalItemToPack, - editGlobalItemAsDuplicateRoute as editGlobalItemAsDuplicate, - deleteGlobalItemRoute as deleteGlobalItem, + getItems, + getItemById, + addItem, + addItemGlobal, + editItem, + deleteItem, + searchItemsByName, + getItemsGlobally, + addGlobalItemToPack, + editGlobalItemAsDuplicate, + deleteGlobalItem, } from '../controllers/item/index'; import * as validator from '@packrat/validations'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; @@ -20,309 +20,84 @@ import { zodParser } from '../middleware/validators/zodParser'; const router = new Hono(); -/** - * @swagger - * tags: - * name: Items - * description: item routes - */ - -/** - * @swagger - * /item/packItems/{packId}: - * get: - * tags: - * - Items - * summary: Get items by pack ID - * parameters: - * - in: path - * name: packId - * required: true - * schema: - * type: string - * responses: - * 200: - * description: Successful response - */ router.get( - '/packItems/:packId', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.getItems, req.body, next)) as any, + '/packItems/:packId?', + authTokenMiddleware, + zodParser(validator.getItems, 'params'), tryCatchWrapper(getItems), ); -/** - * @swagger - * /item/i/{packId}: - * get: - * tags: - * - Items - * summary: Get item by item ID - * parameters: - * - in: path - * name: packId - * required: true - * schema: - * type: string - * responses: - * 200: - * description: Successful response - */ router.get( - '/i/:packId', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.getItemById, req.body, next)) as any, + '/i/:id', + authTokenMiddleware, + zodParser(validator.getItemById, 'params'), tryCatchWrapper(getItemById), ); -/** - * @swagger - * /item/search: - * get: - * tags: - * - Items - * summary: Search items by name - * parameters: - * - in: query - * name: name - * schema: - * type: string - * description: Text to search for items by name - * responses: - * 200: - * description: Successful response - */ router.get( '/search', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(searchItemsByName), ); -/** - * @swagger - * /item/: - * post: - * tags: - * - Items - * summary: Add a new item - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * name: - * type: string - * weight: - * type: number - * quantity: - * type: number - * unit: - * type: string - * packId: - * type: string - * responses: - * 200: - * description: Successful response - */ router.post( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.addItem, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.addItem, 'body'), tryCatchWrapper(addItem), ); -/** - * @swagger - * /item/: - * put: - * tags: - * - Items - * summary: Edit an existing item - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * id: - * type: string - * name: - * type: string - * weight: - * type: number - * quantity: - * type: number - * unit: - * type: string - * responses: - * 200: - * description: Successful response - */ router.put( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.editItem, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.editItem, 'body'), tryCatchWrapper(editItem), ); -/** - * @swagger - * /item/: - * delete: - * tags: - * - Items - * summary: Delete an item by ID - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * id: - * type: string - * responses: - * 200: - * description: Successful response - */ router.delete( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.deleteItem, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.deleteItem, 'body'), tryCatchWrapper(deleteItem), ); -/** - * @swagger - * /item/: - * post: - * tags: - * - Items - * summary: Add a item to Global items list - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * name: - * type: string - * weight: - * type: number - * quantity: - * type: number - * unit: - * type: string - * type: - * type: string - * responses: - * 200: - * description: Successful response - */ router.post( '/global', - authTokenMiddleware as any, - ((req, res, next) => - zodParser(validator.addItemGlobal, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.addItemGlobal, 'body'), tryCatchWrapper(addItemGlobal), ); -/** - * @swagger - * /item/: - * get: - * tags: - * - Items - * summary: get a item to Global items list - * requestBody: - * required: false - * responses: - * 200: - * description: Successful response - */ router.get( '/global', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - ((req, res, next) => - zodParser(validator.getItemsGlobally, req.body, next)) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + zodParser(validator.getItemsGlobally, 'body'), tryCatchWrapper(getItemsGlobally), ); -/** - * @swagger - * /item/: - * post: - * tags: - * - Items - * summary: add a item to Pack - * requestBody: - * required: false - * responses: - * 200: - * description: Successful response - */ router.post( - '/global/select/:packId', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - ((req, res, next) => - zodParser(validator.addGlobalItemToPack, req.body, next)) as any, + '/global/select/', + authTokenMiddleware, + checkRole(['user', 'admin']), + zodParser(validator.addGlobalItemToPack, 'body'), tryCatchWrapper(addGlobalItemToPack), ); -/** - * @swagger - * /item/: - * post: - * tags: - * - Items - * summary: edit a item in Pack - * requestBody: - * required: false - * responses: - * 200: - * description: Successful response - */ + router.put( '/global/:itemId', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - ((req, res, next) => - zodParser(validator.editGlobalItemAsDuplicate, req.body, next)) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + zodParser(validator.editGlobalItemAsDuplicate, 'params'), tryCatchWrapper(editGlobalItemAsDuplicate), ); -/** - * @swagger - * /item/: - * delete: - * tags: - * - Items - * summary: Delete an item by ID - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * id: - * type: string - * responses: - * 200: - * description: Successful response - */ router.delete( '/global/:itemId', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - ((req, res, next) => - zodParser(validator.deleteGlobalItem, req.body, next)) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + zodParser(validator.deleteGlobalItem, 'params'), tryCatchWrapper(deleteGlobalItem), ); diff --git a/server/src/routes/mapPreviewRouter.ts b/server/src/routes/mapPreviewRouter.ts index f37a52de1..565ecfe61 100644 --- a/server/src/routes/mapPreviewRouter.ts +++ b/server/src/routes/mapPreviewRouter.ts @@ -6,35 +6,6 @@ import checkRole from '../middleware/checkRole'; const router = new Hono(); -/** - * @swagger - * /mapPreview/{mapQuery}: - * get: - * summary: get static image map preview - * tags: - * - Map image preview - * parameters: - * - in: path - * name: mapQuery - * schema: - * type: string - * required: true - * description: mapQuery is anything that comes after "https://api.mapbox.com/styles/v1/mapbox/streets-v12/static/" excluding access_token query param - * responses: - * 200: - * content: - * image/png: - * schema: - * type: string - * format: binary - * 500: - * description: Error getting map preview - */ -router.get( - '/*', - authTokenMiddleware as any, - tryCatchWrapper(getMapPreview), - // getMapPreview, -); +router.get('/*', authTokenMiddleware, tryCatchWrapper(getMapPreview)); export default router; diff --git a/server/src/routes/openAiRoutes.ts b/server/src/routes/openAiRoutes.ts index aa633c6c6..fe4991755 100644 --- a/server/src/routes/openAiRoutes.ts +++ b/server/src/routes/openAiRoutes.ts @@ -1,8 +1,9 @@ import { Hono } from 'hono'; import * as validator from '@packrat/validations'; import { - getAIResponseRoute as getAIResponse, - getUserChatsRoute as getUserChats, + getAIResponse, + getUserChats, + getAISuggestions, } from '../controllers/openAi/index'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; import authTokenMiddleware from '../middleware/auth'; @@ -11,66 +12,28 @@ import { zodParser } from '../middleware/validators/zodParser'; const router = new Hono(); -/** - * @swagger - * /openai/ai-response: - * post: - * summary: Generate AI response based on user input and conversation history - * tags: [AI] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * userId: - * type: string - * description: The user's ID. - * conversationId: - * type: string - * description: The conversation's ID. - * userInput: - *authTokenMiddleware as any,as any,e: string - * description: The user's input message. - * example: - * userId: "user1" - * conversationId: "conversation1" - * userInput: "Hello, AI!" - * responses: - * 200: - * description: The AI's response message - * content: - * application/json: - * schema: - * type: object - * properties: - * aiResponse: - * type: string - * description: The AI's response message. - * conversationHistory: - * type: string - * description: The complete conversation history, including the new messages. - * example: - * aiResponse: "Hello, user!" - * conversationHistory: "User: Hello, AI!\nAI: Hello, user!" - */ router.post( '/ai-response', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - ((req, res, next) => - zodParser(validator.getAIResponse, req.body, next)) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + zodParser(validator.getAIResponse, 'body'), tryCatchWrapper(getAIResponse), ); router.get( '/user-chats/:userId', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - ((req, res, next) => - zodParser(validator.getUserChats, req.body, next)) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + zodParser(validator.getUserChats, 'body'), tryCatchWrapper(getUserChats), ); +router.post( + '/ai-suggestions', + authTokenMiddleware, + checkRole(['user', 'admin']), + zodParser(validator.getAISuggestions, 'body'), + tryCatchWrapper(getAISuggestions), +); + export default router; diff --git a/server/src/routes/osmRoutes.ts b/server/src/routes/osmRoutes.ts index 7d3057226..5cd0b5a5a 100644 --- a/server/src/routes/osmRoutes.ts +++ b/server/src/routes/osmRoutes.ts @@ -1,13 +1,12 @@ import { Hono } from 'hono'; import { - getDestinationRoute as getDestination, - getOsmRoute as getOsm, - getParksOSMRoute as getParksOSM, - getPhotonResultsRoute as getPhotonResults, - getTrailsOSMRoute as getTrailsOSM, - postSingleGeoJSONRoute as postSingleGeoJSON, - getPhotonDetailsRoute as getPhotonDetails, - // getEnhancedPhotonDetails, + getDestination, + getOsm, + getParksOSM, + getPhotonResults, + getTrailsOSM, + postSingleGeoJSON, + getPhotonDetails, } from '../controllers/getOsm/index'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; import authTokenMiddleware from '../middleware/auth'; @@ -15,250 +14,53 @@ import checkRole from '../middleware/checkRole'; const router = new Hono(); -/** - * @swagger - * tags: - * name: OSM - * description: OSM routes - */ - -/** - * @swagger - * /osm/photon/search: - * get: - * summary: Get Photon search results - * tags: [OSM] - * parameters: - * - in: query - * name: searchString - * schema: - * type: string - * required: true - * description: The search string for Photon API - * responses: - * '200': - * description: Successful response with Photon search results - * '400': - * description: Invalid request parameters - * '500': - * description: Error retrieving Photon results - */ router.get( '/photon/search', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getPhotonResults), ); -/** - * @swagger - * /osm/trails: - * get: - * summary: Get Trails OSM results - * tags: [OSM] - * parameters: - * - in: query - * name: lat - * required: false - * schema: - * type: number - * - in: query - * name: lon - * required: false - * schema: - * type: number - * - in: query - * name: radius - * required: false - * schema: - * type: number - * responses: - * 200: - * description: Successful response with Trails OSM results - * 400: - * description: Invalid request parameters - * 500: - * description: Error retrieving Trails OSM results - */ router.get( '/trails', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getTrailsOSM), ); -/** - * @swagger - * /osm/parks: - * get: - * summary: Get Parks OSM results - * tags: [OSM] - * parameters: - * - in: query - * name: lat - * schema: - * type: number - * required: false - * - in: query - * name: lon - * schema: - * type: number - * required: false - * - in: query - * name: radius - * schema: - * type: number - * required: false - * responses: - * '200': - * description: Successful response with Parks OSM results - * '400': - * description: Invalid request parameters - * '500': - * description: Error retrieving Parks OSM results - */ router.get( '/parks', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getParksOSM), ); -/** - * @swagger - * /osm: - * post: - * summary: Get OSM data - * tags: [OSM] - * requestBody: - * required: true - * content: - * text/plain: - * schema: - * type: object - * properties: - * activityType: - * type: string - * startPoint: - * type: object - * properties: - * latitude: - * type: number - * longitude: - * type: number - * endPoint: - * type: object - * properties: - * latitude: - * type: number - * longitude: - * type: number - * responses: - * '200': - * description: Successful response with OSM data - * '400': - * description: Invalid request parameters - * '500': - * description: Error retrieving Overpass Data - */ router.post( '/osm', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getOsm), ); -/** - * @swagger - * /process/geojson: - * post: - * summary: Post a single GeoJSON object - * tags: [OSM] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * geojson: - * type: object - * responses: - * '201': - * description: Successfully created new instance - * '400': - * description: Invalid or missing geoJSON - * '500': - * description: Error processing request - */ router.post( '/process/geojson', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(postSingleGeoJSON), ); -/** - * @swagger - * /destination/{id}: - * get: - * summary: Get a single destination by ID - * tags: [OSM] - * parameters: - * - in: path - * name: id - * schema: - * type: string - * required: true - * description: The id of the destination - * responses: - * '200': - * description: Successfully retrieved destination - * '404': - * description: No destination found with provided ID - * '500': - * description: Error retrieving destination - */ router.get( '/destination/:id', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getDestination), ); -/** - * @swagger - * /photonDetails/:type/:id: - * get: - * summary: Get Photon details for a specific result - * tags: [OSM] - * parameters: - * - in: path - * name: type - * schema: - * type: string - * required: true - * description: The type of the Photon result - * - in: path - * name: id - * schema: - * type: string - * required: true - * description: The id of the Photon result - * responses: - * '200': - * description: Successful response with Photon details - * '400': - * description: Invalid request parameters - * '500': - * description: Error retrieving Photon details - */ router.get( '/photonDetails/:type/:id', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getPhotonDetails), ); -// router.get("/photonDetails/:type/:id", getEnhancedPhotonDetails) export default router; diff --git a/server/src/routes/packRoutes.ts b/server/src/routes/packRoutes.ts index a2e1eeaea..fe33c4b29 100644 --- a/server/src/routes/packRoutes.ts +++ b/server/src/routes/packRoutes.ts @@ -1,13 +1,13 @@ import { Hono } from 'hono'; import { - getPacksRoute as getPacks, - getPackByIdRoute as getPackById, - addPackRoute as addPack, - editPackRoute as editPack, - deletePackRoute as deletePack, - getPublicPacksRoute as getPublicPacks, - scorePackRoute as scorePack, - duplicatePublicPackRoute as duplicatePublicPack, + getPacks, + getPackById, + addPack, + editPack, + deletePack, + getPublicPacks, + scorePack, + duplicatePublicPack, } from '../controllers/pack/index'; import * as validator from '@packrat/validations'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; @@ -17,245 +17,60 @@ import { zodParser } from '../middleware/validators/zodParser'; const router = new Hono(); -/** - * @swagger - * tags: - * name: Packs - * description: Pack routes - */ - -/** - * @swagger - * /pack: - * get: - * summary: Get public packs - * tags: [Packs] - * responses: - * '200': - * description: Successful response with public packs - * '500': - * description: Error retrieving public packs - */ router.get( '/', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getPublicPacks), ); -/** - * @swagger - * /pack/{ownerId}: - * get: - * summary: Get packs by owner ID - * tags: [Packs] - * parameters: - * - in: path - * name: ownerId - * schema: - * type: string - * required: true - * description: The ID of the owner - * responses: - * '200': - * description: Successful response with packs by owner ID - * '400': - * description: Invalid request parameters - * '500': - * description: Error retrieving packs by owner ID - */ router.get( '/:ownerId', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - ((req, res, next) => zodParser(validator.getPacks, req.params, next)) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + zodParser(validator.getPacks, 'params'), tryCatchWrapper(getPacks), ); -/** - * @swagger - * /pack/p/{packId}: - * get: - * summary: Get pack by ID - * tags: [Packs] - * parameters: - * - in: path - * name: packId - * schema: - * type: string - * required: true - * description: The ID of the pack - * responses: - * '200': - * description: Successful response with pack by ID - * '400': - * description: Invalid request parameters - * '500': - * description: Error retrieving pack by ID - */ router.get( '/p/:packId', - authTokenMiddleware as any, - ((req, res, next) => - zodParser(validator.getPackById, req.params, next)) as any, + authTokenMiddleware, + zodParser(validator.getPackById, 'params'), tryCatchWrapper(getPackById), ); -/** - * @swagger - * /pack/score/{packId}: - * put: - * summary: Score a pack - * tags: [Packs] - * parameters: - * - in: path - * name: packId - * schema: - * type: string - * required: true - * description: The ID of the pack - * responses: - * '200': - * description: Successful response after scoring the pack - * '400': - * description: Invalid request parameters - * '500': - * description: Error scoring the pack - */ router.put( '/score/:packId', - authTokenMiddleware as any, - ((req, res, next) => - zodParser(validator.getPackById, req.params, next)) as any, + authTokenMiddleware, + zodParser(validator.getPackById, 'params'), tryCatchWrapper(scorePack), ); -/** - * @swagger - * /pack: - * post: - * summary: Add a pack - * tags: [Packs] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * name: - * type: string - * owner_id: - * type: string - * is_public: - * type: boolean - * responses: - * '200': - * description: Successful response after adding the pack - * '400': - * description: Invalid request parameters - * '500': - * description: Error adding the pack - */ router.post( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.addPack, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.addPack, 'body'), tryCatchWrapper(addPack), ); -/** - * @swagger - * /pack: - * put: - * summary: Edit a pack - * tags: [Packs] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * id: - * type: string - * name: - * type: string - * is_public: - * type: boolean - * responses: - * '200': - * description: Successful response after editing the pack - * '400': - * description: Invalid request parameters - * '500': - * description: Error editing the pack - */ router.put( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.editPack, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.editPack, 'body'), tryCatchWrapper(editPack), ); -/** - * @swagger - * /pack: - * delete: - * summary: Delete a pack - * tags: [Packs] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * packId: - * type: string - * responses: - * '200': - * description: Successful response after deleting the pack - * '400': - * description: Invalid request parameters - * '500': - * description: Error deleting the pack - */ router.delete( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.deletePack, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.deletePack, 'body'), tryCatchWrapper(deletePack), ); -/** - * @swagger - * /pack: - * post: - * summary: Duplicate a public pack - * tags: [Pack] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * packId: - * type: string - * responses: - * '200': - * description: Successful response after duplicating the pack - * '400': - * description: Invalid request parameters - * '500': - * description: Error duplicating the pack - */ router.post( '/duplicate', - authTokenMiddleware as any, - ((req, res, next) => - zodParser(validator.duplicatePublicPack, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.duplicatePublicPack, 'body'), tryCatchWrapper(duplicatePublicPack), ); diff --git a/server/src/routes/passwordResetRoutes.ts b/server/src/routes/passwordResetRoutes.ts index e3bd3a899..bacbcc40c 100644 --- a/server/src/routes/passwordResetRoutes.ts +++ b/server/src/routes/passwordResetRoutes.ts @@ -1,7 +1,7 @@ import { Hono } from 'hono'; import { - requestPasswordResetEmailAndTokenRoute as requestPasswordResetEmailAndToken, - handlePasswordResetRoute as handlePasswordReset, + requestPasswordResetEmailAndToken, + handlePasswordReset, } from '../controllers/passwordReset/index'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; diff --git a/server/src/routes/templateRoutes.ts b/server/src/routes/templateRoutes.ts index 830dffc2d..6abe6a224 100644 --- a/server/src/routes/templateRoutes.ts +++ b/server/src/routes/templateRoutes.ts @@ -1,186 +1,53 @@ import { Hono } from 'hono'; import { - getTemplatesRoute as getTemplates, - getTemplateByIdRoute as getTemplateById, - addTemplateRoute as addTemplate, - editTemplateRoute as editTemplate, - deleteTemplateRoute as deleteTemplate, + getTemplates, + getTemplateById, + addTemplate, + editTemplate, + deleteTemplate, } from '../controllers/template/index'; -import { isAdmin } from '../middleware/isAdmin'; // Assuming this is your middleware file +import { isAdmin } from '../middleware/isAdmin'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; import authTokenMiddleware from '../middleware/auth'; import checkRole from '../middleware/checkRole'; -// import * as validator from "@packrat/validations"; - -// TODO - add validators, this is just a placeholder -// REMOVED THIS SINCE VALIDATION IS NOT REALLY DONE HERE -// const validator = { -// getTemplateById: (req,res,next) => next(), -// addTemplate: (req,res,next) => next(), -// editTemplate: (req,res,next) => next(), -// deleteTemplate: (req,res,next) => next(), -// }; - const router = new Hono(); -/** - * @swagger - * tags: - * name: Templates - * description: Template routes - */ - -/** - * @swagger - * /template: - * get: - * summary: Get all templates - * tags: [Templates] - * responses: - * '200': - * description: Successful response with all templates - * '500': - * description: Error retrieving templates - */ router.get( '/', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getTemplates), ); -/** - * @swagger - * /template/{templateId}: - * get: - * summary: Get template by ID - * tags: [Templates] - * parameters: - * - in: path - * name: templateId - * schema: - * type: string - * required: true - * description: The ID of the template - * responses: - * '200': - * description: Successful response with template by ID - * '400': - * description: Invalid request parameters - * '500': - * description: Error retrieving template by ID - */ router.get( '/:templateId', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getTemplateById), ); -/** - * @swagger - * /template: - * post: - * summary: Add a template - * tags: [Templates] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * type: - * type: string - * templateId: - * type: string - * isGlobalTemplate: - * type: boolean - * createdBy: - * type: string - * responses: - * '200': - * description: Successful response after adding the template - * '400': - * description: Invalid request parameters - * '500': - * description: Error adding the template - */ router.post( '/', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - isAdmin as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + isAdmin, tryCatchWrapper(addTemplate), ); -/** - * @swagger - * /template/{templateId}: - * put: - * summary: Edit a template - * tags: [Templates] - * parameters: - * - in: path - * name: templateId - * schema: - * type: string - * required: true - * description: The ID of the template - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * type: - * type: string - * isGlobalTemplate: - * type: boolean - * responses: - * '200': - * description: Successful response after editing the template - * '400': - * description: Invalid request parameters - * '500': - * description: Error editing the template - */ router.put( '/:templateId', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - isAdmin as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + isAdmin, tryCatchWrapper(editTemplate), ); -/** - * @swagger - * /template/{templateId}: - * delete: - * summary: Delete a template - * tags: [Templates] - * parameters: - * - in: path - * name: templateId - * schema: - * type: string - * required: true - * description: The ID of the template - * responses: - * '200': - * description: Successful response after deleting the template - * '400': - * description: Invalid request parameters - * '500': - * description: Error deleting the template - */ router.delete( '/:templateId', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, - isAdmin as any, + authTokenMiddleware, + checkRole(['user', 'admin']), + isAdmin, tryCatchWrapper(deleteTemplate), ); diff --git a/server/src/routes/tripRoutes.ts b/server/src/routes/tripRoutes.ts index 804ae707f..fcde455b4 100644 --- a/server/src/routes/tripRoutes.ts +++ b/server/src/routes/tripRoutes.ts @@ -1,11 +1,11 @@ import { Hono } from 'hono'; import { - getPublicTripsRoute as getPublicTrips, - getTripsRoute as getTrips, - getTripByIdRoute as getTripById, - addTripRoute as addTrip, - editTripRoute as editTrip, - deleteTripRoute as deleteTrip, + getPublicTrips, + getTrips, + getTripById, + addTrip, + editTrip, + deleteTrip, } from '../controllers/trip/index'; import * as validator from '@packrat/validations'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; @@ -15,204 +15,45 @@ import { zodParser } from '../middleware/validators/zodParser'; const router = new Hono(); -/** - * @swagger - * tags: - * name: Trips - * description: Trip routes - */ - -/** - * @swagger - * /trip: - * get: - * tags: - * - Trips - * summary: Get public trips - * responses: - * 200: - * description: Successful response - */ router.get( '/', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getPublicTrips), ); -/** - * @swagger - * /trip/{ownerId}: - * get: - * tags: - * - Trips - * summary: Get trips by owner ID - * parameters: - * - in: path - * name: ownerId - * required: true - * schema: - * type: string - * responses: - * 200: - * description: Successful response - */ router.get( - '/:ownerId', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.getTrips, req.params, next)) as any, + '/:ownerId?', + authTokenMiddleware, + zodParser(validator.getTrips, 'params'), tryCatchWrapper(getTrips), ); -/** - * @swagger - * /trip/t/{tripId}: - * get: - * tags: - * - Trips - * summary: Get trip by trip ID - * parameters: - * - in: path - * name: tripId - * required: true - * schema: - * type: string - * responses: - * 200: - * description: Successful response - */ router.get( '/t/:tripId', - authTokenMiddleware as any, - ((req, res, next) => - zodParser(validator.getTripById, req.params, next)) as any, + authTokenMiddleware, + zodParser(validator.getTripById, 'params'), tryCatchWrapper(getTripById), ); -/** - * @swagger - * /trip: - * post: - * tags: - * - Trips - * summary: Add a new trip - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * name: - * type: string - * description: - * type: string - * duration: - * type: string - * weather: - * type: string - * start_date: - * type: string - * end_date: - * type: string - * destination: - * type: string - * trail: - * type: string - * owner_id: - * type: string - * packs: - * type: array - * items: - * type: string - * is_public: - * type: boolean - * responses: - * 200: - * description: Successful response - */ router.post( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.addTrip, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.addTrip, 'body'), tryCatchWrapper(addTrip), ); -/** - * @swagger - * /trip: - * put: - * tags: - * - Trips - * summary: Edit an existing trip - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * id: - * type: string - * name: - * type: string - * description: - * type: string - * duration: - * type: string - * weather: - * type: string - * start_date: - * type: string - * end_date: - * type: string - * destination: - * type: string - * trail: - * type: string - * owner_id: - * type: string - * packs: - * type: array - * items: - * type: string - * is_public: - * type: boolean - * responses: - * 200: - * description: Successful response - */ router.put( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.editTrip, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.editTrip, 'body'), tryCatchWrapper(editTrip), ); -/** - * @swagger - * /trip: - * delete: - * tags: - * - Trips - * summary: Delete a trip by ID - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * tripId: - * type: string - * responses: - * 200: - * description: Successful response - */ router.delete( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.deleteTrip, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.deleteTrip, 'body'), tryCatchWrapper(deleteTrip), ); diff --git a/server/src/routes/userRoutes.ts b/server/src/routes/userRoutes.ts index 7c6700801..ae8e8a441 100644 --- a/server/src/routes/userRoutes.ts +++ b/server/src/routes/userRoutes.ts @@ -1,26 +1,24 @@ import { Hono } from 'hono'; import { - getUsersRoute as getUsers, - getUserByIdRoute as getUserById, - // addUserRoute as , - editUserRoute as editUser, - deleteUserRoute as deleteUser, + getUsers, + getUserById, + editUser, + deleteUser, // addToFavoriteRoute as addToFavorite, - userSignInRoute as userSignIn, - signUpRoute as userSignup, - sentEmailRoute as sentEmail, - resetPasswordRoute as resetPassword, - getGoogleAuthURLRoute as getGoogleAuthURL, - // googleSignin, - getMeRoute as getMe, + userSignIn, + userSignup, + sentEmail, + resetPassword, + getGoogleAuthURL, + getMe, } from '../controllers/user/index'; import * as validator from '@packrat/validations'; -import { googleSigninRoute as signInGoogle } from '../controllers/passport/index'; +import { signInGoogle } from '../controllers/passport/index'; import { - emailExistsRoute as emailExists, - updatePasswordRoute as updatePassword, - checkCodeRoute as checkCode, + emailExists, + updatePassword, + checkCode, } from '../controllers/auth/index'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; import authTokenMiddleware from '../middleware/auth'; @@ -29,330 +27,86 @@ import { zodParser } from '../middleware/validators/zodParser'; const router = new Hono(); -/** - * @swagger - * tags: - * name: User - * description: User routes - */ - -/** - * @swagger - * /user: - * get: - * summary: Get all users - * tags: [User] - * responses: - * '200': - * description: Successful response with all users - * '500': - * description: Error retrieving users - */ router.get( '/', - authTokenMiddleware as any, - checkRole(['admin']) as any, + authTokenMiddleware, + checkRole(['admin']), tryCatchWrapper(getUsers), ); -/** - * @swagger - * /user/{userId}: - * get: - * summary: Get user by ID - * tags: [User] - * parameters: - * - in: path - * name: userId - * schema: - * type: string - * required: true - * description: ID of the user - * responses: - * '200': - * description: Successful response with the user - * '400': - * description: Invalid request parameters - * '500': - * description: Error retrieving the user - */ router.get( '/:userId', - authTokenMiddleware as any, - ((req, res, next) => { - zodParser(validator.getUserById, req.params, next); - next(); - }) as any, + authTokenMiddleware, + zodParser(validator.getUserById, 'params'), tryCatchWrapper(getUserById), ); -// router.post("/", addUser); - -/** - * @swagger - * /user/signin: - * post: - * summary: User sign-in - * tags: [User] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * email: - * type: string - * password: - * type: string - * responses: - * '200': - * description: Successful sign-in - * '400': - * description: Invalid request parameters - * '500': - * description: Error signing in - */ router.post( '/signin', - ((req, res, next) => zodParser(validator.userSignIn, req.body, next)) as any, + zodParser(validator.userSignIn, 'body'), tryCatchWrapper(userSignIn), ); -/** - * @swagger - * /user/signup: - * post: - * summary: User sign-up - * tags: [User] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * name: - * type: string - * email: - * type: string - * password: - * type: string - * responses: - * '200': - * description: Successful sign-up - * '400': - * description: Invalid request parameters - * '500': - * description: Error signing up - */ - router.post( '/signup', - ((req, res, next) => zodParser(validator.userSignUp, req.body, next)) as any, + zodParser(validator.userSignUp, 'body'), tryCatchWrapper(userSignup), ); -/** - * @swagger - * /user/reset-password-email: - * post: - * summary: Send reset password email - * tags: [User] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * email: - * type: string - * responses: - * '200': - * description: Successful email sent - * '400': - * description: Invalid request parameters - * '500': - * description: Error sending the email - */ router.post( '/reset-password-email', - ((req, res, next) => zodParser(validator.sentEmail, req.body, next)) as any, + zodParser(validator.sentEmail, 'body'), tryCatchWrapper(sentEmail), ); -/** - * @swagger - * /user/reset-password: - * post: - * summary: Reset password - * tags: [User] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * resetToken: - * type: string - * password: - * type: string - * responses: - * '200': - * description: Successful password reset - * '400': - * description: Invalid request parameters - * '500': - * description: Error resetting the password - */ router.post( '/reset-password', - ((req, res, next) => zodParser(validator.checkCode, req.body, next)) as any, + zodParser(validator.resetPassword, 'body'), tryCatchWrapper(resetPassword), ); -/** - * @swagger - * /user/me/info: - * get: - * summary: Get user information - * tags: [User] - * security: - * - bearerAuth: [] - * responses: - * '200': - * description: Successful response with user information - * '401': - * description: Unauthorized - Invalid or missing authentication token - * '500': - * description: Error retrieving user information - */ router.get( '/me/info', - authTokenMiddleware as any, - checkRole(['user', 'admin']) as any, + authTokenMiddleware, + checkRole(['user', 'admin']), tryCatchWrapper(getMe), ); -/** - * @swagger - * /user/google/url: - * get: - * summary: Get Google authentication URL - * tags: [User] - * responses: - * '200': - * description: Successful response with Google authentication URL - * '500': - * description: Error retrieving Google authentication URL - */ router.get('/google/url', tryCatchWrapper(getGoogleAuthURL)); // router.get(`/${REDIRECT_URL}`, tryCatchWrapper(googleSignin)); -/** - * @swagger - * /user/google: - * post: - * summary: Sign in with Google - * tags: [User] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * id_token: - * type: string - * responses: - * '200': - * description: Successful sign-in with Google - * '400': - * description: Invalid request parameters - * '500': - * description: Error signing in with Google - */ router.post('/google', tryCatchWrapper(signInGoogle)); -/** - * @swagger - * /user: - * put: - * summary: Edit user - * tags: [User] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * userId: - * type: string - * responses: - * '200': - * description: Successful response editing the user - * '400': - * description: Invalid request parameters - * '500': - * description: Error editing the user - */ router.put( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.editUser, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.editUser, 'body'), tryCatchWrapper(editUser), ); -/** - * @swagger - * /user: - * delete: - * summary: Delete user - * tags: [User] - * requestBody: - * required: true - * content: - * application/json: - * schema: - * type: object - * properties: - * userId: - * type: string - * responses: - * '200': - * description: Successful response deleting the user - * '400': - * description: Invalid request parameters - * '500': - * description: Error deleting the user - */ router.delete( '/', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.deleteUser, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.deleteUser, 'body'), tryCatchWrapper(deleteUser), ); router.post( '/checkcode', - authTokenMiddleware as any, - ((req, res, next) => zodParser(validator.checkCode, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.checkCode, 'body'), tryCatchWrapper(checkCode), ); router.post( '/updatepassword', - authTokenMiddleware as any, - ((req, res, next) => - zodParser(validator.updatePassword, req.body, next)) as any, + authTokenMiddleware, + zodParser(validator.updatePassword, 'body'), tryCatchWrapper(updatePassword), ); router.post( '/emailexists', - ((req, res, next) => zodParser(validator.emailExists, req.body, next)) as any, + zodParser(validator.emailExists, 'body'), tryCatchWrapper(emailExists), ); diff --git a/server/src/routes/weatherRoutes.ts b/server/src/routes/weatherRoutes.ts index e71c7f2cc..ca3340536 100644 --- a/server/src/routes/weatherRoutes.ts +++ b/server/src/routes/weatherRoutes.ts @@ -1,50 +1,10 @@ import { Hono } from 'hono'; -import { - getWeatherWeekRoute as getWeatherWeek, - getWeatherRoute as getWeather, -} from '../controllers/weather/index'; +import { getWeather } from '../controllers/weather/index'; import authTokenMiddleware from '../middleware/auth'; import { tryCatchWrapper } from '../helpers/tryCatchWrapper'; const router = new Hono(); -/** - * @swagger - * tags: - * name: Weather - * description: Weather routes - */ - -/** - * @swagger - * /weather: - * get: - * summary: Get current weather - * tags: [Weather] - * responses: - * '200': - * description: Successful response with current weather - * '500': - * description: Error retrieving current weather - */ -router.get('/', authTokenMiddleware as any, tryCatchWrapper(getWeather)); - -/** - * @swagger - * /weather/week: - * get: - * summary: Get weekly weather forecast - * tags: [Weather] - * responses: - * '200': - * description: Successful response with weekly weather forecast - * '500': - * description: Error retrieving weekly weather forecast - */ -router.get( - '/week', - authTokenMiddleware as any, - tryCatchWrapper(getWeatherWeek), -); +router.get('/', authTokenMiddleware, tryCatchWrapper(getWeather)); export default router; diff --git a/server/src/services/item/addItemService.ts b/server/src/services/item/addItemService.ts index e297de7e5..daf3e3fc8 100644 --- a/server/src/services/item/addItemService.ts +++ b/server/src/services/item/addItemService.ts @@ -70,4 +70,4 @@ export const addItemService = async ( // return { newItem: updatedItem, packId }; return item; -}; +}; \ No newline at end of file diff --git a/server/src/services/pack/getPublicPacksService.ts b/server/src/services/pack/getPublicPacksService.ts index 0bfeba40a..b6a20ca76 100644 --- a/server/src/services/pack/getPublicPacksService.ts +++ b/server/src/services/pack/getPublicPacksService.ts @@ -17,6 +17,7 @@ export async function getPublicPacksService(queryBy: string = 'createdAt') { is_public: true, }); + // Apply sorting if necessary packs = await sortFunction({ packs, diff --git a/server/src/services/user/emailExistsService.ts b/server/src/services/user/emailExistsService.ts index 398b2f615..51a3c3166 100644 --- a/server/src/services/user/emailExistsService.ts +++ b/server/src/services/user/emailExistsService.ts @@ -18,6 +18,7 @@ export async function emailExistsService({ throw new Error(val); } const result1 = await sendEmailNotice({ sendGridApiKey, smtpEmail, email }); + console.log('result1result1', result1) if (result1.status) { const { newcode } = result1; const result2 = await findUserAndUpdate(email, newcode, 'code'); @@ -26,7 +27,9 @@ export async function emailExistsService({ } } } catch (error) { + console.log('error', error.message) throw new Error(error.message); + } } diff --git a/server/src/trpc/httpDBContext.ts b/server/src/trpc/httpDBContext.ts new file mode 100644 index 000000000..96c4bba57 --- /dev/null +++ b/server/src/trpc/httpDBContext.ts @@ -0,0 +1,10 @@ +import { type Context } from 'hono'; +import { createContext } from './context'; + +// A middleware to initiate db connection and add it to the context +const httpDBContext = async (c: Context, next: () => Promise) => { + await createContext(c)(); + await next(); +}; + +export { httpDBContext }; diff --git a/server/src/utils/accountEmail.ts b/server/src/utils/accountEmail.ts index 9a497c85e..fd2a67c8a 100644 --- a/server/src/utils/accountEmail.ts +++ b/server/src/utils/accountEmail.ts @@ -99,12 +99,12 @@ export const resetEmail = async ( body: JSON.stringify(emailData), }); - if (!response.ok) { - console.log('Email did not Send'); - throw new Error(`HTTP error! status: ${response.status}`); - } + // if (!response.ok) { + // console.log('Email did not Send'); + // throw new Error(`HTTP error! status: ${response.status}`); + // } - console.log('Email Sent'); + console.log('Email Sent', response); // return await response.json(); } catch (error) { console.error('Error resetting email:', error);