-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathitem.js
More file actions
166 lines (144 loc) · 5.26 KB
/
item.js
File metadata and controls
166 lines (144 loc) · 5.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import fs from 'fs';
import csv from 'csv-express';
import express from 'express';
import multer from 'multer';
import parse from 'csv-parse';
let router = express.Router();
import models from '../models';
import { verifyJwt, authenticate } from "../utils/jwt";
import { itemPayload, csvItems } from "../utils/build-payload";
import { unitConversion } from '../utils/dictionary';
router.get('/export', authenticate, async (req, res) => {
const { id: userId } = req.user;
try {
const items = await models.Item.findAll({
where: { userId },
include: [{ model: models.Category, as: 'Category', attributes: ['name'] }]
});
res.csv(csvItems(items), true);
} catch (e) {
res.status(400).json(e);
}
});
const upload = multer({ dest: 'uploads/' });
router.post('/upload', upload.single('file'), authenticate, async (req, res) => {
const content = await fs.readFileSync(req.file.path, { encoding: 'utf8' });
parse(content, {
columns: true,
skip_empty_lines: true,
skip_lines_with_error: true,
trim: true,
}, (err, output) => {
if (err) return res.json(err);
const disallowedKeys = ['id', 'categoryId', 'userId', 'createdAt', 'updatedAt'];
// convert csv headers into database field names
const items = output.map(item => {
const sanitized = {};
for (let [key, value] of Object.entries(item)) {
const formattedKey = key.replace(' ', '_').toLowerCase();
if (!formattedKey || disallowedKeys.includes(formattedKey)) {
continue;
}
if (formattedKey === 'weight' || formattedKey === 'price') {
value = parseFloat(value);
value = !isNaN(value) ? value : 0;
}
if (formattedKey === 'weight_unit' && value) {
const unit = unitConversion(value);
value = unit || req.user.default_weight_unit;
}
sanitized[formattedKey] = value;
}
// set default category to "Unspecified", add user id
return { ...sanitized, categoryId: 1, userId: req.user.id };
});
models.Item.bulkCreate(items, { returning: true })
.then(items => res.json(items))
.catch(err => res.status(400).json(err));
});
});
// Get by userId or authenticated user
router.get('', async (req, res) => {
let { userId } = req.query;
if (!userId) {
try {
const user = await verifyJwt(req);
userId = user.id;
} catch (e) {
return res.sendStatus(401);
}
}
models.Item.findAll({
where: { userId },
include: [{ model: models.Category, as: 'Category', attributes: ['id', 'name', 'level', 'exclude_weight'] }]
})
.then(items => res.json(items))
.catch(err => res.json(err));
});
// create or retrieve category
async function fetchCategory(categoryId, excludeWeight) {
let newCat = null;
const category = { name: categoryId, level: 'USER', exclude_weight: excludeWeight };
try {
newCat = await models.Category.create(category);
} catch (err) {
try {
newCat = await models.Category.findOne({ where: { name: categoryId } });
} catch (err) {
return { newCat: null, err };
}
}
return { category: newCat, err: null };
}
// Create
router.post('', authenticate, async (req, res) => {
const { newCategory, excludeWeight } = req.body;
const { payload } = itemPayload(req.body);
let newCat = null;
if (newCategory) {
const { category, err } = await fetchCategory(payload.categoryId, excludeWeight);
if (err) {
return res.status(400).json(err);
}
newCat = category;
}
let data = { ...payload, userId: req.user.id };
data = newCat ? { ...data, categoryId: newCat.id } : data;
models.Item.create(data)
.then(item => res.json(item))
.catch(err => res.status(400).json(err));
});
// Update
router.put('', authenticate, async (req, res) => {
const { newCategory } = req.body;
const { id, payload } = itemPayload(req.body);
let newCat = null;
if (newCategory) {
// hardcoding false here while I figure out how to do update
const { category, err } = await fetchCategory(payload.categoryId, false);
if (err) {
return res.status(400).json(err);
}
newCat = category;
}
const data = !newCat ? { ...payload } : { ...payload, categoryId: newCat.id };
models.Item.update(data, {
returning: true,
where: { id, userId: req.user.id }
})
.then(([rowsUpdated, [updatedItem]]) => {
if (!rowsUpdated) {
return res.status(400).json({ error: 'Item not found.' })
}
return res.json(updatedItem)
})
.catch(err => res.status(400).json(err));
});
// Delete
router.post('/delete', authenticate, (req, res) => {
const { itemId } = req.body;
models.Item.destroy({ where: { id: itemId, userId: req.user.id } })
.then(rowsUpdated => res.json(rowsUpdated))
.catch(err => res.status(400).json(err))
});
module.exports = router;