-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathprocessFile.js
101 lines (96 loc) · 3.41 KB
/
processFile.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
/*
* Copyright 2022, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import {get} from 'lodash';
import proj4 from 'proj4';
import { compose, createEventHandler, mapPropsStream } from 'recompose';
import Rx from 'rxjs';
import {
MIME_LOOKUPS,
readJson,
recognizeExt
} from '@mapstore/utils/FileUtils';
import {flattenImportedFeatures} from "@js/extension/utils/geojson";
import {parseURN} from "@mapstore/utils/CoordinatesUtils";
/**
* Checks if the file is allowed. Returns a promise that does this check.
*/
const checkFileType = (file) => {
return new Promise((resolve, reject) => {
const ext = recognizeExt(file.name);
const type = file.type || MIME_LOOKUPS[ext];
if (type === 'application/json') {
resolve(file);
} else {
reject(new Error("FILE_NOT_SUPPORTED"));
}
});
};
/**
* Create a function that return a Promise for reading file. The Promise resolves with an array of (json)
*/
const readFile = () => (file) => {
const ext = recognizeExt(file.name);
const type = file.type || MIME_LOOKUPS[ext];
if (type === 'application/json') {
return readJson(file).then(f => {
const projection = get(f, 'map.projection') ?? parseURN(get(f, 'crs'));
if (projection) {
const supportedProjection = proj4.defs(projection);
if (supportedProjection) {
return [{...f, "fileName": file.name}];
}
throw new Error("PROJECTION_NOT_SUPPORTED");
}
return [{...f, "fileName": file.name}];
});
}
return null;
};
/**
* Enhancers a component to process files on drop event.
* Recognizes map files (JSON format) or vector data in various formats.
* They are converted in JSON as a "files" property.
*/
export default compose(
mapPropsStream(
props$ => {
const { handler: onDrop, stream: drop$ } = createEventHandler();
const { handler: onWarnings, stream: warnings$} = createEventHandler();
return props$.combineLatest(
drop$.switchMap(
files => Rx.Observable.from(files)
.flatMap(checkFileType) // check file types are allowed
.flatMap(readFile(onWarnings)) // read files to convert to json
.map(res => {
return ({
loading: false,
flattenFeatures: flattenImportedFeatures(res),
crs: res[0]?.crs?.properties?.name ?? 'EPSG:4326'
});
})
.catch(error => Rx.Observable.of({error, loading: false}))
.startWith({ loading: true})
)
.startWith({}),
(p1, p2) => ({
...p1,
...p2,
onDrop
})
).combineLatest(
warnings$
.scan((warnings = [], warning) => ([...warnings, warning]), [])
.startWith(undefined),
(p1, warnings) => ({
...p1,
warnings
})
);
}
)
);