-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
283 lines (237 loc) · 8.93 KB
/
index.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
var _ = require('lodash')
, async = require('async');
// The `apostrophe-places` module provides map locations (pieces with geolocation).
//
// ### options
//
// `dailyLimit`: defaults to `2500`, Google's free limit
//
// `rateLimit`: defaults to `10` (per second), Google's free limit
//
// `apiKey`: MUST be provided. Google will not geocode for new domains without one
//
// `cacheLifetime`: how long to cache coordinates corresponding to addresses, in seconds.
// Defaults to `86400` (one day). Street addresses don't move around much.
//
// `geocoder`: passed on directly to the `apostrophe-places-geocoder` instance (or the
// subclass corresponding to your subclass), which in turn passes them on to the `node-geocoder`
// npm module.
//
// `infoBoxPositionX`: The X offset (in pixels) from the top left corner of the InfoBox (or the bottom left corner if the alignBottom property is true) to the map pixel corresponding to position.
//
// `infoBoxPositionY`: The Y offset (in pixels) from the top left corner of the InfoBox (or the bottom left corner if the alignBottom property is true) to the map pixel corresponding to position.
module.exports = {
name: 'apostrophe-place',
alias: 'places',
label: 'Place',
extend: 'apostrophe-pieces',
map: {
browser: {
// Hey, you have to configure me or it'll fail in production!
// Yes really
key: null
}
},
moogBundle: {
modules: ['apostrophe-places-pages', 'apostrophe-places-widgets'],
directory: 'lib/modules'
},
afterConstruct: function(self, callback) {
self.addNullIslandMigration();
self.addNullIslandMigration2();
if (!(self.options && self.options.map && self.options.map.browser && self.options.map.browser.key)) {
console.error('*** Beginning July 2016 Google REQUIRES an API key for all new domains.');
console.error('Make sure you get one and configure the "key" options for both the server and');
console.error('the browser:\n\n');
console.error(JSON.stringify({
key: 'your server key here',
map: {
browser: {
key: 'your browser key here'
}
}
} , null, ' '));
console.error('\n\n');
console.error('Otherwise it may work in dev & staging but WILL FAIL in production.');
}
self.pushAsset('script', 'always', { when: 'always' });
self.pushAsset('stylesheet', 'map', { when: 'always' });
var tools = [ 'map' ];
_.each(tools, function(tool) {
self.apos.push.browserMirrorCall('always', self, { 'tool': tool, stop: 'apostrophe-places' });
var _options = (self.options && self.options[tool] && self.options[tool].browser) || {};
// Otherwise there's really only one when multiple subclasses are
// in play. TODO consider whether this makes self-documenting
// options a bad idea when they are objects
_options = _.cloneDeep(_options);
_.defaults(_options, {
name: self.__meta.name
});
self.apos.push.browserCall('always', 'apos.create(? + "-" + ?, ?)', self.__meta.name, tool, _options);
});
// Set up our route for serving
self.apos.app.post(self.action + '/infoBox', function(req, res) {
return res.send(self.render(req, '_infoBox', { item: req.body }));
});
return async.series([
self.ensureIndex,
self.enableGeocoder
], callback);
},
beforeConstruct: function(self, options) {
options.sort = { title: 1 };
if (options.map && options.map.browser) {
_.defaults(options.map.browser, {
infoBoxPositionX: 10,
infoBoxPositionY: -137
});
}
options.addFields = [
{
name: 'address',
label: 'Address',
type: 'string',
help: 'Must be a complete address unless latitude and longitude are specified.'
},
{
name: 'lat',
label: 'Latitude',
type: 'float',
def: null,
help: 'If omitted, the address will be looked up for you. West longitudes are negative.'
},
{
name: 'lng',
label: 'Longitude',
type: 'float',
def: null,
help: 'If omitted, the address will be looked up for you. North latitudes are positive.'
},
].concat(options.addFields || []);
options.arrangeFields = _.merge([
{ name: 'basic', label: 'Basics', fields: ['title', 'slug', 'address'] },
], options.arrangeFields || []);
options.mapInfoBoxFields = _.union(['_id', 'slug', 'title', 'tags', 'address', 'url', 'geo'], options.mapInfoBoxFields || []);
},
construct: function(self, options) {
var superFind = self.find;
self.addHelpers({
pruneMapLocations: self.pruneMapLocations
});
self.pruneMapLocations = function(items) {
var result = _.map(items, function(item) {
return _.pick(item, options.mapInfoBoxFields);
});
return result;
};
// limit the results of autocomplete for joins
// so they only include
self.extendAutocompleteCursor = function(cursor) {
// return cursor.upcoming(true);
};
if(!options.key) {
console.log('WARNING: You need to provide a Google maps API key in your options in order for this module to work in the wild');
}
self.beforeSave = function(req, piece, options, callback) {
return self.geocoder.geocodePiece(piece, callback);
};
// Ensure there is a 2dsphere index for the `geo` property of a doc. Note that this means
// all docs in a project utilizing this module must use a property named `geo` only for a
// geoJSON point (if they have such a property at all).
self.ensureIndex = function(callback) {
return async.series([
fixType,
ensureIndex
], callback);
// Cope with projects where the "type" property of the geo object is somehow missing.
// Otherwise the index will crash. TODO: consider removing this later, it should never have been
// necessary. It can't be a migration because of chicken and egg issues.
function fixType(callback) {
return self.apos.docs.db.update({
type: self.name,
geo: { $type: 3 },
'geo.type': { $exists: 0 }
}, {
$set: {
'geo.type': 'Point'
}
}, {
multi: true
},
callback);
}
function ensureIndex(callback) {
return self.apos.docs.db.ensureIndex({ geo: '2dsphere' }, {}, callback);
}
};
self.defineRelatedType('geocoder', {
stop: 'apostrophe-module'
});
// Sets self.geocoder to an instance of `apostrophe-places-geocoder` (or the appropriate subclass for your subclass).
// Passes on the `rateLimit`, `dailyLimit`, `key` and `name` options, plus all properties of the
// `geocoder` option if you provide one
self.enableGeocoder = function(callback) {
var geocoderOptions = self.options.geocoder || {};
if (options.rateLimit !== undefined) {
geocoderOptions.rateLimit = options.rateLimit;
}
if (options.dailyLimit !== undefined) {
geocoderOptions.dailyLimit = options.dailyLimit;
}
_.defaults(geocoderOptions, {
apiKey: options.key || options.apiKey,
name: self.name,
apos: self.apos
});
return self.createRelatedType('geocoder', geocoderOptions, function(err, geocoder) {
if (err) {
return callback(err);
}
self.geocoder = geocoder;
return callback(null);
});
};
self.addNullIslandMigration = function() {
self.apos.migrations.add(self.__meta.name + '.nullIsland', function(callback) {
var needed;
return self.apos.docs.db.update(
{ type: self.name, lat: 0, lng: 0 },
{ $set: { lat: null, lng: null } },
{ multi: true },
function(err, result) {
if (err) {
return callback(err);
}
if (result && result.result && result.result.nModified > 0) {
console.log('Set lat and lng of ' + result.result.nModified + ' ' + self.name + ' docs to null rather than "Null Island" (0, 0)');
}
return callback(null);
}
);
}, {
safe: true
});
};
self.addNullIslandMigration2 = function() {
self.apos.migrations.add(self.__meta.name + '.nullIsland2', function(callback) {
var needed;
return self.apos.docs.db.update(
{ type: self.name, 'geo.coordinates.0': 0, 'geo.coordinates.1': 0 },
{ $set: { geo: null } },
{ multi: true },
function(err, result) {
if (err) {
return callback(err);
}
if (result && result.result && result.result.nModified > 0) {
console.log('Set lat and lng of ' + result.result.nModified + ' ' + self.name + ' docs to null rather than "Null Island" (0, 0)');
}
return callback(null);
}
);
}, {
safe: true
});
};
}
};