-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathworld.js
75 lines (60 loc) · 1.54 KB
/
world.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
var async = require('async'),
core = require('./core'),
protos = require('./protos'),
traits = require('./traits'),
factory = require('./factory'),
ObjectId = require('mongoose').Types.ObjectId,
models = require('./models');
var theWorld = {};
exports.build = function(world, callback) {
world.forEach(function(roomData) {
var room = factory.createRoom(roomData);
if (room._id in theWorld) {
throw new Error('room id ' + room.id + ' is already used.');
}
theWorld[room._id] = room;
});
//persist the world to the DB.
var tasks = [];
for (roomID in theWorld) {
var room = theWorld[roomID];
//ensure scope!
(function(room) {
tasks.push(function(cb) {
room.save(function(err) {
if (err) cb(err);
else cb(null);
});
});
})(room);
}
async.parallel(tasks, function(err) {
if (err) return callback(err);
callback(null);
});
}
exports.getRoom = function(id) {
if (!(id instanceof ObjectId)) {
id = new ObjectId(id);
}
if (!(id in theWorld)) {
throw new Error('room id ' + id + ' does not exist in the world.');
}
return theWorld[id];
}
exports.deleteRoom = function(id) {
if (!(id in theWorld)) {
throw new Error('room id ' + id + ' does not exist in the world.');
}
return delete theWorld[id];
}
exports.load = function(callback) {
models.Room.find({}, function(err, roomDocs) {
if (err) return callback(err);
roomDocs.forEach(function(roomData) {
var room = factory.createRoom(roomData, true);
theWorld[room._id] = room;
});
callback(null, theWorld);
});
}