Migrating from mongoose to sequelize, introducing types

before-bootstrap
Candid Dauth 2014-12-11 02:42:32 +01:00
rodzic 07d1859154
commit 954be66c7f
9 zmienionych plików z 278 dodań i 360 usunięć

Wyświetl plik

@ -171,6 +171,7 @@
$scope.markers = { }; $scope.markers = { };
$scope.lines = { }; $scope.lines = { };
$scope.views = { }; $scope.views = { };
$scope.types = { };
$scope.dialog = null; $scope.dialog = null;
$scope.dialogError = null; $scope.dialogError = null;
$scope.saveViewName = null; $scope.saveViewName = null;
@ -192,7 +193,7 @@
$scope.onMove = function() { $scope.onMove = function() {
if($scope.currentMarker) if($scope.currentMarker)
$scope.currentMarker.xy = fp.posToXy($scope.currentMarker.position); $scope.currentMarker.xy = fp.posToXy($scope.currentMarker);
if($scope.currentLine && $scope.currentLine.clickPos) if($scope.currentLine && $scope.currentLine.clickPos)
$scope.currentLine.clickXy = fp.posToXy($scope.currentLine.clickPos); $scope.currentLine.clickXy = fp.posToXy($scope.currentLine.clickPos);
}; };
@ -297,7 +298,14 @@
$scope.onMove(); $scope.onMove();
}.fpWrapApply($scope)); }.fpWrapApply($scope));
$scope.addMarker = function() { $scope.addObject = function(type) {
if(type.type == "marker")
$scope.addMarker(type);
else if(type.type == "line")
$scope.addLine(type);
};
$scope.addMarker = function(type) {
var message = $scope.showMessage("info", "Please click on the map to add a marker.", [ var message = $scope.showMessage("info", "Please click on the map to add a marker.", [
{ label: "Cancel", click: function() { { label: "Cancel", click: function() {
$scope.closeMessage(message); $scope.closeMessage(message);
@ -307,7 +315,7 @@
var listener = fp.addClickListener(function(pos) { var listener = fp.addClickListener(function(pos) {
$scope.closeMessage(message); $scope.closeMessage(message);
socket.emit("addMarker", { position: { lon: pos.lon, lat: pos.lat } }, function(err, marker) { socket.emit("addMarker", { lon: pos.lon, lat: pos.lat, typeId: type.id }, function(err, marker) {
if(err) if(err)
return $scope.showMessage("error", err); return $scope.showMessage("error", err);
@ -339,7 +347,7 @@
var listener = fp.addClickListener(function(pos) { var listener = fp.addClickListener(function(pos) {
$scope.closeMessage(message); $scope.closeMessage(message);
socket.emit("editMarker", { id: marker.id, position: pos }, function(err) { socket.emit("editMarker", { id: marker.id, lat: pos.lat, lon: pos.lon }, function(err) {
if(err) if(err)
return $scope.showMessage("error", err); return $scope.showMessage("error", err);
@ -355,8 +363,11 @@
}); });
}; };
$scope.addLine = function() { $scope.addLine = function(type) {
socket.emit("addLine", { points: [ ] }, function(err, line) { socket.emit("addLine", { points: [ ], typeId: type.id }, function(err, line) {
if(err)
return $scope.showMessage("error", err);
line.actualPoints = [ ]; line.actualPoints = [ ];
$scope.currentLine = line; $scope.currentLine = line;
var message = $scope.showMessage("info", "Please click on the map to draw a line. Double-click to finish it.", [ var message = $scope.showMessage("info", "Please click on the map to draw a line. Double-click to finish it.", [
@ -474,7 +485,7 @@
return $scope.dialogError = err; return $scope.dialogError = err;
if(makeDefault) { if(makeDefault) {
socket.emit("editPad", { defaultView: view.id }, function(err) { socket.emit("editPad", { defaultViewId: view.id }, function(err) {
if(err) if(err)
return $scope.dialogError = err; return $scope.dialogError = err;
@ -489,7 +500,7 @@
}; };
$scope.setDefaultView = function(view) { $scope.setDefaultView = function(view) {
socket.emit("editPad", { defaultView: view.id }, function(err) { socket.emit("editPad", { defaultViewId: view.id }, function(err) {
if(err) if(err)
$scope.dialogError = err; $scope.dialogError = err;
}); });
@ -502,6 +513,14 @@
}); });
}; };
$scope.editType = function(type) {
// TODO
};
$scope.removeType = function(type) {
// TODO
};
$scope.copyPad = function() { $scope.copyPad = function() {
socket.emit("copyPad", { toId: $scope.copyPadId }, function(err) { socket.emit("copyPad", { toId: $scope.copyPadId }, function(err) {
if(err) { if(err) {
@ -670,6 +689,14 @@
$scope.padData.defaultViewId = null; $scope.padData.defaultViewId = null;
}); });
socket.on("type", function(data) {
$scope.types[data.id] = data;
});
socket.on("deleteType", function(data) {
delete $scope.types[data.id];
});
socket.on("disconnect", function() { socket.on("disconnect", function() {
$scope.error = $scope.showMessage("error", "The connection to the server was lost."); $scope.error = $scope.showMessage("error", "The connection to the server was lost.");
$scope.markers = { }; $scope.markers = { };

Wyświetl plik

@ -164,15 +164,16 @@ var FacilPad = {
} }
fp.getCurrentView = function() { fp.getCurrentView = function() {
var ret = { var ret = fp.map.getExtent().clone().transform(fp.map.getProjectionObject(), _p());
view: fp.map.getExtent().clone().transform(fp.map.getProjectionObject(), _p()),
baseLayer: fp.map.baseLayer.permalinkName, ret.baseLayer = fp.map.baseLayer.permalinkName;
layers: [ ] ret.layers = [ ];
};
for(var i=0; i<fp.map.layers.length; i++) { for(var i=0; i<fp.map.layers.length; i++) {
if(!fp.map.layers[i].isBaseLayer && fp.map.layers[i].displayInLayerSwitcher && fp.map.layers[i].visibility) if(!fp.map.layers[i].isBaseLayer && fp.map.layers[i].displayInLayerSwitcher && fp.map.layers[i].visibility)
ret.layers.push(fp.map.layers[i].permalinkName || fp.map.layers[i].name); ret.layers.push(fp.map.layers[i].permalinkName || fp.map.layers[i].name);
} }
return ret; return ret;
}; };
@ -180,7 +181,7 @@ var FacilPad = {
if(view == null) { if(view == null) {
fp.map.zoomToMaxExtent(); fp.map.zoomToMaxExtent();
} else { } else {
var bbox = OpenLayers.Bounds.prototype.clone.apply(view.view).transform(_p(), fp.map.getProjectionObject()); var bbox = OpenLayers.Bounds.prototype.clone.apply(view).transform(_p(), fp.map.getProjectionObject());
fp.map.zoomToExtent(bbox); fp.map.zoomToExtent(bbox);
var matching_layers = fp.map.getLayersBy("permalinkName", view.baseLayer); var matching_layers = fp.map.getLayersBy("permalinkName", view.baseLayer);
@ -206,7 +207,7 @@ var FacilPad = {
graphicXOffset: -9, graphicXOffset: -9,
graphicYOffset: -25 graphicYOffset: -25
}; };
var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(marker.position.lon, marker.position.lat).transform(_p(), fp.map.getProjectionObject()), null, style); var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(marker.lon, marker.lat).transform(_p(), fp.map.getProjectionObject()), null, style);
feature.fpMarker = marker; feature.fpMarker = marker;
feature.fpOnClick = function() { feature.fpOnClick = function() {
fp.mapEvents.trigger("clickMarker", [ marker ]); fp.mapEvents.trigger("clickMarker", [ marker ]);
@ -352,7 +353,7 @@ var FacilPad = {
if(!end) { if(!end) {
for(var i=0; i<line.points.length; i++) { for(var i=0; i<line.points.length; i++) {
var marker = { id: "linePoint"+i, position: line.points[i], colour: "ffd700", i: i }; var marker = { id: "linePoint"+i, lat: line.points[i].lat, lon: line.points[i].lon, colour: "ffd700", i: i };
markers.push(marker); markers.push(marker);
fp.addMarker(marker); fp.addMarker(marker);
} }

Wyświetl plik

@ -17,8 +17,7 @@
<div id="map-disabled-cover" ng-show="!loaded || error"></div> <div id="map-disabled-cover" ng-show="!loaded || error"></div>
<ul id="toolbox"> <ul id="toolbox">
<li><a href="javascript:" ng-click="addMarker()" ng-hide="readonly">Add marker</a></li> <li ng-repeat="type in types" fp-variable-menu-item><a href="javascript:" ng-click="addObject(type)" ng-hide="readonly">Add {{type.name}}</a></li>
<li><a href="javascript:" ng-click="addLine()" ng-hide="readonly">Add line</a></li>
<li><a href="javascript:">Views</a><ul> <li><a href="javascript:">Views</a><ul>
<li ng-repeat="(id, view) in views" fp-variable-menu-item><a href="javascript:" ng-click="displayView(view)">{{view.name}}</a></li> <li ng-repeat="(id, view) in views" fp-variable-menu-item><a href="javascript:" ng-click="displayView(view)">{{view.name}}</a></li>
<li><a href="javascript:" ng-click="openDialog('save-view-dialog')" ng-hide="readonly">Save current view</a></li> <li><a href="javascript:" ng-click="openDialog('save-view-dialog')" ng-hide="readonly">Save current view</a></li>
@ -33,8 +32,9 @@
</li> </li>
</ul></li> </ul></li>
<li><a href="javascript:">Tools</a><ul> <li><a href="javascript:">Tools</a><ul>
<li><a href="javascript:" ng-click="openDialog('copy-pad-dialog')" ng-hide="readonly">Copy pad</a></li> <!--<li><a href="javascript:" ng-click="openDialog('copy-pad-dialog')" ng-hide="readonly">Copy pad</a></li>-->
<li><a href="javascript:" ng-click="openDialog('pad-settings-dialog')" ng-hide="readonly">Pad settings</a></li> <li><a href="javascript:" ng-click="openDialog('pad-settings-dialog')" ng-hide="readonly">Pad settings</a></li>
<!--<li><a href="javascript:" ng-click="openDialog('object-types-dialog')" ng-hide="readonly">Object types</a></li>-->
</ul></li> </ul></li>
</ul> </ul>
@ -76,7 +76,7 @@
<div id="view-marker-popup" fp-popup="currentMarker.xy"> <div id="view-marker-popup" fp-popup="currentMarker.xy">
<div class="content"> <div class="content">
<h2>{{currentMarker.name}}</h2> <h2>{{currentMarker.name}}</h2>
<p class="pos">Coordinates: {{round(currentMarker.position.lat, 5)}}, {{round(currentMarker.position.lon, 5)}}</p> <p class="pos">Coordinates: {{round(currentMarker.lat, 5)}}, {{round(currentMarker.lon, 5)}}</p>
<div ng-bind-html="currentMarker.descriptionHtml"></div> <div ng-bind-html="currentMarker.descriptionHtml"></div>
</div> </div>
<div class="buttons"> <div class="buttons">
@ -170,6 +170,34 @@
</form> </form>
</div> </div>
<div id="object-types-dialog" title="Object types" fp-dialog fp-preserve="padData">
<form>
<p class="error" ng-show="dialogError">{{dialogError}}</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th colspan="2">Edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="type in types">
<td>{{type.name}}</td>
<td>{{type.type}}</td>
<td class="button"><button ng-click="editType(type)">Edit</button></td>
<td class="button"><button ng-click="removeType(type)">Remove</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3"><button ng-click="createType()">Create</button></td>
</tr>
</tfoot>
</table>
</form>
</div>
<div id="copy-pad-dialog" title="Copy pad" fp-dialog> <div id="copy-pad-dialog" title="Copy pad" fp-dialog>
<form> <form>
<p class="error" ng-show="dialogError">{{dialogError}}</p> <p class="error" ng-show="dialogError">{{dialogError}}</p>

Wyświetl plik

@ -2,11 +2,11 @@ module.exports = {
host : null, host : null,
port : 40829, port : 40829,
db : { db : {
type: "mongodb", // mongodb, mysql, postgres, mariadb, sqlite type: "mysql", // mysql, postgres, mariadb, sqlite
host: "localhost", host: "localhost",
port: null, port: null,
database: "facilpad", database: "facilpad",
user: null, user: "facilpad",
password: null password: "password"
} }
}; };

Wyświetl plik

@ -1,21 +1,33 @@
var backend = require("./databaseBackendMongodb"); var backend = require("./databaseBackendSequelize");
var listeners = require("./listeners"); var listeners = require("./listeners");
var routing = require("./routing"); var routing = require("./routing");
var utils = require("./utils"); var utils = require("./utils");
var async = require("async"); var async = require("async");
var underscore = require("underscore"); var underscore = require("underscore");
var DEFAULT_TYPES = [
{ name: "marker", type: "marker", fields: { description: { type: "textarea" } } },
{ name: "line", type: "line", fields: { description: { type: "textarea" } } }
];
function getPadData(padId, callback) { function getPadData(padId, callback) {
backend.getPadDataByWriteId(padId, function(err, data) { backend.getPadDataByWriteId(padId, function(err, data) {
if(err || data != null) if(err || data != null)
return callback(err, utils.extend(data, { writable: true })); return callback(err, utils.extend(JSON.parse(JSON.stringify(data)), { writable: true, writeId: null }));
backend.getPadData(padId, function(err, data) { backend.getPadData(padId, function(err, data) {
if(err || data != null) if(err || data != null)
return callback(err, utils.extend(data, { writable: false })); return callback(err, utils.extend(JSON.parse(JSON.stringify(data)), { writable: false, writeId: null }));
backend.createPad(utils.generateRandomId(10), padId, function(err, data) { backend.createPad(utils.generateRandomId(10), padId, function(err, data) {
callback(err, utils.extend(data, { writable: true })); if(err)
return callback(err);
async.each(DEFAULT_TYPES, function(it, next) {
backend.createType(data.id, it, next);
}, function(err) {
callback(err, utils.extend(JSON.parse(JSON.stringify(data)), { writable: true, writeId: null }));
});
}); });
}); });
}); });
@ -43,7 +55,7 @@ function createView(padId, data, callback) {
if(err) if(err)
return callback(err); return callback(err);
listeners.notifyPadListeners(data._pad, "view", data); listeners.notifyPadListeners(data.PadId, "view", data);
callback(null, data); callback(null, data);
}); });
} }
@ -56,7 +68,7 @@ function updateView(viewId, data, callback) {
if(err) if(err)
return callback(err); return callback(err);
listeners.notifyPadListeners(data._pad, "view", data); listeners.notifyPadListeners(data.PadId, "view", data);
callback(null, data); callback(null, data);
}); });
} }
@ -66,7 +78,47 @@ function deleteView(viewId, callback) {
if(err) if(err)
return callback(err); return callback(err);
listeners.notifyPadListeners(data._pad, "deleteView", { id: data.id }); listeners.notifyPadListeners(data.PadId, "deleteView", { id: data.id });
callback(null, data);
});
}
function getTypes(padId) {
return backend.getTypes(padId);
}
function createType(padId, data, callback) {
if(data.name == null || data.name.trim().length == 0)
return callback("No name provided.");
backend.createType(padId, data, function(err, data) {
if(err)
return callback(err);
listeners.notifyPadListeners(data.PadId, "type", data);
callback(null, data);
});
}
function updateType(typeId, data, callback) {
if(data.name == null || data.name.trim().length == 0)
return callback("No name provided.");
backend.updateType(typeId, data, function(err, data) {
if(err)
return callback(err);
listeners.notifyPadListeners(data.PadId, "type", data);
callback(null, data);
});
}
function deleteType(typeId, callback) {
backend.deleteView(typeId, function(err, data) {
if(err)
return callback(err);
listeners.notifyPadListeners(data.PadId, "deleteType", { id: data.id });
callback(null, data); callback(null, data);
}); });
} }
@ -90,7 +142,7 @@ function updateMarker(markerId, data, callback) {
if(err) if(err)
return callback(err); return callback(err);
listeners.notifyPadListeners(data._pad, "marker", _getMarkerDataFunc(data)); listeners.notifyPadListeners(data.PadId, "marker", _getMarkerDataFunc(data));
callback(null, data); callback(null, data);
}); });
} }
@ -100,7 +152,7 @@ function deleteMarker(markerId, callback) {
if(err) if(err)
return callback(err); return callback(err);
listeners.notifyPadListeners(data._pad, "deleteMarker", { id: data.id }); listeners.notifyPadListeners(data.PadId, "deleteMarker", { id: data.id });
callback(null, data); callback(null, data);
}); });
} }
@ -147,7 +199,7 @@ function updateLine(lineId, data, callback) {
if(!res.calculateRouting) if(!res.calculateRouting)
return next(); return next();
_setLinePoints(res.originalLine._pad, lineId, res.calculateRouting, next); _setLinePoints(res.originalLine.PadId, lineId, res.calculateRouting, next);
} ] } ]
}, function(err, res) { }, function(err, res) {
callback(err, res.updateLine); callback(err, res.updateLine);
@ -159,7 +211,7 @@ function _createLine(padId, data, callback) {
if(err) if(err)
return callback(err); return callback(err);
listeners.notifyPadListeners(data._pad, "line", data); listeners.notifyPadListeners(data.PadId, "line", data);
callback(null, data); callback(null, data);
}); });
} }
@ -169,7 +221,7 @@ function _updateLine(lineId, data, callback) {
if(err) if(err)
return callback(err); return callback(err);
listeners.notifyPadListeners(data._pad, "line", data); listeners.notifyPadListeners(data.PadId, "line", data);
callback(null, data); callback(null, data);
}); });
} }
@ -196,7 +248,7 @@ function deleteLine(lineId, callback) {
if(err) if(err)
return callback; return callback;
listeners.notifyPadListeners(data._pad, "deleteLine", { id: data.id }); listeners.notifyPadListeners(data.PadId, "deleteLine", { id: data.id });
callback(null, data); callback(null, data);
}); });
}); });
@ -216,7 +268,7 @@ function getLinePoints(padId, bboxWithZoom) {
}); });
} }
function copyPad(fromPadId, toPadId, callback) { /*function copyPad(fromPadId, toPadId, callback) {
function _handleStream(stream, next, cb) { function _handleStream(stream, next, cb) {
stream.on("data", function(data) { stream.on("data", function(data) {
stream.pause(); stream.pause();
@ -280,7 +332,7 @@ function copyPad(fromPadId, toPadId, callback) {
}); });
}] }]
}, callback); }, callback);
} }*/
function _calculateRouting(line, callback) { function _calculateRouting(line, callback) {
if(line.points && line.points.length >= 2 && line.mode) { if(line.points && line.points.length >= 2 && line.mode) {
@ -308,7 +360,7 @@ function _calculateRouting(line, callback) {
function _getMarkerDataFunc(marker) { function _getMarkerDataFunc(marker) {
return function(bbox) { return function(bbox) {
if(!utils.isInBbox(marker.position, bbox)) if(!utils.isInBbox(marker, bbox))
return null; return null;
return marker; return marker;
@ -347,6 +399,10 @@ module.exports = {
createView : createView, createView : createView,
updateView : updateView, updateView : updateView,
deleteView : deleteView, deleteView : deleteView,
getTypes : getTypes,
createType : createType,
updateType : updateType,
deleteType : deleteType,
getPadMarkers : getPadMarkers, getPadMarkers : getPadMarkers,
createMarker : createMarker, createMarker : createMarker,
updateMarker : updateMarker, updateMarker : updateMarker,
@ -356,5 +412,6 @@ module.exports = {
updateLine : updateLine, updateLine : updateLine,
deleteLine : deleteLine, deleteLine : deleteLine,
getLinePoints : getLinePoints, getLinePoints : getLinePoints,
copyPad : copyPad //copyPad : copyPad,
_defaultTypes : DEFAULT_TYPES
}; };

Wyświetl plik

@ -1,305 +0,0 @@
var mongoose = require("mongoose");
var config = require("../config");
var utils = require("./utils");
var OLD_MARKER_COLOURS = { blue: "8da8f6", green: "90ee90", gold: "ffd700", red: "ff0000" };
function connect(callback) {
var connectionString = "mongodb://"
+ (config.db.user ? encodeURIComponent(config.db.user) + ":" + encodeURIComponent(config.db.password) + "@" : "")
+ config.db.host
+ (config.db.port ? ":" + config.db.port : "")
+ "/" + config.db.database;
mongoose.connect(connectionString);
callback();
}
var ObjectId = mongoose.Schema.Types.ObjectId;
var positionType = {
lon: Number,
lat: Number
};
var bboxType = {
top: Number,
right: Number,
bottom: Number,
left: Number
};
var markerSchema = mongoose.Schema({
_pad : { type: String, ref: "Pad" },
position : positionType,
name : { type: String, default: "Untitled marker" },
description : String,
colour : { type: String, default: "ff0000" }
});
var lineSchema = mongoose.Schema({
_pad : { type: String, ref: "Pad" },
points : [positionType],
mode : { type: String, default: "" },
colour : { type: String, default: "0000ff" },
width : { type: Number, default: 4 },
description : String,
name : { type: String, default: "Untitled line" },
distance : Number,
time : Number
});
var linePointsSchema = mongoose.Schema(utils.extend({ }, positionType, {
zoom : Number,
idx : Number,
_line : { type: ObjectId, ref: "Line" }
}));
linePointsSchema.index({ _id: 1, idx: 1 });
var viewSchema = mongoose.Schema({
_pad : { type: String, ref: "Pad" },
name : String,
baseLayer : String,
layers : [String],
view : bboxType
});
var padSchema = mongoose.Schema({
_id : String,
defaultView : { type: ObjectId, ref: "View" },
name: { type: String, default: "New FacilPad" },
writeId : String
});
padSchema.index({ writeId: 1 });
var Marker = mongoose.model("Marker", markerSchema);
var Line = mongoose.model("Line", lineSchema);
var LinePoints = mongoose.model("LinePoints", linePointsSchema);
var View = mongoose.model("View", viewSchema);
var Pad = mongoose.model("Pad", padSchema);
function getPadData(padId, callback) {
Pad.findById(padId).populate("defaultView").exec(_fixIdCallback(callback));
}
function getPadDataByWriteId(writeId, callback) {
Pad.findOne({ writeId: writeId }).populate("defaultView").exec(_fixIdCallback(callback));
}
function createPad(padId, writeId, callback) {
Pad.create({ _id: padId, writeId: writeId }, _fixIdCallback(callback));
}
function updatePadData(padId, data, callback) {
Pad.findByIdAndUpdate(padId, data).populate("defaultView").exec(_fixIdCallback(callback));
}
function getViews(padId) {
return _fixIdStream(View.find({ "_pad" : padId }).stream());
}
function createView(padId, data, callback) {
data._pad = padId;
View.create(data, _fixIdCallback(callback));
}
function updateView(viewId, data, callback) {
View.findByIdAndUpdate(viewId, data, _fixIdCallback(callback));
}
function deleteView(viewId, callback) {
View.findByIdAndRemove(viewId, _fixIdCallback(callback));
}
function getPadMarkers(padId, bbox) {
var condition = { $and: [ _makeBboxCondition(bbox, "position."), {
"_pad" : padId
} ] };
return _fixIdStream(Marker.find(condition).stream());
}
function createMarker(padId, data, callback) {
data._pad = padId;
Marker.create(data, _fixIdCallback(callback));
}
function updateMarker(markerId, data, callback) {
Marker.findByIdAndUpdate(markerId, data, _fixIdCallback(callback));
}
function deleteMarker(markerId, callback) {
Marker.findByIdAndRemove(markerId, _fixIdCallback(callback));
}
function getPadLines(padId, fields) {
var condition = {
"_pad" : padId
};
return _fixIdStream(Line.find(condition, fields).stream());
}
function getLine(lineId, callback) {
Line.findById(lineId, _fixIdCallback(callback));
}
function createLine(padId, data, callback) {
data = utils.extend({ }, data, { _pad: padId });
Line.create(data, _fixIdCallback(callback));
}
function updateLine(lineId, data, callback) {
Line.findByIdAndUpdate(lineId, data, _fixIdCallback(callback));
}
function deleteLine(lineId, callback) {
Line.findByIdAndRemove(lineId, _fixIdCallback(callback));
}
function getLinePoints(lineId, callback) {
LinePoints.find({ _line: lineId }).sort("idx").exec(_linePointsCallback(callback));
}
function getLinePointsByBbox(lineId, bboxWithZoom, callback) {
var condition = { $and: [ _makeBboxCondition(bboxWithZoom), {
"_line" : lineId,
"zoom" : { $lte: bboxWithZoom.zoom }
} ] };
LinePoints.find(condition, "idx zoom", { sort: "idx" }).exec(_linePointsCallback(callback));
}
function getLinePointsByIdx(lineId, indexes, callback) {
LinePoints.find({ _line: lineId, idx: { $in: indexes } }).select("lon lat idx").sort("idx").exec(_linePointsCallback(callback));
}
function setLinePoints(lineId, points, callback) {
LinePoints.remove({ _line: lineId }, function(err) {
if(err)
return callback(err);
var create = [ ];
for(var i=0; i<points.length; i++) {
create.push(utils.extend({ }, points[i], { _line: lineId }));
}
if(create.length > 0)
LinePoints.create(create, callback);
else
callback();
});
}
function _fixId(data) {
if(data != null) {
data = JSON.parse(JSON.stringify(data));
data.id = data._id;
delete data._id;
if(data.writeId)
delete data.writeId;
if(data.defaultView) {
data.defaultView.id = data.defaultView._id;
delete data.defaultView._id;
}
if(data.points) {
for(var i=0; i<data.points.length; i++)
delete data.points[i]._id;
}
// Backwards compatibility for markers
if(data.style) {
data.colour = OLD_MARKER_COLOURS[data.style];
delete data.style;
}
}
return data;
}
function _fixIdCallback(callback) {
return function(err, data) {
callback(err, _fixId(data));
}
}
function _fixIdStream(stream) {
return utils.filterStream(stream, _fixId);
}
function _linePointsCallback(callback) {
return function(err, linePoints) {
if(err)
return callback(err);
var ret = [ ];
for(var i=0; i<linePoints.length; i++) {
var c = JSON.parse(JSON.stringify(linePoints[i]));
delete c._id;
ret.push(c);
}
callback(null, ret);
};
}
function _makeBboxCondition(bbox, prefix) {
if(!bbox)
return { };
prefix = prefix || "";
function cond(key, value) {
var ret = { };
ret[prefix+key] = value;
return ret;
}
var conditions = [ ];
conditions.push(cond("lat", { $lte: bbox.top, $gte: bbox.bottom }));
if(bbox.right < bbox.left) // Bbox spans over lon=180
conditions.push({ $or: [ cond("lon", { $gte: bbox.left }), cond("lon", { $lte: bbox.right }) ] });
else
conditions.push(cond("lon", { $gte: bbox.left, $lte: bbox.right }));
if(bbox.except) {
var exceptConditions = [ ];
exceptConditions.push({ $or: [ cond("lat", { $gt: bbox.except.top }), cond("lat", { $lt: bbox.except.bottom }) ] });
if(bbox.except.right < bbox.except.left)
exceptConditions.push(cond("lon", { $lt: bbox.except.left, $gt: bbox.except.right }));
else
exceptConditions.push({ $or: [ cond("lon", { $lt: bbox.except.left }), cond("lon", { $gt: bbox.except.right }) ] });
conditions.push({ $or: exceptConditions });
}
return { $and : conditions };
}
module.exports = {
connect : connect,
getPadData : getPadData,
getPadDataByWriteId : getPadDataByWriteId,
createPad : createPad,
updatePadData : updatePadData,
getViews : getViews,
createView : createView,
updateView : updateView,
deleteView : deleteView,
getPadMarkers : getPadMarkers,
createMarker : createMarker,
updateMarker : updateMarker,
deleteMarker : deleteMarker,
getPadLines : getPadLines,
getLine : getLine,
createLine : createLine,
updateLine : updateLine,
deleteLine : deleteLine,
getLinePoints : getLinePoints,
getLinePointsByBbox : getLinePointsByBbox,
getLinePointsByIdx : getLinePointsByIdx,
setLinePoints : setLinePoints
};

Wyświetl plik

@ -27,9 +27,8 @@ database.connect(function(err) {
}, },
setPadId : function(padId) { setPadId : function(padId) {
if(socket.padId != null) { if(typeof padId != "string" || socket.padId != null)
return; return;
}
socket.padId = true; socket.padId = true;
@ -43,6 +42,7 @@ database.connect(function(err) {
_sendData(socket, "padData", null, data); _sendData(socket, "padData", null, data);
_sendStreamData(socket, "view", database.getViews(socket.padId)); _sendStreamData(socket, "view", database.getViews(socket.padId));
_sendStreamData(socket, "type", database.getTypes(socket.padId));
_sendStreamData(socket, "line", database.getPadLines(socket.padId)); _sendStreamData(socket, "line", database.getPadLines(socket.padId));
if(socket.bbox) { // In case bbox is set while fetching pad data if(socket.bbox) { // In case bbox is set while fetching pad data
@ -53,6 +53,9 @@ database.connect(function(err) {
}, },
updateBbox : function(bbox) { updateBbox : function(bbox) {
if(!utils.stripObject(bbox, { top: "number", left: "number", bottom: "number", right: "number", zoom: "number" }))
return;
var bboxWithExcept = utils.extend({ }, bbox); var bboxWithExcept = utils.extend({ }, bbox);
if(socket.bbox && bbox.zoom == socket.bbox.zoom) if(socket.bbox && bbox.zoom == socket.bbox.zoom)
bboxWithExcept.except = socket.bbox; bboxWithExcept.except = socket.bbox;
@ -71,78 +74,139 @@ database.connect(function(err) {
}, },
editPad : function(data, callback) { editPad : function(data, callback) {
if(!utils.stripObject(data, { name: "string", defaultViewId: "number" }))
return callback("Invalid parameters.");
if(!socket.writable) if(!socket.writable)
return callback(new Error("In read-only mode.")); return callback("In read-only mode.");
database.updatePadData(socket.padId, data, callback); database.updatePadData(socket.padId, data, callback);
}, },
addMarker : function(data, callback) { addMarker : function(data, callback) {
if(!utils.stripObject(data, { lat: "number", lon: "number", name: "string", colour: "string", typeId: "number" } ))
return callback("Invalid parameters.");
if(!socket.writable) if(!socket.writable)
return callback(new Error("In read-only mode.")); return callback("In read-only mode.");
database.createMarker(socket.padId, data, callback); database.createMarker(socket.padId, data, callback);
}, },
editMarker : function(data, callback) { editMarker : function(data, callback) {
if(!utils.stripObject(data, { id: "number", lat: "number", lon: "number", name: "string", colour: "string" }))
return callback("Invalid parameters.");
if(!socket.writable) if(!socket.writable)
return callback(new Error("In read-only mode.")); return callback("In read-only mode.");
database.updateMarker(data.id, data, callback); database.updateMarker(data.id, data, callback);
}, },
deleteMarker : function(data, callback) { deleteMarker : function(data, callback) {
if(!utils.stripObject(data, { id: "number" }))
return callback("Invalid parameters.");
if(!socket.writable) if(!socket.writable)
return callback(new Error("In read-only mode.")); return callback("In read-only mode.");
database.deleteMarker(data.id, callback); database.deleteMarker(data.id, callback);
}, },
addLine : function(data, callback) { addLine : function(data, callback) {
if(!utils.stripObject(data, { points: [ { lat: "number", lon: "number" } ], mode: "string", colour: "string", width: "number", name: "string", typeId: "number" }))
return callback("Invalid parameters.");
if(!socket.writable) if(!socket.writable)
return callback(new Error("In read-only mode.")); return callback("In read-only mode.");
database.createLine(socket.padId, data, callback); database.createLine(socket.padId, data, callback);
}, },
editLine : function(data, callback) { editLine : function(data, callback) {
if(!utils.stripObject(data, { id: "number", points: [ { lat: "number", lon: "number" } ], mode: "string", colour: "string", width: "number", name: "string" }))
return callback("Invalid parameters.");
if(!socket.writable) if(!socket.writable)
return callback(new Error("In read-only mode.")); return callback("In read-only mode.");
database.updateLine(data.id, data, callback); database.updateLine(data.id, data, callback);
}, },
deleteLine : function(data, callback) { deleteLine : function(data, callback) {
if(!utils.stripObject(data, { id: "number" }))
return callback("Invalid parameters.");
if(!socket.writable) if(!socket.writable)
return callback(new Error("In read-only mode.")); return callback("In read-only mode.");
database.deleteLine(data.id, callback); database.deleteLine(data.id, callback);
}, },
addView : function(data, callback) { addView : function(data, callback) {
if(!utils.stripObject(data, { name: "string", baseLayer: "string", layers: [ "string" ], top: "number", left: "number", right: "number", bottom: "number" }))
return callback("Invalid parameters.");
if(!socket.writable) if(!socket.writable)
return callback(new Error("In read-only mode.")); return callback("In read-only mode.");
database.createView(socket.padId, data, callback); database.createView(socket.padId, data, callback);
}, },
editView : function(data, callback) { editView : function(data, callback) {
if(!utils.stripObject(data, { id: "number", baseLayer: "string", layers: [ "string" ], top: "number", left: "number", right: "number", bottom: "number" }))
return callback("Invalid parameters.");
if(!socket.writable) if(!socket.writable)
return callback(new Error("In read-only mode.")); return callback("In read-only mode.");
database.updateView(data.id, data, callback); database.updateView(data.id, data, callback);
}, },
deleteView : function(data, callback) { deleteView : function(data, callback) {
if(!utils.stripObject(data, { id: "number" }))
return callback("Invalid parameters.");
if(!socket.writable) if(!socket.writable)
return callback(new Error("In read-only mode.")); return callback("In read-only mode.");
database.deleteView(data.id, callback); database.deleteView(data.id, callback);
}, },
addType : function(data, callback) {
// TODO: Strip object
if(!socket.writable)
return callback("In read-only mode.");
database.createType(socket.padId, data, callback);
},
editType : function(data, callback) {
// TODO: Strip object
if(!socket.writable)
return callback("In read-only mode.");
database.updateType(data.id, data, callback);
},
deleteType : function(data, callback) {
if(!utils.stripObject(data, { id: "number" }))
return callback("Invalid parameters.");
if(!socket.writable)
return callback("In read-only mode.");
database.deleteType(data.id, callback);
}/*,
copyPad : function(data, callback) { copyPad : function(data, callback) {
if(!utils.stripObject(data, { toId: "string" }))
return callback("Invalid parameters.");
database.copyPad(socket.padId, data.toId, callback); database.copyPad(socket.padId, data.toId, callback);
} }*/
}; };
for(var i in handlers) for(var i in handlers)

Wyświetl plik

@ -129,11 +129,57 @@ function generateRandomId(length) {
return randomPadId; return randomPadId;
} }
var FAILURE = { };
function stripObject(obj, structure) {
return _stripObject(obj, structure) !== FAILURE;
}
function _stripObject(obj, type) {
if(obj === undefined)
return obj;
else if(obj === null)
return obj;
else if(type instanceof Array) {
if(!(obj instanceof Array))
return FAILURE;
for(var i=0; i<obj.length; i++) {
if((obj[i] = _stripObject(obj[i], type[0])) === FAILURE)
return FAILURE;
}
return obj;
}
else if(typeof type == "function")
return (obj instanceof type) ? obj : FAILURE;
else if(type instanceof Object) {
if(!(obj instanceof Object))
return FAILURE;
for(var i in obj) {
if(type[i] == null || obj[i] === undefined)
delete obj[i];
else if((obj[i] = _stripObject(obj[i], type[i])) === FAILURE)
return FAILURE;
}
return obj;
}
else if(type == "number" && typeof obj == "string")
return isNaN(obj = 1*obj) ? FAILURE : obj;
else if(type == "string" && typeof obj == "number")
return ""+obj;
else if(typeof type == "string")
return (typeof obj == type) ? obj : FAILURE;
else
return FAILURE;
}
module.exports = { module.exports = {
isInBbox : isInBbox, isInBbox : isInBbox,
filterStream : filterStream, filterStream : filterStream,
filterStreamAsync : filterStreamAsync, filterStreamAsync : filterStreamAsync,
extend : extend, extend : extend,
calculateDistance : calculateDistance, calculateDistance : calculateDistance,
generateRandomId : generateRandomId generateRandomId : generateRandomId,
stripObject : stripObject
}; };

Wyświetl plik

@ -4,7 +4,7 @@
"author": "Candid Dauth <cdauth@cdauth.eu>", "author": "Candid Dauth <cdauth@cdauth.eu>",
"version": "0.0.1", "version": "0.0.1",
"dependencies": { "dependencies": {
"mongoose": "x.x.x", "sequelize": "x.x.x",
"socket.io": "x.x.x", "socket.io": "x.x.x",
"async" : "x.x.x", "async" : "x.x.x",
"request" : "x.x.x", "request" : "x.x.x",