Skip to content

Commit 88171a6

Browse files
committed
refactor: Added decorators
1 parent ad5c6cf commit 88171a6

File tree

5 files changed

+331
-359
lines changed

5 files changed

+331
-359
lines changed

src/routes/item/catalyze.ts

Lines changed: 82 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1+
// routes/item/catalize.ts
2+
13
import express, { Request, Response, NextFunction } from 'express';
4+
import { param, validationResult } from 'express-validator';
25
import logger from '../../logger';
3-
import Item from '../../models/Item';
4-
import Satchel from '../../models/Satchel';
5-
import { consumePA, getPA } from '../../redis/redisUtils';
66

7+
import { fetchItemMiddleware, assertItemPresent } from '../../middlewares/fetch-item';
8+
import { fetchSatchelMiddleware, assertSatchelPresent} from '../../middlewares/fetch-satchel';
9+
10+
import { consumePA, getPA } from '../../redis/redisUtils';
711
import { ITEM_RARITIES } from '../../globals';
812

913
const router = express.Router();
@@ -14,112 +18,91 @@ function asyncHandler(fn: (req: Request, res: Response, next: NextFunction) => P
1418
};
1519
}
1620

17-
router.post('/:uuid/catalyze', asyncHandler(async (req: Request, res: Response) => {
18-
logger.info(`POST /${req.params.uuid}/catalyze`);
19-
20-
const { uuid } = req.params;
21+
router.post(
22+
'/:item_uuid/catalyze',
23+
[
24+
param('item_uuid')
25+
.isUUID(4)
26+
.withMessage('Invalid UUID format'),
27+
],
28+
asyncHandler(fetchItemMiddleware),
29+
asyncHandler(fetchSatchelMiddleware),
30+
asyncHandler(async (req: Request, res: Response) => {
31+
// Check validation result
32+
const errors = validationResult(req);
33+
if (!errors.isEmpty()) {
34+
return res.status(400).json({ errors: errors.array() });
35+
}
2136

22-
// We look for the related Item
23-
const item = await Item.findById(uuid).exec();
24-
if (!item) {
25-
logger.warn(`Item.id:${uuid} not found`);
26-
return res.status(200).json({
27-
success: false,
28-
msg: `Item.id:${uuid} not found`,
29-
payload: null
30-
});
31-
} else {
32-
logger.debug(`Item.id:${uuid} found`);
33-
}
37+
const { item_uuid } = req.params;
38+
logger.info(`POST /${item_uuid}/catalyze`);
3439

35-
// We look for the related Satchel (Item.bearer)
36-
const satchel = await Satchel.findById(item.bearer).exec();
37-
if (!satchel) {
38-
logger.warn(`Satchel.id:${uuid} not found`);
39-
return res.status(200).json({
40-
success: false,
41-
msg: `Satchel.id:${uuid} not found`,
42-
payload: null
43-
});
44-
} else {
45-
logger.debug(`Satchel.id:${uuid} found`);
46-
}
40+
// We check middleware functions didn't screw up
41+
assertItemPresent(req)
42+
assertSatchelPresent(req)
4743

48-
// Find index of current item rarity and get next rarity
49-
const rarityIndex = ITEM_RARITIES.indexOf(item.rarity);
50-
if (rarityIndex === -1 || rarityIndex === ITEM_RARITIES.length - 1) {
51-
// Current rarity not found or already at max rarity
52-
const msg = `Item rarity '${item.rarity}' is invalid or at max level.`;
53-
logger.warn(msg);
54-
return res.status(200).json({
55-
success: false,
56-
msg: msg,
57-
payload: null
58-
});
59-
}
60-
const nextRarity = ITEM_RARITIES[rarityIndex + 1];
61-
const nextRarityKey = nextRarity.toLowerCase();
44+
// Find index of current item rarity and get next rarity
45+
const rarityIndex = ITEM_RARITIES.indexOf(req.item.rarity);
46+
if (rarityIndex === -1 || rarityIndex === ITEM_RARITIES.length - 1) {
47+
// Current rarity not found or already at max rarity
48+
const msg = `Item rarity '${req.item.rarity}' is invalid or at max level.`;
49+
logger.warn(msg);
50+
return res.status(200).json({ success: false, msg: msg, payload: null });
51+
}
52+
const nextRarity = ITEM_RARITIES[rarityIndex + 1];
53+
const nextRarityKey = nextRarity.toLowerCase();
6254

63-
// We check that there is enough shards
64-
if (satchel.shard[nextRarityKey] < 10) {
65-
logger.warn(`Satchel.id:${satchel.id} not enough shard.${nextRarityKey}`);
66-
return res.status(200).json({
67-
success: false,
68-
msg: `Satchel.id:${satchel.id} not enough shard.${nextRarityKey}`,
69-
payload: null
70-
});
71-
} else {
72-
logger.debug(`Satchel.id:${satchel.id} enough shard.${nextRarityKey}`);
73-
}
55+
// We check that there is enough shards
56+
if (req.satchel.shard[nextRarityKey] < 10) {
57+
const msg = `Satchel.id:${req.satchel.id} not enough shard.${nextRarityKey}`
58+
logger.warn(msg);
59+
return res.status(200).json({ success: false, msg: msg, payload: null });
60+
} else {
61+
logger.verbose(`Satchel.id:${req.satchel.id} enough shard.${nextRarityKey}`);
62+
}
7463

75-
// Update Item
76-
try {
77-
item.rarity = nextRarity;
78-
item.updated = new Date();
79-
await item.save();
80-
} catch (err) {
81-
logger.error(`Item.id:${uuid} Unable to UPDATE: ${err}`)
82-
}
64+
// Update Item
65+
try {
66+
req.item.rarity = nextRarity;
67+
req.item.updated = new Date();
68+
await req.item.save();
69+
} catch (err) {
70+
logger.error(`Item.id:${item_uuid} Unable to UPDATE: ${err}`)
71+
}
8372

84-
// Update Satchel amount
85-
try {
86-
// Decrement shard count by 10
87-
if (typeof satchel.shard[nextRarityKey] === 'number') {
88-
satchel.shard[nextRarityKey] -= 10;
73+
// Update Satchel amount
74+
try {
75+
req.satchel.shard[nextRarityKey] -= 10;
76+
req.satchel.updated = new Date();
77+
await req.satchel.save();
78+
} catch (err) {
79+
logger.error(`Satchel.id:${req.satchel.id} Unable to UPDATE: ${err}`)
80+
}
8981

90-
// Optional: ensure it doesn't go below zero
91-
if (satchel.shard[nextRarityKey] < 0) {
92-
satchel.shard[nextRarityKey] = 0;
93-
}
82+
// We consume 2 🔵 for this action
83+
try {
84+
await consumePA({
85+
creatureUUID: req.item.bearer, // The creature UUID
86+
bluepa: 2, // Number of blue PA to consume
87+
redpa: 0, // Number of red PA to consume
88+
duration: 3600 // Each PA lasts 1 hours (in seconds)
89+
});
90+
} catch (err) {
91+
logger.error(`Creature.id:${req.item.bearer} Unable to consume PA: ${err}`)
9492
}
95-
satchel.updated = new Date();
96-
await satchel.save();
97-
} catch (err) {
98-
logger.error(`Satchel.id:${satchel.id} Unable to UPDATE: ${err}`)
99-
}
10093

101-
// We consume 2 🔵 for this action
102-
try {
103-
await consumePA({
104-
creatureUUID: item.bearer, // The creature UUID
105-
bluepa: 2, // Number of blue PA to consume
106-
redpa: 0, // Number of red PA to consume
107-
duration: 3600 // Each PA lasts 1 hours (in seconds)
94+
const msg = `Item.id:${item_uuid} catalyzed`
95+
logger.verbose(msg);
96+
return res.status(200).json({
97+
success: true,
98+
msg: msg,
99+
payload: {
100+
item: req.item,
101+
pa: await getPA(req.item.bearer),
102+
satchel: req.satchel
103+
}
108104
});
109-
} catch (err) {
110-
logger.error(`Creature.id:${item.bearer} Unable to consume PA: ${err}`)
111105
}
112-
113-
logger.info(`Item.id:${uuid} catalyzed`);
114-
return res.status(200).json({
115-
success: true,
116-
msg: `Item.id:${uuid} catalyzed successfully`,
117-
payload: {
118-
item: item,
119-
pa: await getPA(item.bearer),
120-
satchel: satchel
121-
}
122-
});
123-
}));
106+
));
124107

125108
export default router;

src/routes/item/create.ts

Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// routes/item/create.ts
2+
13
import express, { Request, Response, NextFunction } from 'express';
24
import logger from '../../logger';
35

@@ -12,43 +14,37 @@ function asyncHandler(fn: (req: Request, res: Response, next: NextFunction) => P
1214
};
1315
}
1416

15-
router.post('/', asyncHandler(async (req: Request, res: Response) => {
16-
logger.info(`POST /`);
17-
18-
const item_base = req.body
19-
20-
if (item_base.bound_type == 'BoE') { item_base.bound = false }
21-
22-
// We look for the related metaWeapon (Item.metaid)
23-
if (req.body.metatype == 'weapon') {
24-
const meta = await metaWeapon.findOne({ _id: Number(req.body.metaid) }).exec();
25-
if (!meta) {
26-
logger.warn(`metaWeapon.id:${req.body.metaid} not found`);
27-
return res.status(200).json({
28-
success: false,
29-
msg: `metaWeapon.id:${req.body.metaid} not found`,
30-
payload: null
31-
});
32-
} else {
33-
logger.debug(`metaWeapon.id:${req.body.metaid} found`);
34-
item_base.ammo = meta.max_ammo
17+
router.post(
18+
'/',
19+
asyncHandler(async (req: Request, res: Response) => {
20+
21+
const item_base = req.body
22+
logger.info(`POST /`);
23+
24+
if (item_base.bound_type == 'BoE') { item_base.bound = false }
25+
26+
// We look for the related metaWeapon (Item.metaid)
27+
if (req.body.metatype == 'weapon') {
28+
const meta = await metaWeapon.findOne({ _id: Number(req.body.metaid) }).exec();
29+
if (!meta) {
30+
const msg = `metaWeapon.id:${req.body.metaid} not found`
31+
logger.warn(msg);
32+
return res.status(200).json({ success: false, msg: msg, payload: null });
33+
} else {
34+
logger.verbose(`metaWeapon.id:${req.body.metaid} found`);
35+
item_base.ammo = meta.max_ammo
36+
}
3537
}
36-
}
3738

38-
try {
39-
const item = await Item.create(item_base);
40-
41-
logger.info(`Item.id:${item.id} created`);
42-
return res.status(201).json({
43-
success: true,
44-
msg: `Item.id:${item.id} created successfully`,
45-
payload: {
46-
item: item,
47-
}
48-
});
49-
} catch (err) {
50-
logger.error(`Item.id:null creation failed: ${err}`)
39+
try {
40+
const item = await Item.create(item_base);
41+
const msg = `Item.id:${item.id} created`
42+
logger.verbose(msg);
43+
return res.status(201).json({ success: true, msg: msg, payload: {item: item} });
44+
} catch (err) {
45+
logger.error(`Item.id:null creation failed: ${err}`)
46+
}
5147
}
52-
}));
48+
));
5349

5450
export default router;

src/routes/item/delete.ts

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1+
// routes/item/delete.ts
2+
13
import express, { Request, Response, NextFunction } from 'express';
4+
import { param, validationResult } from 'express-validator';
25
import logger from '../../logger';
3-
import Item from '../../models/Item';
6+
7+
import { fetchItemMiddleware, assertItemPresent } from '../../middlewares/fetch-item';
48

59
const router = express.Router();
610

@@ -10,31 +14,38 @@ function asyncHandler(fn: (req: Request, res: Response, next: NextFunction) => P
1014
};
1115
}
1216

13-
router.delete('/:uuid', asyncHandler(async (req: Request, res: Response) => {
14-
logger.info(`DELETE /${req.params.uuid}`);
15-
16-
const { uuid } = req.params;
17-
18-
// We look for the related Item
19-
const item = await Item.findById(uuid).exec();
20-
if (!item) {
21-
logger.warn(`Item.id:${uuid} not found`);
22-
return res.status(200).json({
23-
success: false,
24-
msg: `Item.id:${uuid} not found`,
25-
payload: null
26-
});
27-
} else {
28-
logger.debug(`Item.id:${uuid} found`);
29-
await item.deleteOne(); // This deletes the document from MongoDB
30-
}
17+
router.delete(
18+
'/:item_uuid',
19+
[
20+
param('item_uuid')
21+
.isUUID(4)
22+
.withMessage('Invalid UUID format'),
23+
],
24+
asyncHandler(fetchItemMiddleware),
25+
asyncHandler(async (req: Request, res: Response) => {
26+
// Check validation result
27+
const errors = validationResult(req);
28+
if (!errors.isEmpty()) {
29+
return res.status(400).json({ errors: errors.array() });
30+
}
3131

32-
logger.info(`Item.id:${uuid} destroyed`);
33-
return res.status(204).json({
34-
success: true,
35-
msg: `Item.id:${uuid} destroyed successfully`,
36-
payload: null
37-
});
38-
}));
32+
const { item_uuid } = req.params;
33+
logger.info(`DELETE /${req.params.item_uuid}`);
34+
35+
// We check middleware functions didn't screw up
36+
assertItemPresent(req)
37+
38+
try {
39+
await req.item.deleteOne(); // This deletes the document from MongoDB
40+
const msg = `Item.id:${item_uuid} destroyed`
41+
logger.verbose(msg);
42+
return res.status(204).json({ success: true, msg: msg, payload: {item: req.item} });
43+
} catch (err) {
44+
const msg = `Item.id:${item_uuid} deletion failed: ${err}`
45+
logger.error(msg)
46+
return res.status(200).json({ success: false, msg: msg, payload: null });
47+
}
48+
}
49+
));
3950

4051
export default router;

0 commit comments

Comments
 (0)