Skip to content

Commit

Permalink
Many fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasgehl3n committed Nov 13, 2023
1 parent 4720e7b commit ef42a19
Show file tree
Hide file tree
Showing 10 changed files with 49 additions and 54 deletions.
38 changes: 7 additions & 31 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import expressSession from 'express-session';
import PassportManager from './middlewares/authentication/PassportManager';
import AuthenticationValidator from './middlewares/authentication/AuthenticationValidator';
import cors from 'cors';
import RedisStore from "connect-redis";
import { createClient } from 'redis';
class Application {
server: http.Server;
express: express.Application;
Expand All @@ -26,22 +24,13 @@ class Application {
}

private _setMiddlewares(): void {
// if (process.env.NODE_ENV === 'production') {
// this.express.use(cors({
// origin: process.env.FRONTEND_URL,
// credentials: true,
// methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
// optionsSuccessStatus: 200
// }));
// }
// else {
this.express.use(cors({
origin: 'http://localhost:3000',
credentials: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
optionsSuccessStatus: 200
}));
// }
this.express.use(cors({
origin: process.env.FRONTEND_URL,
credentials: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
optionsSuccessStatus: 200
}));

this.express.use(function (req: any, res: any, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
Expand All @@ -65,19 +54,6 @@ class Application {

private async _setSession(): Promise<void> {
const addedSessionStore: any = {};
if (process.env.REDIS_URL) {
let redisClient = createClient({
url: process.env.REDIS_URL,
});
redisClient.connect();
redisClient.on("error", function (error) {
console.error("Error in Redis client: " + error);
});

redisClient.flushDb();

addedSessionStore.store = new RedisStore({ client: redisClient });
}
this.express.use(expressSession({
...addedSessionStore,
secret: 'xkACzfyIvmx8wEL?-Z9652ub?h61Ozu5/ag13mzSaXzuv--8EfCwUDTqT8QGtZGgYqzDcWguh8qqqGiQWqxMTx98PmRBFIk7CuuEos!JQ7N=vdhnl5jY9N6K20oQtbynxrvLhyBB7CACN99!xb7cQwt3MkMODuz=D!cryE?va5J-Htq=z5ZTYM3B8xbQxQyVsNHAZBWOjbBKW3wZSGyjOhu/cV-zLFyFhnSmLKY2Dter//Fe9nJ9cBJJVRTjW/pN',
Expand Down
29 changes: 16 additions & 13 deletions src/controllers/AnimalController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import AnimalAttachmentService from "../services/AnimalAttachmentService";
import Constants from "../../constants";
import AnimalFilters from "../filters/AnimalFilters";
import AnimalPredictionService from "../services/AnimalPredictionService";
import { Species } from "../enums/Species";
const _mapRequestToData = async (req: Request) => {
let data = req.body as unknown as Animal;
data = mapData(data);
Expand Down Expand Up @@ -225,18 +226,20 @@ export default class AnimalController {
const animalSaved = await AnimalService.SaveWithDependences(animal, transaction);
if (animalSaved?.id || animalSaved?.id === 0) {
if (animal.animalImages && animal.animalImages.length > 0) {
let i = 0;
const listImages = [];
for (const image of animal.animalImages) {
if (i > 10)
break;
const buffer = Buffer.from(image.image);
const blob = new Blob([buffer], { type: image.type });
listImages.push(blob);
i++;
if (animal.species == Species.Dog) {
let i = 0;
const listImages = [];
for (const image of animal.animalImages) {
if (i > 10)
break;
const buffer = Buffer.from(image.image);
const blob = new Blob([buffer], { type: image.type });
listImages.push(blob);
i++;
}
await AnimalPredictionService
.generateAnimalPrediction(listImages, animal.id);
}
await AnimalPredictionService
.generateAnimalPrediction(listImages, animal.id);
}
}
}
Expand Down Expand Up @@ -293,7 +296,7 @@ export default class AnimalController {
model: AnimalImage,
as: 'animalImages',
separate: true,
limit: 1,
limit: 1,
},
],
...AnimalFilters.ApplyFilters(req),
Expand Down Expand Up @@ -340,7 +343,7 @@ export default class AnimalController {

const filters = req.body.filters;
const page = req.body.page;

const prediction = await AnimalPredictionService.getAnimalPredictionsOnSearch(blob);
if (prediction) {
for (const entities of prediction) {
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/InstitutionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ class InstitutionController {
const shouldGenerateUserService = !data.id;

const institution = await InstitutionService.SaveWithDependences(data);
if (shouldGenerateUserService) {
UserRoleService.GenerateUserServiceToInstitution(authenticatedRequest.user!, data);
if (shouldGenerateUserService && institution) {
UserRoleService.GenerateUserServiceToInstitution(authenticatedRequest.user!, institution);
}

return res.status(200).send({ id: institution?.id});
Expand Down
1 change: 1 addition & 0 deletions src/database/models/Animal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class Animal extends Model {
public weight!: number;
public deathDate!: Date;
public deathDetail!: string;
public idBreed!: number;
public adoptionDate!: Date;
public adoptionUser!: User;
public adoptionSolictationDate!: Date;
Expand Down
5 changes: 2 additions & 3 deletions src/database/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import dotenv from 'dotenv';

dotenv.config();


let devOptions = {
host: process.env.DB_HOST,
username: process.env.DB_USER,
Expand All @@ -14,8 +13,8 @@ let devOptions = {
let prodOptions = {
dialectOptions: {
ssl: {
require: true, // Requer SSL
rejectUnauthorized: false // Desativa a verificação do certificado SSL (use apenas em ambientes de desenvolvimento)
require: true,
rejectUnauthorized: false
}
}
};
Expand Down
4 changes: 4 additions & 0 deletions src/enums/Species.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export enum Species {
Dog = 1,
Cat = 2,
}
3 changes: 2 additions & 1 deletion src/filters/AnimalFilters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { AuthenticatedRequest } from "../..";
import { Op } from "sequelize";
import Institution from "../database/models/Institution";
import AnimalImage from "../database/models/AnimalImage";
import { Species } from "../enums/Species";

const _bondedFilters = (userRoles: UserRole[], searchFilter: any) => {
return {
Expand Down Expand Up @@ -67,7 +68,7 @@ export default class AnimalFilters {
}


const specie = req.query.dog ? 1 : req.query.cat ? 2 : null;
const specie = req.query.dog ? Species.Dog : req.query.cat ? Species.Cat : null;
if (specie) {
searchFilter = _specieFilter(specie, searchFilter);
}
Expand Down
1 change: 0 additions & 1 deletion src/middlewares/acl/CheckAclPermission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { Roles } from "../../enums/Roles";

export default function CheckAclPermission(role: Roles) {
return function (req: Request, res: Response, next: NextFunction) {
// return next();
const authenticatedRequest = req as unknown as AuthenticatedRequest;
const { userRoles } = authenticatedRequest.user!;
const id = req.params.id || req.body.id;
Expand Down
17 changes: 15 additions & 2 deletions src/services/AnimalPredictionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ class AnimalPredictionService extends BaseService<AnimalPrediction>{
let listAnimals: number[] = [];
if (predictionViewList && predictionViewList.length > 0) {
for (let i = 0; i < predictionViewList.length; i++) {
if(predictionViewList[i].prob < 0.2) continue;
if (predictionViewList[i].prob < 0.2) continue;
const breed = await BreedService.getBreedByAITag(predictionViewList[i].breed);
if (breed && breed.id) {
const animals = await this.GetAnimalsByBreedPrediction(breed.id);
let animals = await this.GetAnimalsByBreedPrediction(breed.id);
animals = animals.filter(x => x.predictions.find(x => x.idBreed == breed.id)?.percentage || 0 > 0.15);
const view = new AnimalView();
view.breed = breed;
view.animalList = animals.filter(x => !listAnimals.includes(x.id));
Expand Down Expand Up @@ -54,6 +55,16 @@ class AnimalPredictionService extends BaseService<AnimalPrediction>{
return animals;
}

static async deleteCurrentPredictions(idAnimal: number) {
const predictions = await AnimalPrediction.findAll({
where: {
idAnimal: idAnimal
}
});
for (let i = 0; i < predictions.length; i++) {
await predictions[i].destroy();
}
}
static async generateAnimalPrediction(images: Blob[], idAnimal: number) {
let listPredictions: AnimalPredictionView[] = [];

Expand Down Expand Up @@ -84,6 +95,8 @@ class AnimalPredictionService extends BaseService<AnimalPrediction>{
const sizeSlice = finalListPredictions.length > 5 ? 5 : finalListPredictions.length;
finalListPredictions = finalListPredictions.slice(0, sizeSlice);


this.deleteCurrentPredictions(idAnimal);
let listAnimalPredictions: AnimalPrediction[] = [];
for (let i = 0; i < finalListPredictions.length; i++) {
const breed = await BreedService.getBreedByAITag(finalListPredictions[i].breed);
Expand Down
1 change: 0 additions & 1 deletion src/services/InstitutionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ class InstitutionService extends BaseService<Institution>{
static async SaveWithDependences(institution: Institution) {
const t = await database.connection.transaction();
try {
console.log(institution.name)
if (institution.adress) {
const address = await AdressService.Save(institution.adress, t);
institution.idAddress = address?.id;
Expand Down

0 comments on commit ef42a19

Please sign in to comment.