UNPKG

2.5 kBJavaScriptView Raw
1var contentType = require('content-type')
2var randombytes = require('randombytes')
3var convert = require('base-convertor')
4var JSONStream = require('JSONStream')
5
6var version = require('../package.json').version
7
8/**
9 * Converts objects from osm-p2p to objects compatible with the OSM JSON format
10 * @param {object} doc object from osm-p2p
11 * @return {object} object compatible with the OSM JSON format
12 */
13function 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 * Converts objects from OSM JSON to objects compatible with osm-p2p
28 * @param {object} obj object from parsing OSM JSON
29 * @return {object} object compatible with osm-p2p
30 */
31function 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
44var TEMPLATE = {
45 version: 0.6,
46 generator: 'osm-p2p v' + version,
47 elements: []
48}
49
50var SEP = ',\n '
51
52function 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 * Sort function to sort forks by most recent first, or by version id
62 * if no timestamps are set
63 */
64function 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 // Ensure sorting is stable between requests
73 return a.version < b.version ? -1 : 1
74}
75
76/**
77 * Generate a unique 64-bit id string which can be parsed as a 64-bit integer
78 */
79function generateId () {
80 return hex2dec(randombytes(8).toString('hex'))
81}
82
83function hex2dec (hex) {
84 return convert(hex.toUpperCase(), '0123456789ABCDEF', '0123456789')
85}
86
87function isValidContentType (req) {
88 try {
89 if (/\/xml$/.test(contentType.parse(req).type)) {
90 return true
91 }
92 } catch (e) {}
93}
94
95module.exports = {
96 refs2nodes: refs2nodes,
97 nodes2refs: nodes2refs,
98 generateId: generateId,
99 isValidContentType: isValidContentType,
100 cmpFork: cmpFork,
101 OsmJSONStream: OsmJSONStream
102}