Skip to content

Commit d6042a1

Browse files
author
Victor Badaró
authored
Merge pull request #2 from victorbadaro/feature/crud-products
Methods to find, create, update and delete products
2 parents 5847d21 + 25dacc6 commit d6042a1

4 files changed

Lines changed: 181 additions & 0 deletions

File tree

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import Product from "../models/Product";
2+
import User from "../models/User";
3+
4+
class ProductController {
5+
async index(request, response) {
6+
const products = await Product.find();
7+
8+
return response.json(products);
9+
}
10+
11+
async find(request, response) {
12+
const { id } = request.params;
13+
const result = await Product.find({ where: { id } });
14+
const product = result[0];
15+
16+
if (!product)
17+
return response.status(400).json({ erro: 'Product not found!' });
18+
19+
return response.json(product);
20+
}
21+
22+
async create(request, response) {
23+
const { description, user_id } = request.body;
24+
25+
if (!description)
26+
return response.status(400).json({ error: 'Product description can\'t be null' });
27+
28+
if (user_id === null)
29+
return response.status(400).json({ error: 'User ID can\'t be null' });
30+
31+
const result = await User.find({ where: { id: user_id } });
32+
const user = result[0];
33+
34+
if (!user)
35+
return response.status(400).json({ erro: 'User not found!' });
36+
37+
const product = await Product.create({ description, user_id });
38+
39+
return response.status(201).json(product);
40+
}
41+
42+
async update(request, response) {
43+
const { id } = request.params;
44+
const { description } = request.body;
45+
const result = await Product.find({ where: { id } });
46+
const product = result[0];
47+
48+
if (!product)
49+
return response.status(400).json({ error: 'Product not found!' });
50+
51+
if (!description)
52+
return response.status(400).json({ error: 'Product description can\'t be null' });
53+
54+
await Product.update({ description }, { where: { id } });
55+
56+
return response.status(204).send();
57+
}
58+
59+
async delete(request, response) {
60+
const { id } = request.params;
61+
const result = await Product.find({ where: { id } });
62+
const product = result[0];
63+
64+
if (!product)
65+
return response.status(400).json({ error: 'Product not found!' });
66+
67+
await Product.delete({ where: { id } });
68+
return response.status(204).send();
69+
}
70+
}
71+
72+
export default new ProductController();

src/models/Product.js

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import { connection as database } from '../config/database';
2+
3+
class Product {
4+
async find(filters) {
5+
let query = 'SELECT * FROM products';
6+
7+
if (filters)
8+
Object.keys(filters).forEach(filter => {
9+
query += ` ${filter}`;
10+
11+
Object.keys(filters[filter]).forEach(field => {
12+
if (filters[filter][field] !== null)
13+
query += ` ${field} = '${filters[filter][field]}'`;
14+
else
15+
query += ` ${field} = null`;
16+
});
17+
});
18+
19+
const result = await database.query(query);
20+
const products = result.rows;
21+
22+
return products;
23+
}
24+
25+
async create(data) {
26+
const fields = [];
27+
const values = [];
28+
29+
Object.keys(data).forEach(field => {
30+
fields.push(field);
31+
32+
if (data[field] !== null) {
33+
if (Array.isArray(data[field])) {
34+
const newArray = data[field].map(item => `'${item}'`);
35+
36+
values.push(`ARRAY[${newArray}]`);
37+
} else
38+
values.push(`'${data[field]}'`);
39+
} else
40+
values.push('null');
41+
});
42+
43+
const query = `INSERT INTO products (${fields.join(', ')}) VALUES (${values.join(', ')}) RETURNING *`;
44+
const result = await database.query(query);
45+
const user = result.rows[0];
46+
47+
return user;
48+
}
49+
50+
async update(data, filters) {
51+
const fieldsToUpdate = [];
52+
53+
Object.keys(data).forEach(field => {
54+
fieldsToUpdate.push(`${field} = '${data[field]}'`);
55+
});
56+
57+
let query = `UPDATE products SET ${fieldsToUpdate.join(', ')}`;
58+
59+
if (filters)
60+
Object.keys(filters).forEach(filter => {
61+
query += ` ${filter.toUpperCase()}`;
62+
63+
Object.keys(filters[filter]).forEach(field => {
64+
if (filters[filter][field] !== null)
65+
query += ` ${field} = '${filters[filter][field]}'`;
66+
else
67+
query += ` ${field} = null`;
68+
});
69+
});
70+
71+
await database.query(query);
72+
return;
73+
}
74+
75+
async delete(filters) {
76+
let query = 'DELETE FROM products';
77+
78+
if (filters)
79+
Object.keys(filters).forEach(filter => {
80+
query += ` ${filter.toUpperCase()}`;
81+
82+
Object.keys(filters[filter]).forEach(field => {
83+
if (filters[filter][field] !== null)
84+
query += ` ${field} = '${filters[filter][field]}'`;
85+
else
86+
query += ` ${field} = null`;
87+
});
88+
});
89+
90+
await database.query(query);
91+
return;
92+
}
93+
}
94+
95+
export default new Product();

src/routes/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import { Router } from 'express';
22
import { router as usersRouter } from './usersRoutes';
3+
import { router as productsRouter } from './productsRoutes';
34

45
const router = Router();
56

67
router.use('/users', usersRouter);
8+
router.use('/products', productsRouter);
79

810
export { router };

src/routes/productsRoutes.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { Router } from 'express';
2+
import ProductController from '../controllers/ProductController';
3+
4+
const router = Router();
5+
6+
router.get('/', ProductController.index);
7+
router.post('/', ProductController.create);
8+
router.get('/:id', ProductController.find);
9+
router.put('/:id', ProductController.update);
10+
router.delete('/:id', ProductController.delete);
11+
12+
export { router };

0 commit comments

Comments
 (0)