-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmodel.js
358 lines (320 loc) · 9.7 KB
/
model.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*
model.js
This file is required. It must export a class with at least one public function called `getData`
Documentation: http://koopjs.github.io/docs/specs/provider/
*/
const request = require('request-promise').defaults({
gzip: true,
json: true
})
const _ = require('lodash')
const FeatureService = require('featureservice')
const baseGeoJSON = require('./base-geojson')
const terraformer = require('terraformer')
/**
*
* @param {*} koop
*/
function Model(koop) {
//this.indicator = {}
this.getData = function (req, callback) {
if (!req.query.outSR) {
req.query.outSR = 4326
}
if (!req.query.f) {
req.query.f = 'json'
}
this.cache.catalog.retrieve(req.params.id, function (e, schema) {
if (e) return callback(e)
if (schema.indicator_schema.metadata) {
baseGeoJSON.metadata = schema.indicator_schema.metadata
}
buildQueries(schema.aggregate_schemas, req.query, function (err, data) {
if (err) return callback(err)
Promise.all(
data.map(function (d) {
console.log(d.url);
return request({
uri: d.url,
schema: d,
transform: function (b) {
return translateFields(b, this.schema)
}
})
})).then(function (results) {
// everything is done, combine the results and send it along
if (results[0] && results[0].count) {
var c = {}
c.count = results.reduce(function (pVal, cVal) {
return pVal + cVal.count
}, 0)
return callback(null, c)
}
var agg = baseGeoJSON
const combinedFeatures = results.reduce(function (pre, curr) {
if (curr) return pre.concat(curr)
return pre
}, [])
agg.filtersApplied = {
all:true
}
// console.log(agg.metadata)
// agg.features = combinedFeatures || []
agg.features = combinedFeatures.slice(0, req.query.resultRecordCount || combinedFeatures.length)
return callback(null, agg)
})
.catch(function (err) {
return callback(err);
})
})
})
}
var counter = 0;
this.getDatasetSchema = function (req, res, callback) {
this.cache.catalog.retrieve(req.params.id, function (e, data) {
if (e) return callback(e, `unable to find intitiative ${req.params.id}`, res)
return callback(null, data.aggregate_schemas[req.params.schema], res)
})
}
this.putDatasetSchema = function (req, res, callback) {
const rCache = this.cache
rCache.catalog.retrieve(req.params.id, function (e, data) {
if (e) return callback(e, `unable to find intitiative ${req.params.id}`, res)
// retrieve adds geojson schema by default, is this appropriate?
data.aggregate_schemas = data.aggregate_schemas || {}
data.aggregate_schemas[req.params.schema] = req.body
// TODO - Update Indicator Extent, after inserting a new agg service
rCache.catalog.update(req.params.id, data, function (err) {
if (err) return callback(err, 'unable to add schema definition', res)
var d = data.aggregate_schemas[req.params.schema]
callback(e, d, res)
})
})
}
this.removeDatasetSchema = function (req, res, callback) {
const rCache = this.cache
rCache.catalog.retrieve(req.params.id, function (e, data) {
if (e) return callback(e, `unable to find intiative : ${req.params.id}`, res)
delete data.aggregate_schemas[req.params.schema]
rCache.catalog.update(req.params.id, data, function (err) {
if (err) callback(err, `unable to remove schema definition : ${req.params.schema}`, res)
return callback(null, `${req.params.schema} sucessfully removed`, res)
})
})
}
this.getDataset = function (req, res, callback) {
this.cache.catalog.retrieve(req.params.id, function (err, data) {
if (err) return callback(err, `Unable to get ${req.params.id}`, res)
callback(null, data, res)
})
}
this.putDataset = function (req, res, callback) {
// put the initiative schema map into a cache
//
// validate these before inserting?
this.cache.catalog.insert(req.params.id, req.body, function (e) {
if (e) return callback(e, 'unable to put initiative', res)
return callback(null, req.body, res)
})
}
/**
*
*/
this.removeDataset = function (req, res, callback) {
this.cache.catalog.delete(req.params.id, function (err) {
if (err) return callback(err, `unable to find ${req.params.id}, nothing to delete`, res)
callback(null, `${req.params.id} successfully removed`, res)
})
}
}
/**
*
* @param {*} schema
* @param {*} query
* @param {*} qcb
*/
function buildQueries(schema, query, qcb) {
// for each schema
const validExtents = Object.keys(schema)
.filter(function (itm) {
return isValidExtent(schema[itm], query);
})
const urls = validExtents
.map(
function (k) {
const srvcSchema = schema[k]
const base = srvcSchema.url
const fldMap = srvcSchema.fieldMap
// const swizzledQuery = _.cloneDeep(query)
// var tQuery = translateQuery(fldMap, query)
// if (tQuery.where) swizzledQuery.where = tQuery.where
const swizzledQuery = translateQuery(fldMap, query, validExtents.length);
const newQuery = getAsParams(swizzledQuery)
const newURL = `${base}?${newQuery}`
return {
url: newURL,
schema: srvcSchema,
q: swizzledQuery
}
}
)
qcb(null, urls)
/* paging?
async.map(urls, getFSUrls, (e,r)=>{
qcb(null, r.reduce((p,c)=>{return p.concat(c)}))
})
*/
}
/**
* only send queries if they fall in our aoi
* @param {*extent of query} geometry sent in query extent
* @param {*extent of schema} Extent of baseSchema to compare against
*/
function isValidExtent (schema, query) {
if (schema.extent && query.geometry) {
var sJSON = {
"type": "Polygon",
"coordinates": [[
[schema.extent.xmin, schema.extent.ymin],
[schema.extent.xmax, schema.extent.ymin],
[schema.extent.xmax, schema.extent.ymax],
[schema.extent.xmin, schema.extent.ymax]
]]
}
terraformer.Tools.toGeographic(sJSON)
var sPoly = new terraformer.Primitive(sJSON);
sPoly.close();
//
var qj = JSON.parse(query.geometry)
var qJSON = {
"type": "Polygon",
"coordinates": [[
[qj.xmin, qj.ymin],
[qj.xmax, qj.ymin],
[qj.xmax, qj.ymax],
[qj.xmin, qj.ymax]
]]
}
terraformer.Tools.toGeographic(qJSON)
var qPoly = new terraformer.Primitive(qJSON)
qPoly.close()
var i = qPoly.intersects(sPoly);
return i
}
// schema or query doesn't have a specified boundary
// let it through
return true;
}
/**
*
* @param {*} itm
*/
function requestASync(itm) {
return new Promise(function (resolve, reject) {
request(itm.url, function (err, res, body) {
if (err) return reject(err)
if (itm.q.returnCountOnly || itm.q.returnIdsOnly) {
return resolve(body.properties)
}
const features = translateFields(body, itm)
return resolve(features)
})
})
}
/**
*
* @param {*} i
* @param {*} cb
*/
function getFSUrls(i, cb) {
const fs = new FeatureService(i.url, {
where: i.where
})
fs.pages(function (e, pages) {
if (e) cb(e)
cb(
null,
pages.map(function (p) {
return {
url: p.req,
schema: i.schema
}
}))
})
}
function getIndicator(results) {
console.log('Get Results')
}
/**
*
* @param {*} queryObj
*/
function getAsParams(queryObj = {}) {
let str = []
const xParams = ['callback', 'outStatistics']
for (var i = 0, keys = Object.keys(queryObj); i < keys.length; i++) {
var prop = keys[i]
if (!xParams.includes(prop)) {
str.push(encodeURIComponent(prop) + '=' + encodeURIComponent(queryObj[prop]))
}
}
return str.join('&')
}
/**
*
* @param {*} ofResults
* @param {*} toSchema
*/
function translateFields(ofResults, toSchema) {
if (!ofResults.features || ofResults.features.length === 0) {
// if incoming results set is from a query with `returnCountOnly=true`
if (ofResults.count) {
return { count: ofResults.count }
} else {
return null
}
}
return ofResults.features.map(function (f) {
let newProps = {}
let att = f.attributes ? f.attributes : f.properties
const prefixID = toSchema.schema.oidPreFix || (Date.now() * (Math.random() * 30000))
Object.keys(att).forEach(function (fAtt) {
for (var prop in toSchema.schema.fieldMap) {
if (fAtt === toSchema.schema.fieldMap[prop]) {
newProps[prop] = att[fAtt]
}
}
})
// try and pseudo randomize an objectid
newProps.aid = parseInt(`${prefixID}${f.id}`,10)
newProps.sourceservice = toSchema.url.split('?')[0]
return {
attributes: newProps,
geometry: f.geometry
}
})
}
/**
*
* @param {*} fields
* @param {*} query
*/
function translateQuery(fields, query, servicesCount) {
// replace query fields with fields from the schema map
query = _.cloneDeep(query)
if (!query.where) return
if (query.orderByFields === 'aid ASC' || query.orderByFields === 'aid DESC') {
delete query.orderByFields
}
if (query.resultOffset) {
query.resultOffset = Math.floor(query.resultOffset / servicesCount)
}
for (var f in fields) {
query.where = query.where.replace(new RegExp(f, 'g'), fields[f])
if (query.orderByFields) {
query.orderByFields = query.orderByFields.replace(new RegExp(f, 'g'), fields[f])
}
}
return query
}
module.exports = Model