-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
new-api.js
260 lines (227 loc) · 7.07 KB
/
new-api.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
import 'core-js/es/reflect'
import ky from 'ky/umd'
import logger from '../logger'
import UriTemplate from 'uri-templates'
export default Api({
// globals are set in src/renderer/index-preload.js
ipc: window.middlewareClient,
baseUrl: `http://127.0.0.1:${window.mapeoServerPort}/`,
mapUrl: `http://127.0.0.1:${window.mapPrinterPort}/`
})
function Api ({ baseUrl, mapUrl, ipc }) {
// We append this to requests for presets and map styles, in order to override
// the local static server cache whenever the app is restarted. NB. sprite,
// font, and map tile requests might still be cached, only changes in the map
// style will be cache-busted.
const startupTime = Date.now()
const req = ky.create({
prefixUrl: baseUrl,
// No timeout because indexing after first sync takes a long time, which mean
// requests to the server take a long time
timeout: false,
headers: {
'cache-control': 'no-cache',
pragma: 'no-cache'
}
})
function logRequest (prefix, promise) {
const start = Date.now()
promise
.then(data => {
logger.debug(prefix, Date.now() - start + 'ms')
})
.catch(error => {
// Preset errors aren't fatal errors.
if (prefix.indexOf('presets') > -1) logger.info(prefix, error)
// Styles errors aren't fatal errors either.
else if (prefix.indexOf('styles') > -1) logger.info(prefix, error)
else logger.error(prefix, error)
})
return promise
}
// Request convenience methods that wait for the server to be ready
function get (url) {
return logRequest('<GET: ' + url, req.get(url).json())
}
function del (url) {
return logRequest('<DEL: ' + url, req.delete(url).json())
}
function put (url, data) {
return logRequest('<PUT: ' + url, req.put(url, { json: data }).json())
}
function post (url, data) {
return logRequest('<POST: ' + url, req.post(url, { json: data }).json())
}
// All public methods
const api = {
getBaseUrl: function getBaseUrl () {
return baseUrl
},
/**
* GET async methods
*/
getPresets: function getPresets (id) {
if (!id) id = 'default'
return get(`presets/${id}/presets.json?${startupTime}`)
},
getObservations: function getObservations () {
return get('observations')
},
getMapStyle: function getMapStyle (id) {
return get(`styles/${id}/style.json?${startupTime}`)
},
getMetadata: function getMetadata () {
return get(`presets/default/metadata.json?${Date.now()}`).then(
data => data || {}
)
},
/**
* DELETE methods
*/
deleteObservation: function deleteObservation (id) {
return del(`observations/${id}`)
},
/**
* PUT and POST methods
*/
updateObservation: function updateObservation (id, value) {
const valueForServer = {
...value,
type: 'observation',
schemaVersion: 3,
id
}
return put(`observations/${id}`, valueForServer)
},
createObservation: function createObservation (value) {
const valueForServer = {
...value,
type: 'observation',
schemaVersion: 3
}
return post('observations', valueForServer)
},
/**
* SYNC methods
*/
// Listens to the server for updates to the list of peers available for sync
// returns a remove() function to unscubribe
addPeerListener: function addPeerListener (handler) {
// We sidestep the http API here, and instead of polling the endpoint, we
// listen for an event from mapeo-core whenever the peers change, then
// request an updated peer list.
function onPeerUpdate (peers) {
logger.debug('peer-update', peers)
handler(peers)
}
ipc.on('peer-update', onPeerUpdate)
api.syncGetPeers().then(handler)
return {
remove: () => ipc.removeListener('peer-update', onPeerUpdate)
}
},
addDataChangedListener: function (ev, handler) {
ipc.on('sync-complete', handler)
ipc.on(ev, handler)
return {
remove: () => {
ipc.removeListener('sync-complete', handler)
ipc.removeListener(ev, handler)
}
}
},
getEncryptionKey: function () {
return new Promise((resolve, reject) => {
ipc.send('encryption-key', null, (err, encryptionKey) => {
if (err) return reject(err)
resolve(encryptionKey)
})
})
},
// Start listening for sync peers and advertise with `deviceName`
syncJoin: function syncJoin () {
logger.debug('Join sync')
ipc.send('sync-join')
},
// Stop listening for sync peers and stop advertising
syncLeave: function syncLeave () {
logger.debug('Leave sync')
ipc.send('sync-leave')
},
// Get a list of discovered sync peers
syncGetPeers: function syncGetPeers () {
return get('sync/peers').then(data => data && data.message)
},
// Start sync with a peer
syncStart: function syncStart (target, createFile) {
ipc.send('sync-start', { target, createFile })
},
exportData: function (filename, { format = 'geojson' } = {}) {
return new Promise((resolve, reject) => {
ipc.send('export-data', { filename, format }, err => {
if (err) {
logger.error('export data', err)
reject(err)
} else resolve()
})
})
},
getData: function (opts) {
return new Promise((resolve, reject) => {
ipc.send('get-data', opts, (err, res) => {
if (err) {
logger.error('export data', err)
reject(err)
} else resolve(res)
})
})
},
/**
* HELPER synchronous methods
*/
// Return the url for an icon
getIconUrl: function getIconUrl (iconId, size = 'medium') {
// Some devices are @4x or above, but we only generate icons up to @3x
// Also we don't have @1.5x, so we round it up
const roundedRatio = Math.min(Math.ceil(window.devicePixelRatio), 3)
return `${baseUrl}presets/default/icons/${iconId}-medium@${roundedRatio}x.png`
},
// Return the url for a media attachment
getMediaUrl: function getMediaUrl (attachmentId, size = 'preview') {
return `${baseUrl}media/${size}/${attachmentId}`
},
// Return the url to a map style
getMapStyleUrl: function getMapStyleUrl (id) {
return `${baseUrl}styles/${id}/style.json?${startupTime}`
},
getCentroid: function (type, cb) {
ipc.send('zoom-to-data-get-centroid', type, cb)
},
getMapImageTemplateURL: function () {
return `${mapUrl}map/{lon}/{lat}/{zoom}/{width}/{height}/x{dpi}.png{?style,accessToken}`
},
getMapImageURL: function ({
lon,
lat,
zoom,
width = 300,
height = 300,
dpi = 1,
style,
accessToken
}) {
const template = new UriTemplate(api.getMapImageTemplateURL())
return template.fillFromObject({
lon,
lat,
zoom,
width,
height,
dpi,
style,
accessToken
})
}
}
return api
}