Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: get available stocks #11

Merged
merged 4 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions src/controllers/stock.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Request, Response } from 'express';
import { StatusCodes } from 'http-status-codes';
import { RequestExtended } from 'src/interfaces';
import {
createOne,
deleteById,
Expand All @@ -12,15 +13,16 @@ import { handleHttpError } from 'src/utils';
/**
* Get all stocks.
*
* @param _req The request object.
* @param req The request object.
* @param res The response object.
*/
export const getStocks = async (
_req: Request,
req: RequestExtended,
res: Response
): Promise<void> => {
try {
const response = await findAll();
const { id: userId } = req;
const response = await findAll(userId as string);
res.json(response);
} catch (error) {
handleHttpError(res, error);
Expand All @@ -34,12 +36,13 @@ export const getStocks = async (
* @param res The response object.
*/
export const getStockById = async (
req: Request,
req: RequestExtended,
res: Response
): Promise<void> => {
try {
const { id: userId } = req;
const { id } = req.params;
const response = await findById(id);
const response = await findById(userId as string, id);
res.json(response);
} catch (error) {
handleHttpError(res, error);
Expand Down
91 changes: 79 additions & 12 deletions src/services/stock.service.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,105 @@
import { StatusCodes } from 'http-status-codes';
import { Stock } from 'src/database/models';
import {
IStock,
IStockDocument,
IStandardResponse,
} from 'src/interfaces';
import { Broker, Stock } from 'src/database/models';
import { IStock, IStockDocument, IStandardResponse } from 'src/interfaces';
import { HttpError } from 'src/utils';
import * as userService from 'src/services/user.service';

/**
* Find all stocks.
* Find all the stocks available in the user's country.
*
* @param userId The user id.
* @returns The stocks found.
*/
export const findAll = async (): Promise<IStockDocument[]> => {
const stocks = await Stock.find();
export const findAll = async (userId: string): Promise<IStockDocument[]> => {
const user = await userService.findById(userId);

if (!user) {
throw new HttpError('El usuario no existe', StatusCodes.NOT_FOUND);
}

const countryId = user.country;

const stocks = await Broker.aggregate([
{
$match: {
countries: countryId,
},
},
{
$lookup: {
from: 'stocks',
localField: 'stocks',
foreignField: '_id',
as: 'stocks',
},
},
{
$unwind: '$stocks',
},
{
$replaceRoot: {
newRoot: '$stocks',
},
},
]);

return stocks;
};

/**
* Find a stock by id.
*
* @param userId The user id.
* @param id The stock id.
* @returns The stock found.
*/
export const findById = async (
userId: string,
id: string
): Promise<IStockDocument | null> => {
const stock = await Stock.findById(id);
const user = await userService.findById(userId);

if (!stock) {
throw new HttpError('La accion no existe', StatusCodes.NOT_FOUND);
if (!user) {
throw new HttpError('El usuario no existe', StatusCodes.NOT_FOUND);
}

const countryId = user.country;

const stockResult = await Broker.aggregate<IStockDocument>([
{
$match: {
countries: countryId,
},
},
{
$lookup: {
from: 'stocks',
localField: 'stocks',
foreignField: '_id',
as: 'stocks',
},
},
{
$unwind: '$stocks',
},
{
$replaceRoot: {
newRoot: '$stocks',
},
},
{
$match: {
_id: id,
},
},
]);

if (!stockResult.length) {
throw new HttpError('La accion no esta disponible', StatusCodes.NOT_FOUND);
}

const stock = stockResult[0];

return stock;
};

Expand Down
2 changes: 1 addition & 1 deletion src/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
export const findOne = async (
filter: Record<string, unknown>
): Promise<IUserDocument | null> => {
const user = await User.findOne(filter).populate('country currency');
const user = await User.findOne(filter);

return user;
};
Expand Down
Loading