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 8 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
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ Agora é necessário adaptar o código de modo a transformá-lo em uma API respe
- `GET /plants/:id`: retorna uma planta com o id;
- `DELETE /plants/:id`: deleta uma planta com o id;
- `PUT /plants/:id`: sobrescreve a planta com id;
- `GET /sunny`: retorna as plantas que precisam de sol;
- Realizar validações necessárias para os novos endpoints;
- Implementar na camada **Model**, pelo menos uma classe responsável por manipular as informações que estão no `./src/models/database`. Essa classe deve implementar a interface `IModel`:

Expand Down
32 changes: 31 additions & 1 deletion src/controllers/PlantController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Request, Response, NextFunction } from 'express';
import PlantService from '../services/PlantService';

class PlantController {
public service: PlantService = new PlantService();
constructor(private service: PlantService) {}
flpnascto marked this conversation as resolved.
Show resolved Hide resolved

public async getAll(_req: Request, res: Response, next: NextFunction): Promise<Response | void> {
try {
Expand All @@ -21,6 +21,36 @@ class PlantController {
next(error);
}
}

public async getById(req: Request, res: Response, next: NextFunction): Promise<Response | void> {
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): Promise<Response | void> {
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): Promise<Response | void> {
const { id } = req.params;
try {
const plant = await this.service.update(id, req.body);
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'>;
9 changes: 9 additions & 0 deletions src/interfaces/IPlantModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { IPlant } from './IPlant';

export default interface IPlantModel {
getAll(): Promise<IPlant[]>
create(plant: Omit<IPlant, 'id'>): Promise<IPlant>
getById(id: string): Promise<IPlant | null>
removeById(id: string): Promise<boolean>
update(plant: IPlant): Promise<IPlant>
}
flpnascto marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 3 additions & 0 deletions src/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { default as IOpsInfo } from './IOpsInfo';
export { IPlant, INewPlant } from './IPlant';
export { default as IPlantModel } from './IPlantModel';
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;
}
}
67 changes: 67 additions & 0 deletions src/models/PlantModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { HandleFile, FileType } from './HandleFile';
import { IPlantModel, IPlant, IOpsInfo } from '../interfaces';

class PlantModel implements IPlantModel {
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<boolean> {
const plants = await this.getAll();

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

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 true;
}

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;
}
}

export default PlantModel;
9 changes: 8 additions & 1 deletion src/router/PlantRouter.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { Router } from 'express';

import PlantController from '../controllers/PlantController';
import PlantModel from '../models/PlantModel';
import PlantService from '../services/PlantService';

const plantController = new PlantController();
const plantModel = new PlantModel();
const plantService = new PlantService(plantModel);
const plantController = new PlantController(plantService);

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;
90 changes: 28 additions & 62 deletions src/services/PlantService.ts
Original file line number Diff line number Diff line change
@@ -1,80 +1,46 @@
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 { IPlantModel, 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;
}
constructor(private model: IPlantModel) {}

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;

if (typeof breed !== 'string') {
throw new HttpException(400, 'Attribute "breed" must be string.');
}

if (typeof needsSun !== 'boolean') {
throw new HttpException(400, 'Attribute "needsSun" must be boolen.');
}

if (typeof origin !== 'string') {
throw new HttpException(400, 'Attribute "origin" must be string.');
}

if (typeof size !== 'number') {
throw new HttpException(400, 'Attribute "size" must be number.');
}
PlantValidate.validateAttibutes(plant);

const { needsSun, size, origin } = plant;
const waterFrequency = needsSun
? size * 0.77 + (origin === 'Brazil' ? 8 : 7)
: (size / 2) * 1.33 + (origin === 'Brazil' ? 8 : 7);

const dataRaw = await fs.readFile(this.plantsFile, { encoding: 'utf8' });
const plants: IPlant[] = JSON.parse(dataRaw);
const newPlant = await this.model.create({ ...plant, waterFrequency });
return newPlant;
}

const newPlantId = await this.updateOpsInfo(1);
const newPlant = { id: newPlantId, ...plant, waterFrequency };
plants.push(newPlant);
public async getById(id: string): Promise<IPlant> {
const plant = await this.model.getById(id);
if (!plant) throw new NotFoundException('Plant not Found!');
return plant;
}

await fs.writeFile(this.plantsFile, JSON.stringify(plants, null, 2));
return newPlant;
public async removeById(id: string): Promise<void> {
const isPlantRemoved = await this.model.removeById(id);
if (!isPlantRemoved) throw new NotFoundException('Plant not Found!');
}

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!');

PlantValidate.validateAttibutes(plant);

const editedPlant = await this.model.update({ id: parseInt(id, 10), ...plant });
return editedPlant;
}
}

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);
}
}