- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 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
.get(csrfProtection, function(req, res, next) {
let query = bandModel.count();
query.exec(function(err, amount) {
if (err) {
err = new Error('Sorry, the file with contents were not found on server.');
err.status = 500;
next(err);
}
// None bands are in database
else if (amount <= 0) {
res.render('bands', {
csrfToken: req.csrfToken(),
curPage: 1,
maxPage: 1,
arr: [],
search_value: ""
});
}
else {
let search_value = req.query.bandName;
// If search field is empty - assign search_value to ""
if(search_value === null ||
search_value === undefined)
{
search_value = "";
}
// Receive amount of bands that meet criteria
query = bandModel.count({
// search (case insensitive) partial match
name: { "$regex": search_value, "$options": "i" }
});
query.exec(function(err, amount) {
if(err) {
err = new Error('Sorry, the file with contents were not found on server.');
err.status = 500;
next(err);
}
else {
// if amount equals 0, notify the user about it
if (amount === 0) {
req.flash('error_msg', 'Nothing was found :(');
res.redirect('/bands');
}
else {
let pageNumber = req.query.page;
req.checkQuery('page', 'Page is required').notEmpty();
if (!search_value) {
req.checkQuery('page', 'Page should lay in proper bounds (from 1 to ' + parseInt((amount-1)/4 + 1) + ' at the moment).').isInt({ min: 1, max: parseInt((amount-1)/4 + 1) });
}
else {
req.checkQuery('page', 'Page should lay in proper bounds (from 1 to ' + parseInt((amount-1)/4 + 1) + ' for this query).').isInt({ min: 1, max: parseInt((amount-1)/4 + 1) });
}
let errs = req.validationErrors();
// If page is set improperly
if (errs.length === 1) {
req.flash('error_msg', errs[0].msg);
// If the search field was empty: redirect to /bands
if (!search_value) {
res.redirect('/bands');
}
// If the search field was not empty: redirect to /bands with search field that was set previously
else {
res.redirect('/bands?bandName=' + search_value);
}
}
// If page is not set at all: set is on default (1)
else {
if (errs.length === 2) {
pageNumber = 1;
}
query = bandModel.find({
// search (case insensitive) partial match
name: { "$regex": search_value, "$options": "i" }
}).limit(4).skip(4 * (pageNumber - 1)).lean();
query.exec(function(err, bands) {
if (err) {
err = new Error('Sorry, the file with contents were not found on server.');
err.status = 500;
next(err);
}
else {
res.render('bands', {
csrfToken: req.csrfToken(),
curPage: pageNumber,
maxPage: parseInt((amount-1)/4 + 1),
arr: bands,
search_value: search_value
});
}
});
}
}
}
});
}
});
})
Вот что бывает, если не разбивать код на модули. Попробуйте разобраться в этих коллбеках, которые в коллбеках, которые в коллбеках, которые...
Fike 21.12.2016 09:18 # +3
> err.status = 500;
так бы и уебал
dxd 21.12.2016 09:27 # 0
roman-kashitsyn 21.12.2016 12:52 # +4
Analotolievich 22.12.2016 16:33 # 0
barop 24.12.2016 15:14 # −1
вот именно потому JS и не следует использовать для серьезных проектов в которых больше 20ти строк кода
3_14dar 24.12.2016 15:59 # 0
Жаваскрипту в браузере альтернативы нет, а за пределами браузера в ecmascript не нужно асинхронное программирование.
barop 24.12.2016 16:04 # −1
3_14dar 24.12.2016 16:09 # 0
barop 24.12.2016 16:26 # 0
3_14dar 24.12.2016 18:28 # 0
В котором ты во фронтенде вообще не участвуешь.
> typescript async/await
Чтоэта?
barop 24.12.2016 19:01 # 0
лолшто?
>>Чтоэта?
https://ru.wikipedia.org/wiki/TypeScript
bormand 24.12.2016 16:20 # +1
Согласен с тобой, нода жс нинужна. Но сейчас набегут фанатики и заминусуют нас.
barop 24.12.2016 16:35 # 0
1) чтобы шарить логику на фронте и беке
2) чтобы шарить программиста на фронте и беке
ну только надо понимать что программисту будет очень больно писать на JS
TPAXHY_B_AHYC 24.12.2016 17:06 # 0
barop 24.12.2016 17:50 # −1
1024-- 24.12.2016 19:27 # +1
А на C/C++ можно писать кроссплатформенный код. Только оказывается, что всё это - маркетинговый ход, и надо какие-то дополнительные решения использовать, чтобы не страдать.
barop 24.12.2016 19:33 # 0
Конечно можно. Стандартная библиотека есть везде.
А теперь по делу:
Если у меня есть в коде знание о том, что жителям Камеруна полагается скидка 42%, то у меня есть четыре варианта действий
1) написать его один раз на JS для клиента и другой раз на другом ЯП для сервера
2) отказаться от валидации на клиенте
3) написать его на DSL и потом сгенерить код для клиента и сервера
4) написать его на js (или на чем-то что компилится в Js) и юзать на ноде и в браузере
Варианты 1 и 2 -- говно, пиздец, и йобаный стыд.
Варианты 3 и 4 -- годные.
ps: да, я знаю что в хорошем коде таких знаний нет: Они должны быть описаны декларативно или браться из БД
3_14dar 24.12.2016 20:28 # −1
Щаз тебя выебут.
inkanus-gray 24.12.2016 20:52 # +2
barop 25.12.2016 00:06 # 0
inkanus-gray 25.12.2016 00:18 # +2
Хотя даже примера J/J++ достаточно. Только поймут не все.
bormand 25.12.2016 07:22 # 0
3_14dar 24.12.2016 18:29 # 0
1024-- 24.12.2016 19:23 # 0
inkanus-gray 25.12.2016 10:27 # 0
1024-- 25.12.2016 11:02 # 0