-
Notifications
You must be signed in to change notification settings - Fork 401
/
Copy pathindex.public.js
149 lines (128 loc) · 4.5 KB
/
index.public.js
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
import nextConnect from 'next-connect';
import controller from 'models/controller.js';
import authentication from 'models/authentication.js';
import authorization from 'models/authorization.js';
import validator from 'models/validator.js';
import content from 'models/content.js';
import event from 'models/event.js';
import database from 'infra/database.js';
import balance from 'models/balance.js';
import { NotFoundError, UnprocessableEntityError } from 'errors/index.js';
export default nextConnect({
attachParams: true,
onNoMatch: controller.onNoMatchHandler,
onError: controller.onErrorHandler,
})
.use(controller.injectRequestMetadata)
.use(authentication.injectAnonymousOrUser)
.use(controller.logRequest)
.post(postValidationHandler, authorization.canRequest('update:content'), postHandler);
function postValidationHandler(request, response, next) {
const cleanQueryValues = validator(request.query, {
username: 'required',
slug: 'required',
});
request.query = cleanQueryValues;
const cleanBodyValues = validator(request.body, {
transaction_type: 'required',
});
request.body = cleanBodyValues;
next();
}
async function postHandler(request, response) {
const userTryingToPost = request.context.user;
const contentFound = await content.findOne({
where: {
owner_username: request.query.username,
slug: request.query.slug,
status: 'published',
},
});
if (!contentFound) {
throw new NotFoundError({
message: `O conteúdo informado não foi encontrado no sistema.`,
action: 'Verifique se o "slug" está digitado corretamente.',
stack: new Error().stack,
errorLocationCode: 'CONTROLLER:CONTENT:TABCOINS:CONTENT_NOT_FOUND',
key: 'slug',
});
}
if (userTryingToPost.id === contentFound.owner_id) {
throw new UnprocessableEntityError({
message: `Você não pode realizar esta operação em conteúdos de sua própria autoria.`,
action: 'Realize esta operação em conteúdos de outros usuários.',
stack: new Error().stack,
errorLocationCode: 'CONTROLLER:CONTENT:TABCOINS:OWN_CONTENT',
key: 'tabcoins',
});
}
let currentContentTabCoinsBalance;
await tabcoinsTransaction(null, 5);
async function tabcoinsTransaction(transaction, remainingAttempts) {
if (!transaction) {
transaction = await database.transaction();
}
try {
await transaction.query('BEGIN');
await transaction.query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
const tabCoinsRequiredAmount = 2;
const currentEvent = await event.create(
{
type: 'update:content:tabcoins',
originatorUserId: request.context.user.id,
originatorIp: request.context.clientIp,
metadata: {
transaction_type: request.body.transaction_type,
from_user_id: userTryingToPost.id,
content_owner_id: contentFound.owner_id,
content_id: contentFound.id,
amount: tabCoinsRequiredAmount,
},
},
{
transaction: transaction,
}
);
currentContentTabCoinsBalance = await balance.rateContent(
{
contentId: contentFound.id,
contentOwnerId: contentFound.owner_id,
fromUserId: userTryingToPost.id,
transactionType: request.body.transaction_type,
},
{
eventId: currentEvent.id,
transaction: transaction,
}
);
await transaction.query('COMMIT');
await transaction.release();
} catch (error) {
await transaction.query('ROLLBACK');
if (
error.databaseErrorCode === database.errorCodes.SERIALIZATION_FAILURE ||
error.stack?.startsWith('error: could not serialize access due to read/write dependencies among transaction')
) {
if (remainingAttempts > 0) {
await tabcoinsTransaction(transaction, remainingAttempts - 1);
} else {
await transaction.release();
throw new UnprocessableEntityError({
message: `Muitos votos ao mesmo tempo.`,
action: 'Tente realizar esta operação mais tarde.',
errorLocationCode: 'CONTROLLER:CONTENT:TABCOINS:SERIALIZATION_FAILURE',
});
}
} else {
await transaction.release();
throw error;
}
}
}
const secureOutputValues = authorization.filterOutput(
userTryingToPost,
'read:content:tabcoins',
currentContentTabCoinsBalance
);
return response.status(201).json(secureOutputValues);
}