Skip to content
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
1 change: 1 addition & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ jobs:
REFRESH_EXPIRE: 7d
RESET_SECRET: secret3
RESET_EXPIRE: 15m
REDIS_URL: redis://localhost:6379

steps:
- name: Checkout repository
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ dist
*.sqlite
*.todo
insomnia-collection-complete.json
TODO.md
TODO.md
coverage
12 changes: 11 additions & 1 deletion docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,14 @@ services:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
volumes:
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
- ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql
redis:
image: redis:latest
container_name: payment_records_redis
ports:
- "6379:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
8 changes: 8 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,12 @@ module.exports = {
transform: {
"^.+\\.(t|j)sx?$": ["ts-jest", { useESM: true }],
},
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
}
};
1,107 changes: 608 additions & 499 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"nodemailer": "^7.0.6",
"pg": "^8.16.3",
"pg-query-stream": "^4.10.3",
"redis": "^5.10.0",
"reflect-metadata": "^0.2.2",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.1",
Expand Down Expand Up @@ -58,4 +59,4 @@
"overrides": {
"validator": "13.12.0"
}
}
}
13 changes: 10 additions & 3 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ import { UserRouter } from "@modules/User/user.routes";
import { BankRouter } from "@modules/Bank/bank.routes";
import { AccountRouter } from "@modules/Account/account.routes";
import { TransactionRouter } from "@modules/Transaction/transaction.routes";
import { redisRouter } from "@modules/redis/redis.routes";
import { loggerMiddleware } from "@middlewares/loggger.middleware";
import cors from "cors";
import { runSeeds } from "@shared/seeds";
import { env } from "@shared/env";
import swaggerUi from "swagger-ui-express"
import docs from "docs/swagger";
import * as dotenv from "dotenv";
import { redisClient } from "@modules/redis/redis.config";

dotenv.config();

Expand All @@ -31,12 +34,14 @@ app.use(

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(loggerMiddleware);
app.use("/auth", AuthRouter);
app.use("/user", UserRouter);
app.use("/bank", BankRouter);
app.use("/account", AccountRouter);
app.use("/transaction", TransactionRouter);
app.use("/api", swaggerUi.serve, swaggerUi.setup(docs));
app.use("/redis", redisRouter);
app.use(ErrorHandler.handle.bind(ErrorHandler));

app.get("/health", (_req, res) => {
Expand All @@ -46,9 +51,11 @@ app.get("/health", (_req, res) => {

AppDataSource.initialize()
.then(() => {
app.listen(port, async () => {
await runSeeds();
});
redisClient.connect().then(() => {
app.listen(port, async () => {
await runSeeds();
});
})
})
.catch((err) => {
console.error("Error during Data Source initialization", err);
Expand Down
4 changes: 4 additions & 0 deletions src/core/interfaces/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface Logger{
store(key: string, value: object): void;
get(key: string): object | null;
}
5 changes: 5 additions & 0 deletions src/lib/enums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,8 @@ export const ErrorEnum = {
ACCOUNT_BLOCKED: { message: "Account Blocked", status: 403 },
MISSING_PROPERTIES: { message: "Missing Required Properties", status: 400 },
} as const;

export enum Role{
USER,
ADMIN
}
2 changes: 2 additions & 0 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import nodemailer from "nodemailer"
import { Role } from "./enums";

/**
* @swagger
Expand Down Expand Up @@ -34,6 +35,7 @@ export type MailOptions = nodemailer.SendMailOptions;
export type AccessPayload = {
email: string
id: string
role: Role
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/middlewares/jwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,4 @@ export function validateToken(req: Request, res: Response, next: NextFunction) {
});
}
}

23 changes: 23 additions & 0 deletions src/middlewares/loggger.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { RedisService } from "@modules/redis/redis.service";
import { Request, Response, NextFunction } from "express";
import { redisClient } from "@modules/redis/redis.config";

export const redisService = new RedisService(redisClient);

export function loggerMiddleware(req: Request, res: Response, next: NextFunction){
const timestamp = new Date().toISOString();
const {method, url, params, query, host, hostname, httpVersion,ip} = req;
console.log(`[${timestamp}] ${method} ${url} - ${ip}`);
redisService.store(timestamp, {
method,
url,
params,
query,
host,
hostname,
httpVersion,
ip
})

next();
};
11 changes: 7 additions & 4 deletions src/modules/Auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,20 @@ export class AuthService {

async register(createUserDTO: CreateUserDto): Promise<User> {
const isAlreadyRegistered = await this.authRepository.findOne({ where: { email: createUserDTO.email } });

if (isAlreadyRegistered) {
console.error("Usuário já existe:", isAlreadyRegistered);
throw new Error(ErrorEnum.USER_ALREADY_EXISTS.message);
}

const password_digest = await hashPassword(createUserDTO.password);
const user = await this.authRepository.save({...createUserDTO, password: password_digest });
await this.emailService.send({
this.emailService.send({
to: user.email,
subject: "Welcome to Payment Records",
from: process.env.EMAIL_USER,
html: welcomeTemplate(user.name)
})
console.debug("Mensagem enviada");
return user;
}

Expand All @@ -47,12 +49,13 @@ export class AuthService {
const access_token = jwt.sign(
{
email: user.email,
id: user.id
sub: user.id,
role: user.role
}, env.ACCESS_SECRET,
{ expiresIn: env.ACCESS_EXPIRE as number })

const refresh_token = jwt.sign({
id: user.id
sub: user.id
}, env.REFRESH_SECRET,
{
expiresIn: env.REFRESH_EXPIRE as number
Expand Down
4 changes: 4 additions & 0 deletions src/modules/User/entity/user.entity.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { Account } from "@modules/Account/entity/account.entity";
import { Role as RoleEnum } from "@lib/enums";

@Entity("users")
export class User {
Expand All @@ -18,6 +19,9 @@ export class User {
@Column("int", { nullable: false })
age: number;

@Column("enum", {enum: RoleEnum, default: RoleEnum.USER})
role: RoleEnum;

@OneToMany(() => Account, (account) => account.user)
accounts: Account[];
}
6 changes: 6 additions & 0 deletions src/modules/redis/redis.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {createClient} from 'redis'
import { env } from '@shared/env'

export const redisClient = createClient({
url: env.REDIS_URL
})
8 changes: 8 additions & 0 deletions src/modules/redis/redis.factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { RedisService } from "./redis.service";
import { redisClient } from "./redis.config";

export class RedisFactory {
public static createController(){
return new RedisService(redisClient);
}
}
28 changes: 28 additions & 0 deletions src/modules/redis/redis.routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Router } from "express";
import { RedisFactory } from "./redis.factory";
import { Request, Response } from "express";
import { validateToken } from "@middlewares/jwt";
import { Role as RoleEnum } from "@lib/enums";

export const redisRouter = Router();

// Here i don't want to expose the store method
// The store is a internal method that should be used by other services, not by external clients

redisRouter.get("/", validateToken, async (req: Request, res: Response) => {
const role = req.data?.role;
if(role !== RoleEnum.ADMIN) return res.status(403).json({message: "Forbidden - Admins only"});

const data = await RedisFactory.createController().getAll();
return res.status(200).json({data});
})

redisRouter.get("/:key", validateToken, async (req: Request, res: Response) => {
const {key} = req.params;
const role = req.data?.role;
if(role !== RoleEnum.ADMIN) return res.status(403).json({message: "Forbidden - Admins only"});

const data = await RedisFactory.createController().get(key);
if(!data) return res.status(404).json({message: "Key not found"});
return res.status(200).json({data});
})
30 changes: 30 additions & 0 deletions src/modules/redis/redis.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { redisClient as CreateClient } from "./redis.config";
import { Logger } from "@core/interfaces/logger";
export class RedisService implements Logger{
constructor(private readonly client:typeof CreateClient){}

store(key: string, value: object){
return this.client.set(key, JSON.stringify(value))
}

async get(key: string){
const data = await this.client.get(key);

if(!data) return null;

return JSON.parse(data);
}

async getAll(){
const keys = await this.client.keys("*");
const allData = {};

for(const key of keys){
const data = await this.client.get(key);
if(!data) continue;
allData[key] = JSON.parse(data);
}

return allData
}
}
2 changes: 1 addition & 1 deletion src/shared/db/data-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const AppDataSource = new typeorm.DataSource({
username: env.DB_USERNAME,
password: env.DB_PASSWORD,
synchronize: true,
logging: true,
logging: false,
entities: [User, Bank, Transaction, Account],
subscribers: [],
migrations: [],
Expand Down
2 changes: 2 additions & 0 deletions src/shared/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const envSchema = z.object(
RESET_SECRET: z.string(),
RESET_EXPIRE: z.string().or(z.number()),
FRONTEND_URL: z.url(),

REDIS_URL: z.string()
},
{ error: "Missing variables in env file" }
);
Expand Down
2 changes: 1 addition & 1 deletion src/tests/integration/account.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Account } from '@modules/Account/entity/account.entity';
import { User } from '@modules/User/entity/user.entity';
import { Bank } from '@modules/Bank/entity/bank.entity';
import { Repository } from 'typeorm';
import { TestAppDataSource as dataSource } from './db';
import { TestAppDataSource as dataSource } from './postgres-db';
import { BankService } from '@modules/Bank/bank.service';
import { generateRandomUser, generateRandomBank, generateRandomAccount, getRandomFromArray } from '../../lib/utils';
import { AuthService } from '@modules/Auth/auth.service';
Expand Down
2 changes: 1 addition & 1 deletion src/tests/integration/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Email } from "@core/abstractions/email";
import { AuthService } from "@modules/Auth/auth.service";
import { User } from "@modules/User/entity/user.entity";
import { TestAppDataSource as dataSource } from "./db";
import { TestAppDataSource as dataSource } from "./postgres-db";
import { MailOptions } from "@lib/types";
import { CreateUserDto } from "@modules/Auth/dto/create-user.dto";

Expand Down
2 changes: 1 addition & 1 deletion src/tests/integration/bank.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BankService } from '@modules/Bank/bank.service';
import { Bank } from '@modules/Bank/entity/bank.entity';
import { Repository } from 'typeorm';
import { ErrorEnum } from '@lib/enums';
import { TestAppDataSource as dataSource } from './db';
import { TestAppDataSource as dataSource } from './postgres-db';

describe('BankService', () => {
let bankService: BankService;
Expand Down
File renamed without changes.
47 changes: 47 additions & 0 deletions src/tests/integration/redis.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { RedisService } from "@modules/redis/redis.service";
import { Request } from "express";
import { createClient } from "redis";
import { redisClient as Client } from "@modules/redis/redis.config";

describe("RedisService Integration Tests", () => {
let redisService: RedisService;
let client: typeof Client;

beforeAll(async () => {
client = createClient({
url: "redis://localhost:6379"
});

client.on("error", (err) => console.error("Redis Client Error", err));

await client.connect();

redisService = new RedisService(client);
})

afterAll(async () => {
await client.quit();
})

test("Store and Retrieve Data", async () => {
const timestamp = new Date();

const mockRequest: Partial<Request> = {
method: "GET",
url: "/test",
params: {},
query: {},
host: "localhost",
hostname: "localhost",
httpVersion: "1.1",
ip: "127.0.0.1"
}


await redisService.store(timestamp.toISOString(), mockRequest);

const retrieveData = await redisService.get(timestamp.toISOString());

expect(retrieveData).toEqual(mockRequest);
})
})
Loading