Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task 8 #4

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea/
/node_modules
/Server script/node_modules
9 changes: 9 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[submodule "qunit"]
path = qunit
url = git://github.com/jquery/qunit.git
[submodule "jquery"]
path = jquery
url = git://github.com/jquery/jquery.git
[submodule "es5-shim"]
path = es5-shim
url = git://github.com/kriskowal/es5-shim.git
33 changes: 33 additions & 0 deletions Server script/GUID.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
(function () {
"use strict";
var randomHex4,
GUID;
/**
* @function генерирует случайный hex из четырех символов
* @private
* @return {String}
*/
randomHex4 = function () {
return Math.floor(
Math.random() * 0x10000 /* 65536 */
).toString(16);
};
/**
* @namespaсe , содержащий инструменты для работы с GUID
*/
GUID = function () {};
exports.GUID = GUID;
/**
* function генерирует guid в виде строки
* @return {String}
*/
GUID.createGUID = function () {
return (
randomHex4() + randomHex4() + "-" +
randomHex4() + "-" +
randomHex4() + "-" +
randomHex4() + "-" +
randomHex4() + randomHex4() + randomHex4()
);
};
}());
16 changes: 16 additions & 0 deletions Server script/ValidateEvent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
(function () {
"use strict";
var validate = function (event) {
//это можно сказать копи паст...
return !(typeof event.start === "undefined" ||
typeof event.end === "undefined" ||
typeof event.name === "undefined" ||
typeof event.gps === "undefined" ||
typeof event.gps.x === "undefined" ||
typeof event.gps.y === "undefined" ||
typeof event.stars === "undefined" ||
typeof event.cost === "undefined" ||
typeof event.parties === "undefined");
};
exports.validate = validate;
}());
74 changes: 74 additions & 0 deletions Server script/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
(function () {
"use strict";
var express = require('express'),
optimist = require('optimist').default('port', 8080).default('host', '127.0.0.1'),
color = require('colors'),
fs = require('fs'),
eventValidator = require('./validateEvent.js'),
guidModule = require('./guid.js'),
cfg,
app = express(),
printDate = function (date) {
return date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate();
};
app.use(express.static("../WebSite"));
app.use(express.bodyParser());

app.post("/saveNewEvent", function (req, res) {
console.log("Обработка запроса на добавления нового события в Бд....".green);
var newEventRequest = JSON.parse(req.param('request')),
newEvent;
if (!eventValidator.validate(newEventRequest)) {
console.log("Событие не валидное".red);
res.send({"request": false});
console.log("Обработка закончена".green);
return;
}
console.log("Событие прошло валидацию");
newEvent = {
"start": printDate(new Date(newEventRequest.start)),
"end": printDate(new Date(newEventRequest.end)),
"gps": {
"x": parseFloat(newEventRequest.gps.x),
"y": parseFloat(newEventRequest.gps.x)
},
"name": newEventRequest.name,
"stars": newEventRequest.stars,
"cost": newEventRequest.cost,
"parties": newEventRequest.parties,
"id": guidModule.GUID.createGUID()
};
console.log("Начинаем обновлять БД");
console.log("Открываем бд");
fs.readFile("../WebSite/base.json", "utf8", function (err, date) {
if (err) {
res.send({"request": false});
console.log("Открыть бд не удалось".red);
console.log("Обработка закончена".red);
return;
}
console.log("Файл прочитался");

var eventList = JSON.parse(date);
console.log("Файл преобразовали в json");
eventList.items.push(newEvent);
console.log("Сохраняем изменение в бд");
fs.writeFile("../WebSite/base.json", JSON.stringify(eventList), "utf8", function (error) {
if (error) {
res.send({"request": false});
console.log("Сохранить Бд не удалось".red);
console.log("Обработка закончена".red);
return;
}
console.log("Все удачно сохранилось");
console.log("Обработка закончена".green);
res.send({"request": true, "id": newEvent.id});
});
});

});

cfg = optimist.argv;
app.listen(cfg.port, cfg.host);
console.log("Server up: ".green + cfg.host + ":" + cfg.port);
}());
14 changes: 14 additions & 0 deletions Server script/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"dependencies": {
"optimist": "*",
"express": "*",
"colors": "*"
},
"name": "CalendarServer",
"version": "1.0.0",
"description": "Задание на dz8-nodejs",
"author": {
"name": "Mangin.Alex",
"email": "[email protected]"
}
}
162 changes: 162 additions & 0 deletions WebSite/Scripts/BaseEvent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/*global
Collection: false
*/
(function (toExport) {
"use strict";
/**
* Создает оболочку над массивом событий, предоставляющую "sql" подобные операции
*
* @class Оболочка над массивом событий.
* @augments Collection
*/
var BaseEvent = function BaseEvent(events) {
Collection.call(this, events);
},
starsComparer,
dateComparer;

toExport.BaseEvent = BaseEvent;

BaseEvent.prototype = Object.create(Collection.prototype, {
constructor: {
value: BaseEvent,
enumerable: false,
writable: true,
configurable: true
}
});
/**
*
*@field {BaseEvent} - ссылка на "родной" конструктор
*/
BaseEvent.prototype.constructor = BaseEvent;
/**
*@function Возвращает новую оболочку, но уже только с прошедшими событиями
*
*@return {BaseEvent}
*/
BaseEvent.prototype.pastEventBase = function () {
var currentDate = new Date();
return this.filter(function (event) {
return event.end.getTime() < currentDate.getTime();
});
};
/**
* @function Возвращает новую оболочку, но уже только с ненаступившими событиями
*
* @return {BaseEvent}
*/
BaseEvent.prototype.nextEventBase = function () {
var currentDate = new Date();
return this.filter(function (event) {
return event.start.getTime() > currentDate.getTime();
});
};
/**
* @function Возвращает новую оболочку, но уже с событиями, которые идут в данный момент
*
* @return
*/
BaseEvent.prototype.nowEventBase = function () {
var currentDate = new Date();
return this.filter(function (event) {
return (event.start.getTime() <= currentDate.getTime() && event.end.getTime() >= currentDate.getTime());
});
};

/**
* @function Возвращает новую оболочку, но уже с событиями, в которых участвует определенный человек
*
* @return
*/
BaseEvent.prototype.withFriend = function (myFriend) {
return this.filter(function (event) {
return event.parties.some(function (party) {
return party.name === myFriend.name;
});
});
};

/**
* @function Возвращает новую оболочку, но уже с событиями, которые будут в определенный период
*
* @param {Date} fromDate - начала периода
* @param {Date} toDate - конец периода
*
* @return
*/
BaseEvent.prototype.getEventFromPeriod = function (fromDate, toDate) {
return this.filter(function (event) {
return (event.start.getTime() > fromDate.getTime() && event.end.getTime() < toDate.getTime());
});
};

/**
* @function Возвращает новую оболочку, но уже с событиями, которые стоят не меньше min и не больше max
*
* @param {Number} min - начала периода
* @param {Number} max - начала периода
*
* @return {BaseEvent}
*/
BaseEvent.prototype.getEventWithCost = function (min, max) {
return this.filter(function (event) {
return (event.cost >= min && event.cost <= max);
});
};

/**
* @function Компаратор рейтинга по убыванию
* @private
*
* @field {Date} a
* @field {Date} b
*
* @return {Number}
*/
starsComparer = function compare(a, b) {
if (a.stars > b.stars) {
return -1;
}
if (a.stars < b.stars) {
return 1;
}
return 0;
};
/**
* @function Возвращает новую оболочку c теми же событиями, но отсортированными по уменьшению количества звезд
*
* @return {BaseEvent}
*/
BaseEvent.prototype.sortByStars = function (ascending) {
return this.sortBy(starsComparer, ascending);
};

/**
* @function Компаратор дат по возрастанию
* @private
*
* @field {Date} a
* @field {Date} b
*
* @return {Number}
*/
dateComparer = function (a, b) {
if (a.start.getTime() < b.start.getTime()) {
return -1;
}
if (a.start.getTime() > b.start.getTime()) {
return 1;
}
return 0;
};

/**
* @function Возвращает новую оболочку c теми же событиями, но отсортированными по дате
*
* @return {BaseEvent}
*/
BaseEvent.prototype.sortByDate = function (ascending) {
return this.sortBy(dateComparer, ascending);
};
}(window));
Loading