Skip to content

Commit

Permalink
Merge pull request #1096 from andrew-bierman/feat/integrate_rest_api
Browse files Browse the repository at this point in the history
Feat/integrate rest api
  • Loading branch information
andrew-bierman authored Jul 20, 2024
2 parents b1fed6d + 0a95e8f commit 218effa
Show file tree
Hide file tree
Showing 95 changed files with 1,414 additions and 3,199 deletions.
7 changes: 7 additions & 0 deletions packages/validations/src/validations/openAIRoutesValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
});
26 changes: 10 additions & 16 deletions server/src/controllers/auth/checkCode.ts
Original file line number Diff line number Diff line change
@@ -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<void>} - 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) => {
Expand Down
22 changes: 16 additions & 6 deletions server/src/controllers/auth/emailExists.ts
Original file line number Diff line number Diff line change
@@ -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<void>} - 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) => {
Expand Down
54 changes: 14 additions & 40 deletions server/src/controllers/auth/updatePassword.ts
Original file line number Diff line number Diff line change
@@ -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<void>} - 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
Expand Down
37 changes: 11 additions & 26 deletions server/src/controllers/favorite/addToFavorite.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
23 changes: 10 additions & 13 deletions server/src/controllers/favorite/getFavoritePacksByUser.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
26 changes: 11 additions & 15 deletions server/src/controllers/favorite/getUserFavorites.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
38 changes: 17 additions & 21 deletions server/src/controllers/geoCode/getGeoCode.ts
Original file line number Diff line number Diff line change
@@ -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<void>} - 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) => {
Expand Down
32 changes: 11 additions & 21 deletions server/src/controllers/getOsm/getDestination.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
21 changes: 6 additions & 15 deletions server/src/controllers/getOsm/getNominatimDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>} - 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 = '';

Expand All @@ -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);
}
};
Loading

0 comments on commit 218effa

Please sign in to comment.