1 | var contentType = require('content-type')
|
2 | var randombytes = require('randombytes')
|
3 | var convert = require('base-convertor')
|
4 | var JSONStream = require('JSONStream')
|
5 |
|
6 | var version = require('../package.json').version
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | function refs2nodes (doc) {
|
14 | var element = {}
|
15 | for (var prop in doc) {
|
16 | if (!doc.hasOwnProperty(prop)) continue
|
17 | if (prop === 'refs') {
|
18 | element.nodes = doc.refs
|
19 | } else {
|
20 | element[prop] = doc[prop]
|
21 | }
|
22 | }
|
23 | return element
|
24 | }
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | function nodes2refs (obj) {
|
32 | var doc = {}
|
33 | for (var prop in obj) {
|
34 | if (!obj.hasOwnProperty(prop)) continue
|
35 | if (prop === 'nodes') {
|
36 | doc.refs = obj.nodes
|
37 | } else {
|
38 | doc[prop] = obj[prop]
|
39 | }
|
40 | }
|
41 | return doc
|
42 | }
|
43 |
|
44 | var TEMPLATE = {
|
45 | version: 0.6,
|
46 | generator: 'osm-p2p v' + version,
|
47 | elements: []
|
48 | }
|
49 |
|
50 | var SEP = ',\n '
|
51 |
|
52 | function OsmJSONStream (opts) {
|
53 | var template = Object.assign({}, TEMPLATE, opts)
|
54 | var openClose = JSON.stringify(template, null, 4).split('"elements": [')
|
55 | var open = openClose[0] + '"elements": [\n '
|
56 | var close = '\n ' + openClose[1]
|
57 | return JSONStream.stringify(open, SEP, close)
|
58 | }
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 | function cmpFork (a, b) {
|
65 | if (a.timestamp && b.timestamp) {
|
66 | if (a.timestamp > b.timestamp) return -1
|
67 | if (a.timestamp < b.timestamp) return 1
|
68 | return 0
|
69 | }
|
70 | if (a.timestamp) return -1
|
71 | if (b.timestamp) return 1
|
72 |
|
73 | return a.version < b.version ? -1 : 1
|
74 | }
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | function generateId () {
|
80 | return hex2dec(randombytes(8).toString('hex'))
|
81 | }
|
82 |
|
83 | function hex2dec (hex) {
|
84 | return convert(hex.toUpperCase(), '0123456789ABCDEF', '0123456789')
|
85 | }
|
86 |
|
87 | function isValidContentType (req) {
|
88 | try {
|
89 | if (/\/xml$/.test(contentType.parse(req).type)) {
|
90 | return true
|
91 | }
|
92 | } catch (e) {}
|
93 | }
|
94 |
|
95 | module.exports = {
|
96 | refs2nodes: refs2nodes,
|
97 | nodes2refs: nodes2refs,
|
98 | generateId: generateId,
|
99 | isValidContentType: isValidContentType,
|
100 | cmpFork: cmpFork,
|
101 | OsmJSONStream: OsmJSONStream
|
102 | }
|