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

Storage ms alberto recruitment #31

Open
wants to merge 15 commits into
base: development
Choose a base branch
from
Open
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
19 changes: 19 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
PORT=3000

DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=admin
DB_NAME=database_name

JWT_SECRET=jwt_secret_key

# Firebase Configuration
FIREBASE_PROJECT_ID=your-firebase-project-id
FIREBASE_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----\nYOUR_PRIVATE_KEY_HERE\n-----END PRIVATE KEY-----
FIREBASE_CLIENT_EMAIL=firebase-adminsdk@your-project-id.iam.gserviceaccount.com
FIREBASE_STORAGE_BUCKET=your-firebase-storage-bucket

REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_EXP=60000
Binary file modified .yarn/install-state.gz
Binary file not shown.
21 changes: 18 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,32 +17,47 @@
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
"test:e2e": "jest --config ./test/jest-e2e.json",
"typeorm": "ts-node ./node_modules/typeorm/cli -d ./src/infrastructure/typeorm/typeorm.config.ts",
"migration:generate": "npm run typeorm migration:generate src/db/migrations/migration -t -p",
"migration:run": "npm run typeorm -- migration:run",
"migration:revert": "npm run typeorm -- migration:revert"
},
"dependencies": {
"@nestjs-modules/ioredis": "^2.0.2",
"@nestjs/cache-manager": "^2.2.2",
"@nestjs/common": "^10.4.4",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.4.4",
"@nestjs/jwt": "^10.2.0",
"@nestjs/platform-express": "^10.4.4",
"@nestjs/swagger": "^7.4.2",
"@nestjs/typeorm": "^10.0.2",
"axios": "^1.7.7",
"cache-manager-redis-store": "^3.0.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"dotenv": "^16.4.5",
"firebase-admin": "^12.6.0",
"ioredis": "^5.4.1",
"pg": "^8.13.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"sharp": "^0.33.5",
"typeorm": "^0.3.20",
"uuid": "^10.0.0"
"uuid": "^10.0.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@nestjs/cli": "^10.4.5",
"@nestjs/schematics": "^10.1.4",
"@nestjs/testing": "^10.4.4",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.13",
"@types/multer": "^1.4.12",
"@types/node": "^20.16.11",
"@types/supertest": "^6.0.2",
"@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^7.18.0",
"@typescript-eslint/parser": "^7.18.0",
"eslint": "^8.57.1",
Expand Down Expand Up @@ -76,4 +91,4 @@
"testEnvironment": "node"
},
"packageManager": "[email protected]"
}
}
22 changes: 0 additions & 22 deletions src/app.controller.spec.ts

This file was deleted.

12 changes: 0 additions & 12 deletions src/app.controller.ts

This file was deleted.

18 changes: 13 additions & 5 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { RedisModule } from '@nestjs-modules/ioredis';

import { ImagesModule } from './modules/images/images.module';
import { TypeormModule } from './infrastructure/typeorm/typeorm.module';
import { config } from './config/envs';

@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
imports: [
ImagesModule,
TypeormModule,
RedisModule.forRoot({
type: 'single',
url: `redis://${config.REDIS_HOST}:${config.REDIS_PORT}`,
}),
],
})
export class AppModule {}
8 changes: 0 additions & 8 deletions src/app.service.ts

This file was deleted.

34 changes: 34 additions & 0 deletions src/config/envs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import * as z from 'zod';
import * as dotenv from 'dotenv';

dotenv.config();

const configSchema = z.object({
PORT: z.preprocess((value) => Number(value), z.number().default(3000)),
FIREBASE_PROJECT_ID: z.string(),
FIREBASE_PRIVATE_KEY: z.string(),
FIREBASE_CLIENT_EMAIL: z.string().email(),
FIREBASE_STORAGE_BUCKET: z.string(),
JWT_SECRET: z.string().optional(),
DB_HOST: z.string(),
DB_PORT: z.preprocess((value) => Number(value), z.number()),
DB_NAME: z.string().default('postgres'),
DB_USER: z.string().default('postgres'),
DB_PASSWORD: z.string(),
DB_SYNCHRONIZE: z.preprocess((value) => !!value, z.boolean().default(false)),
REDIS_HOST: z.string().optional(),
REDIS_PORT: z.preprocess((value) => Number(value), z.number()),
REDIS_EXP: z.preprocess((value) => Number(value), z.number()),
});

const parsedConfig = configSchema.safeParse(process.env);

if (!parsedConfig.success) {
console.error(
'❌ Invalid environment variables:',
parsedConfig.error.format(),
);
process.exit(1);
}

export const config = parsedConfig.data;
58 changes: 58 additions & 0 deletions src/infrastructure/cache/cache.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { Injectable } from '@nestjs/common';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';

import { LoggerService } from '../loggers/logger.service';
import { config } from '../../config/envs';

@Injectable()
export class CacheService {
constructor(
@InjectRedis()
private readonly redis: Redis,
private readonly logger: LoggerService,
) {}

async readCached<T>(key: string) {
try {
const value = await this.redis.get(key);

if (value) {
this.logger.log(`Cache hit for key: ${key}`);
return JSON.parse(value) as T;
} else {
this.logger.warn(`Cache miss for key: ${key}`);
}
return;
} catch (error) {
this.logger.error(`Error reading from cache: ${key}`);
}
}

async writeCached(key: string, obj: any, exp: number = config.REDIS_EXP) {
try {
await this.redis.set(key, JSON.stringify(obj), 'EX', exp);
this.logger.log(
`Cache set for key: ${key} with expiration of ${exp} seconds`,
);
} catch (error) {
this.logger.error(`Error writing to cache for key: ${key}`);
}
}

async invalidateCached(key: string) {
try {
await this.redis.del(key);
this.logger.log(`Cache invalidated for key: ${key}`);
} catch (error) {
this.logger.error(`Error deleting from cache for key: ${key}`);
}
}

async invalidateCachedPattern(pattern: string) {
const keys = await this.redis.keys(pattern);
if (keys.length > 0) {
await this.redis.del(keys);
}
}
}
19 changes: 19 additions & 0 deletions src/infrastructure/decorators/user.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { randomUUID } from 'node:crypto';

import { User as UserI } from '../../modules/users/domain/user.domain';

export const User = createParamDecorator(
(data: unknown, ctx: ExecutionContext): UserI => {
const request = ctx.switchToHttp().getRequest();

// Simulamos un usuario logueado creando un mock de los datos del usuario.
// En una aplicación real, esto sería gestionado por Passport u otro sistema de autenticación.
request.user = new UserI({
email: '[email protected]',
id: randomUUID(),
});

return request.user;
},
);
28 changes: 28 additions & 0 deletions src/infrastructure/firebase/firebase.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Injectable } from '@nestjs/common';
import * as admin from 'firebase-admin';

import { config } from '../../config/envs';

@Injectable()
export class FirebaseConfig {
constructor() {
const firebaseConfig = {
projectId: config.FIREBASE_PROJECT_ID,
privateKey: config.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
clientEmail: config.FIREBASE_CLIENT_EMAIL,
};

admin.initializeApp({
credential: admin.credential.cert(firebaseConfig),
storageBucket: `${firebaseConfig.projectId}.appspot.com`,
});
}

getStorage() {
return admin.storage();
}

getBucket() {
return admin.storage().bucket();
}
}
31 changes: 31 additions & 0 deletions src/infrastructure/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class JwtMockGuard implements CanActivate {
constructor(private readonly jwtService: JwtService) {}

canActivate(context: ExecutionContext): boolean {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const request = context.switchToHttp().getRequest();

/*
const authHeader = request.headers.authorization;
if (!authHeader) {
return false;
}

const token = authHeader.split(' ')[1];
try {
const decoded = this.jwtService.verify(token);
request.user = decoded;
return true;
} catch (error) {
return false;
}
*/

// Mock para simular que el guard siempre permite el acceso
return true;
}
}
34 changes: 34 additions & 0 deletions src/infrastructure/loggers/logger.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Injectable, Logger } from '@nestjs/common';

export interface LoggerServiceI {
log(message: string): void;
error(message: string): void;
warn(message: string): void;
}

@Injectable()
export class LoggerService extends Logger implements LoggerServiceI {
constructor() {
super();
// Aquí puedes inicializar la conexión a un sistema externo de logging,
// como AWS CloudWatch, Elasticsearch, o cualquier otra plataforma de logs.
// O implementar un repositorio para guárdalos en una base de datos si se desea.
}

private formatMessage(message: string): string {
const timestamp = new Date().toISOString();
return `[${timestamp}] ${message}`;
}

log(message: string): void {
super.log(this.formatMessage(message));
}

error(message: string): void {
super.error(this.formatMessage(message));
}

warn(message: string): void {
super.warn(this.formatMessage(message));
}
}
19 changes: 19 additions & 0 deletions src/infrastructure/typeorm/typeorm.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { DataSource, DataSourceOptions } from 'typeorm';
import { TypeOrmModuleOptions } from '@nestjs/typeorm';

import { config } from '../../config/envs';

export const getTypeOrmModuleOptions = (): TypeOrmModuleOptions =>
({
type: 'postgres',
host: config.DB_HOST,
port: config.DB_PORT,
database: config.DB_NAME,
username: config.DB_USER,
password: config.DB_PASSWORD,
entities: [__dirname + './../../**/*.entity{.ts,.js}'],
synchronize: config.DB_SYNCHRONIZE,
migrations: [__dirname + '/migrations/**/*{.ts,.js}'],
}) as TypeOrmModuleOptions;

export default new DataSource(getTypeOrmModuleOptions() as DataSourceOptions);
13 changes: 13 additions & 0 deletions src/infrastructure/typeorm/typeorm.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

import { getTypeOrmModuleOptions } from './typeorm.config';

@Module({
imports: [
TypeOrmModule.forRoot({
...getTypeOrmModuleOptions(),
}),
],
})
export class TypeormModule {}
Loading