Skip to content

Commit 34dc2c8

Browse files
Ported all backend to TS
Builds without issues and works perfectly with the existing frontend.
1 parent 8255bdd commit 34dc2c8

File tree

9 files changed

+82
-76
lines changed

9 files changed

+82
-76
lines changed

index.ts

+3-6
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,12 @@ app.get("/authed", (request: Request, response: Response) => {
3939
import inv from "./src/routes/invoices";
4040
app.use('/invoices', inv);
4141

42-
/*
42+
import products from "./src/routes/products";
43+
app.use('/products', products);
4344

44-
var clients = require('./src/routes/clients.js');
45+
import clients from "./src/routes/clients";
4546
app.use('/clients', clients);
4647

47-
var products = require('./src/routes/products.js');
48-
app.use('/products', products); */
49-
5048
//Internal function for hashing passwords.
5149
/*
5250
app.post("/pass", async (request, response) => {
@@ -68,7 +66,6 @@ app.post("/pass", async (request, response) => {
6866
});*/
6967

7068

71-
7269
//Error Handler
7370
const jsonErrorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
7471
console.log("Error: ", err);

src/middleware/auth.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import express, { Express, Request, Response, NextFunction } from "express";
2-
import bcrypt from "bcrypt";
1+
import {Request, Response, NextFunction } from "express";
32
import jwt, { VerifyOptions } from "jsonwebtoken"
43
import dbConn from "../db/connection";
54
import { RowDataPacket } from "mysql2";

src/routes/clients.js src/routes/clients.ts

+18-21
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,48 @@
1-
var express = require('express');
2-
var router = express.Router();
3-
1+
import express, { Express, Request, Response, NextFunction } from "express";
2+
import { RowDataPacket } from "mysql2";
3+
import dbConn from "../db/connection";
4+
import { Client } from "../types/clients";
5+
const router = express.Router();
46

57
//Routes will go here
6-
module.exports = router;
8+
export default router;
79

8-
router.get('/', async function (req, res, next) {
9-
if(req.user.isClient){
10+
router.get('/', async function (req: Request, res: Response, next: NextFunction) {
11+
if(req.user!.isClient){
1012
res.status(403).send({ error: 'User isn\'t allowed to make this action' });
1113
return;
1214
}
1315

1416
try {
15-
const con = require('../db/connection.js')().promise();
17+
const con = dbConn().promise();
1618

1719
let baseQuery = "SELECT clients.user_email, clients.name, MIN(invoices.date) AS oldest_invoice_date, MAX(total_amount) AS most_expensive_invoice_total FROM clients LEFT JOIN (\
1820
SELECT invoices.client_email, invoices.id, SUM((invoices_products.unit_price * invoices_products.quantity) * (1 - (invoices.discount / 100))) AS total_amount FROM invoices\
1921
LEFT JOIN invoices_products ON invoices.id = invoices_products.invoice_id GROUP BY invoices.id ) AS invoice_totals ON clients.user_email = invoice_totals.client_email LEFT JOIN\
2022
invoices ON invoice_totals.id = invoices.id GROUP BY clients.user_email";
2123

2224
try {
23-
const [rows] = await con.query(baseQuery);
24-
25-
console.log("Result: ", rows);
26-
27-
const clients = [];
28-
29-
25+
const [rows] = await con.query<RowDataPacket[]>(baseQuery);
26+
const clients: Client[] = [];
3027

3128
rows.forEach(row => {
3229
let allowedDiscount = 0;
3330

34-
if(row.most_expensive_invoice_total!=null){
35-
if(row.most_expensive_invoice_total > 2000)
31+
if(row['most_expensive_invoice_total']!=null){
32+
if(row['most_expensive_invoice_total'] > 2000)
3633
allowedDiscount = 45;
37-
if(row.most_expensive_invoice_total < 1000)
34+
if(row['most_expensive_invoice_total'] < 1000)
3835
allowedDiscount = 10;
3936
}
4037

41-
let dateDif = new Date(Date.now() - (row.oldest_invoice_date == null ? Date.now() : row.oldest_invoice_date.getTime())).getUTCFullYear() - 1970; //restamos la unix timestamp de hoy y la de la fecha de la compra mas vieja. Eso nos da la diferencia de años + 1970
38+
let dateDif = new Date(Date.now() - (row['oldest_invoice_date'] == null ? Date.now() : row['oldest_invoice_date'].getTime())).getUTCFullYear() - 1970; //restamos la unix timestamp de hoy y la de la fecha de la compra mas vieja. Eso nos da la diferencia de años + 1970
4239

4340
if(dateDif>=3)
4441
allowedDiscount = 30;
4542

4643
clients.push({
47-
email : row.user_email,
48-
name : row.name,
44+
email : row['user_email'],
45+
name : row['name'],
4946
allowedDiscount : allowedDiscount
5047
});
5148
});
@@ -55,7 +52,7 @@ SELECT invoices.client_email, invoices.id, SUM((invoices_products.unit_price * i
5552
console.log(error);
5653
res.status(500).send({error:"Internal Server Error"});
5754
} finally {
58-
con.close();
55+
con.end();
5956
}
6057

6158
} catch (error) {

src/routes/products.js

-43
This file was deleted.

src/routes/products.ts

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import express, { Express, Request, Response, NextFunction } from "express";
2+
import { Product } from "../types/product";
3+
import { RowDataPacket } from "mysql2";
4+
import dbConn from "../db/connection";
5+
const router = express.Router();
6+
7+
8+
//Routes will go here
9+
export default router;
10+
11+
router.get('/', async function (req: Request, res: Response, next: NextFunction) {
12+
if(req.user!.isClient){
13+
res.status(403).send({ error: 'User isn\'t allowed to make this action' });
14+
return;
15+
}
16+
17+
try {
18+
const con = dbConn().promise();
19+
20+
let baseQuery = "SELECT * FROM products";
21+
22+
try {
23+
const [rows] = await con.query<RowDataPacket[]>(baseQuery);
24+
console.log("Result: ", rows);
25+
const products: Product[] = [];
26+
rows.forEach(row => {
27+
products.push({
28+
id : row['id'],
29+
name : row['name'],
30+
price : row['price']
31+
});
32+
});
33+
34+
res.status(200).send(products);
35+
} catch (error) {
36+
console.log(error);
37+
res.status(500).send({error:"Internal Server Error"});
38+
} finally {
39+
con.end();
40+
}
41+
42+
} catch (error) {
43+
next(error);
44+
return;
45+
}
46+
});

src/types/clients.ts

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export type Client = {
2+
email : string,
3+
name : string,
4+
allowedDiscount : number
5+
}

src/types/invoice.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { InvoiceProduct } from "./product"
1+
import { InvoiceProduct } from "./invoiceproduct"
22

33
export type Invoice = {
44
id: number,

src/types/invoiceproduct.ts

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export type InvoiceProduct = {
2+
id: number,
3+
quantity: number,
4+
unitPrice: number,
5+
name: string
6+
}

src/types/product.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
export type InvoiceProduct = {
1+
export type Product = {
22
id: number,
3-
quantity: number,
4-
unitPrice: number,
3+
price: number,
54
name: string
65
}

0 commit comments

Comments
 (0)