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

resolucao exercicio #1

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion src/App.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import express, { Request, Response } from 'express';
import PlantRouter from './router/PlantRouter';
import { PlantRouter, SunnyRouter } from './router';
import errorMiddleware from './middlewares/errorMiddleware';

export default class App {
Expand All @@ -17,6 +17,7 @@ export default class App {

private routes(): void {
this.app.use('/plants', PlantRouter);
this.app.use('/sunny', SunnyRouter);
}

private config():void {
Expand Down
39 changes: 39 additions & 0 deletions src/controllers/PlantController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,45 @@ class PlantController {
next(error);
}
}

public async getById(req: Request, res: Response, next: NextFunction) {
flpnascto marked this conversation as resolved.
Show resolved Hide resolved
const { id } = req.params;
try {
const plant = await this.service.getById(id);
return res.status(200).json(plant);
} catch (error) {
next(error);
}
}

public async remove(req: Request, res: Response, next: NextFunction) {
const { id } = req.params;
try {
await this.service.removeById(id);
return res.status(204).end();
} catch (error) {
next(error);
}
}

public async update(req: Request, res: Response, next: NextFunction) {
const { id } = req.params;
try {
const plant = await this.service.update(id, req.body);
return res.status(200).json(plant);
} catch (error) {
next(error);
}
}

public async getPlantsThatNeedsSun(_req: Request, res: Response, next: NextFunction) {
try {
const plant = await this.service.getPlantsThatNeedsSun();
return res.status(200).json(plant);
} catch (error) {
next(error);
}
}
}

export default PlantController;
3 changes: 3 additions & 0 deletions src/interfaces/IOpsInfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default interface IOpsInfo {
createdPlants: number
}
10 changes: 10 additions & 0 deletions src/interfaces/IPlant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export interface IPlant {
id: number,
breed: string,
needsSun: boolean,
origin: string,
size: number,
waterFrequency: number,
}

export type INewPlant = Omit<IPlant, 'id' | 'waterFrequency'>;
2 changes: 2 additions & 0 deletions src/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { default as IOpsInfo } from './IOpsInfo';
export { IPlant, INewPlant } from './IPlant';
26 changes: 26 additions & 0 deletions src/models/HandleFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import fs from 'fs/promises';
import path from 'path';

export enum FileType {
Plants = 'plants',
OpsInfo = 'opsInfo',
}

const PATHS = {
plants: path.join(__dirname, 'database', 'plantsData.json'),
opsInfo: path.join(__dirname, 'database', 'opsInfo.json'),
};

export class HandleFile {
private PATHS = PATHS;

public async saveFile<DataType>(type: FileType, data: DataType): Promise<void> {
await fs.writeFile(this.PATHS[`${type}`], JSON.stringify(data, null, 2));
}

public async readFile<DataType>(type: FileType): Promise<DataType> {
const dataRaw = await fs.readFile(this.PATHS[`${type}`], { encoding: 'utf8' });
const data: DataType = JSON.parse(dataRaw);
return data;
}
}
75 changes: 75 additions & 0 deletions src/models/PlantModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { HandleFile, FileType } from './HandleFile';
import { IPlant, IOpsInfo } from '../interfaces';

class PlantModel {
flpnascto marked this conversation as resolved.
Show resolved Hide resolved
private handleFile = new HandleFile();

private async updateOpsInfo(incrementAmount = 1): Promise<number> {
const opsInfo = await this.handleFile.readFile<IOpsInfo>(FileType.OpsInfo);
opsInfo.createdPlants += incrementAmount;

await this.handleFile.saveFile(FileType.OpsInfo, opsInfo);

return opsInfo.createdPlants;
}

public async getAll(): Promise<IPlant[]> {
const plants = await this.handleFile.readFile<IPlant[]>(FileType.Plants);
return plants;
}

public async create(plant: Omit<IPlant, 'id'>): Promise<IPlant> {
const plants = await this.getAll();

const newPlantId = await this.updateOpsInfo(1);
const newPlant = { id: newPlantId, ...plant };
plants.push(newPlant);

await this.handleFile.saveFile(FileType.Plants, plants);

return newPlant;
}

public async getById(id: string): Promise<IPlant | null> {
const plants = await this.getAll();

const plantById = plants.find((plant) => plant.id === parseInt(id, 10));
if (!plantById) return null;
return plantById;
}

public async removeById(id: string): Promise<IPlant | null> {
const plants = await this.getAll();

const removedPlant = plants.find((plant) => plant.id === parseInt(id, 10));
if (!removedPlant) return null;

const newPlants = plants.filter((plant) => plant.id !== parseInt(id, 10));
this.handleFile.saveFile(FileType.Plants, newPlants);
flpnascto marked this conversation as resolved.
Show resolved Hide resolved

return removedPlant;
}

public async update(plant: IPlant): Promise<IPlant> {
const plants = await this.getAll();

const updatedPlants = plants.map((editPlant) => {
if (plant.id === editPlant.id) return { ...plant };
return editPlant;
});

await this.handleFile.saveFile(FileType.Plants, updatedPlants);

return plant;
}

public async getPlantsThatNeedsSun() {
const plants = await this.getAll();

const filteredPlants = plants.filter((plant) => plant.needsSun);

return filteredPlants;
}
}

export default PlantModel;
3 changes: 3 additions & 0 deletions src/router/PlantRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,8 @@ const plantRouter = Router();

plantRouter.get('/', (req, res, next) => plantController.getAll(req, res, next));
plantRouter.post('/', (req, res, next) => plantController.create(req, res, next));
plantRouter.get('/:id', (req, res, next) => plantController.getById(req, res, next));
plantRouter.delete('/:id', (req, res, next) => plantController.remove(req, res, next));
plantRouter.put('/:id', (req, res, next) => plantController.update(req, res, next));

export default plantRouter;
11 changes: 11 additions & 0 deletions src/router/SunnyRouter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Router } from 'express';

import PlantController from '../controllers/PlantController';

const plantController = new PlantController();

const sunnyRouter = Router();

sunnyRouter.get('/', (req, res, next) => plantController.getPlantsThatNeedsSun(req, res, next));
flpnascto marked this conversation as resolved.
Show resolved Hide resolved

export default sunnyRouter;
2 changes: 2 additions & 0 deletions src/router/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { default as PlantRouter } from './PlantRouter';
export { default as SunnyRouter } from './SunnyRouter';
95 changes: 33 additions & 62 deletions src/services/PlantService.ts
Original file line number Diff line number Diff line change
@@ -1,81 +1,52 @@
// import PlantValidate from './validations/PlantValidate';
import fs from 'fs/promises';
import path from 'path';
import HttpException from './exceptions/HttpException';

interface IPlant {
id: number,
breed: string,
needsSun: boolean,
origin: string,
size: number,
waterFrequency: number,
}

type INewPlant = Omit<IPlant, 'id' | 'waterFrequency'>;

interface IOpsInfo {
createdPlants: number
}
import PlantModel from '../models/PlantModel';
import { INewPlant, IPlant } from '../interfaces';
import { NotFoundException } from './exceptions';
import PlantValidate from './validations/PlantValidate';

class PlantService {
private readonly plantsFile = path.join(__dirname, '..', 'models', 'database', 'plantsData.json');

private readonly opsFile = path.join(__dirname, '..', 'models', 'database', 'opsInfo.json');

private async updateOpsInfo(incrementAmount = 1): Promise<number> {
const dataRaw = await fs.readFile(this.opsFile, { encoding: 'utf8' });
const opsInfo: IOpsInfo = JSON.parse(dataRaw);
opsInfo.createdPlants += incrementAmount;

await fs.writeFile(this.opsFile, JSON.stringify(opsInfo, null, 2));

return opsInfo.createdPlants;
}
private model: PlantModel = new PlantModel();

public async getAll(): Promise<IPlant[]> {
const dataRaw = await fs.readFile(this.plantsFile, { encoding: 'utf8' });
const plants: IPlant[] = JSON.parse(dataRaw);
const plants = await this.model.getAll();
return plants;
}

public async create(plant: INewPlant): Promise<IPlant> {
const {
breed,
needsSun,
origin,
size,
} = plant;
PlantValidate.validateAttibutes(plant);

if (typeof breed !== 'string') {
throw new HttpException(400, 'Attribute "breed" must be string.');
}
const { needsSun, size, origin } = plant;
const waterFrequency = needsSun
? size * 0.77 + (origin === 'Brazil' ? 8 : 7)
: (size / 2) * 1.33 + (origin === 'Brazil' ? 8 : 7);

if (typeof needsSun !== 'boolean') {
throw new HttpException(400, 'Attribute "needsSun" must be boolen.');
}
const newPlant = await this.model.create({ ...plant, waterFrequency });
return newPlant;
}

if (typeof origin !== 'string') {
throw new HttpException(400, 'Attribute "origin" must be string.');
}
public async getById(id: string): Promise<IPlant> {
const plant = await this.model.getById(id);
if (!plant) throw new NotFoundException('Plant not Found!');
return plant;
}

if (typeof size !== 'number') {
throw new HttpException(400, 'Attribute "size" must be number.');
}
public async removeById(id: string): Promise<void> {
const plant = await this.model.removeById(id);
if (!plant) throw new NotFoundException('Plant not Found!');
}

const waterFrequency = needsSun
? size * 0.77 + (origin === 'Brazil' ? 8 : 7)
: (size / 2) * 1.33 + (origin === 'Brazil' ? 8 : 7);
public async update(id: string, plant: Omit<IPlant, 'id'>): Promise<IPlant> {
const plantExists = await this.model.getById(id);
if (!plantExists) throw new NotFoundException('Plant not Found!');

const dataRaw = await fs.readFile(this.plantsFile, { encoding: 'utf8' });
const plants: IPlant[] = JSON.parse(dataRaw);
PlantValidate.validateAttibutes(plant);

const newPlantId = await this.updateOpsInfo(1);
const newPlant = { id: newPlantId, ...plant, waterFrequency };
plants.push(newPlant);
const editedPlant = await this.model.update({ id: parseInt(id, 10), ...plant });
return editedPlant;
}

await fs.writeFile(this.plantsFile, JSON.stringify(plants, null, 2));
return newPlant;
public async getPlantsThatNeedsSun(): Promise<IPlant[]> {
const plants = await this.model.getPlantsThatNeedsSun();
return plants;
}
}

Expand Down
9 changes: 9 additions & 0 deletions src/services/exceptions/BadRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import HttpException from './HttpException';

export default class BadRequestException extends HttpException {
private static status = 400;

constructor(message?: string) {
super(BadRequestException.status, message || 'Bad request');
}
}
2 changes: 1 addition & 1 deletion src/services/exceptions/HttpException.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class HttpException extends Error {
abstract class HttpException extends Error {
status: number;

message: string;
flpnascto marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
9 changes: 9 additions & 0 deletions src/services/exceptions/NotFound.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import HttpException from './HttpException';

export default class NotFoundException extends HttpException {
flpnascto marked this conversation as resolved.
Show resolved Hide resolved
private static status = 404;

constructor(message?: string) {
super(NotFoundException.status, message || 'Not Found');
}
}
2 changes: 2 additions & 0 deletions src/services/exceptions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { default as BadRequestException } from './BadRequest';
export { default as NotFoundException } from './NotFound';
35 changes: 35 additions & 0 deletions src/services/validations/PlantValidate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { INewPlant } from '../../interfaces';
import { BadRequestException } from '../exceptions';

export default class PlantValidate {
static validateBreed(breed: string): void {
if (typeof breed !== 'string') {
throw new BadRequestException('Attribute "breed" must be string.');
}
}

static validateNeedsSun(needsSun: boolean): void {
if (typeof needsSun !== 'boolean') {
throw new BadRequestException('Attribute "needsSun" must be boolen.');
}
}

static validateOrigin(origin: string): void {
if (typeof origin !== 'string') {
throw new BadRequestException('Attribute "origin" must be string.');
}
}

static validateSize(size: number): void {
flpnascto marked this conversation as resolved.
Show resolved Hide resolved
if (typeof size !== 'number') {
throw new BadRequestException('Attribute "size" must be number.');
}
}

static validateAttibutes(plant: INewPlant): void {
PlantValidate.validateBreed(plant.breed);
PlantValidate.validateNeedsSun(plant.needsSun);
PlantValidate.validateOrigin(plant.origin);
PlantValidate.validateSize(plant.size);
}
}