UNPKG

1.9 kBJavaScriptView Raw
1var util = require('../lib/util')
2var errors = require('../errors')
3
4/**
5 * Replace placeholder ids with generated unique ids
6 * - Any `id` of a created object is considered a placeholder id
7 * - Throws an error if placeholder ids are not unique within types
8 * - Does not mutate arguments
9 * - cb() with array of changes with ids replaced and an additional
10 * `old_id` prop if the id has been replaced.
11 */
12module.exports = function replacePlaceholderIds (changes, cb) {
13 var idMap = {
14 node: {},
15 way: {},
16 relation: {}
17 }
18 var dupIds = []
19 // First pass to generate ids for the elements that are created.
20 // This ensures that by the second pass we have all the ids generated
21 // to replace them in the way's nodes.
22 var changesWithIds = changes.map(function (change) {
23 var mapped = Object.assign({}, change)
24 if (change.action === 'create') {
25 if (idMap[change.type][change.id] || !change.id) {
26 dupIds.push(change.id)
27 }
28 var id = util.generateId()
29 idMap[change.type][change.id] = id
30 mapped.id = id
31 mapped.old_id = change.id
32 }
33 return mapped
34 })
35 // Second pass. Handle id replacement.
36 .map(function (change) {
37 // no need to Object.assign() here because we have already cloned and can mutate
38 if (change.type === 'way' && change.nodes) {
39 change.nodes = change.nodes.map(function (ref) {
40 return idMap.node[ref] || ref
41 })
42 }
43 if (change.type === 'relation' && change.members) {
44 change.members = change.members.map(function (member) {
45 if (!idMap[member.type][member.ref]) return Object.assign({}, member)
46 return Object.assign({}, member, {ref: idMap[member.type][member.ref]})
47 })
48 }
49 return change
50 })
51 if (dupIds.length) {
52 var errMsg = '#' + dupIds.join(', #')
53 return cb(new errors.PlaceholderIdError(errMsg))
54 }
55 cb(null, changesWithIds)
56}