-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
74 lines (52 loc) · 1.62 KB
/
reader.go
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
package database
import (
"context"
"fmt"
"io"
"log/slog"
"github.com/paulmach/orb/geojson"
"github.com/tidwall/gjson"
"github.com/whosonfirst/go-whosonfirst-feature/geometry"
)
// IndexDatabaseWithReader will index the data contained in 'r' in 'db'.
func IndexDatabaseWithReader(ctx context.Context, db SpatialDatabase, r io.Reader) error {
index_func := func(ctx context.Context, body []byte, geom_type string) error {
switch geom_type {
case "Polygon", "MultiPolygon":
return db.IndexFeature(ctx, body)
default:
slog.Warn("Record in unsupported geometry type, skipping", "type", geom_type)
return nil
}
}
body, err := io.ReadAll(r)
if err != nil {
return fmt.Errorf("Failed to read document, %w", err)
}
geom_type, err := geometry.Type(body)
if err == nil {
return index_func(ctx, body, geom_type)
}
// Check to see if this is a FeatureCollection
t_rsp := gjson.GetBytes(body, "type")
if !t_rsp.Exists() || t_rsp.String() != "FeatureCollection" {
return fmt.Errorf("Failed to derive geometry type for record, %w", err)
}
// If it is process each file
fc, err := geojson.UnmarshalFeatureCollection(body)
if err != nil {
return fmt.Errorf("Failed to unmarshal record in to a FeatureCollection, %w", err)
}
for i, f := range fc.Features {
f_body, err := f.MarshalJSON()
if err != nil {
return fmt.Errorf("Failed to marshal Feature at offset %d in record, %w", i, err)
}
geom_type := f.Geometry.GeoJSONType()
err = index_func(ctx, f_body, geom_type)
if err != nil {
return fmt.Errorf("Failed to index Feature at offset %d in record, %w", i, err)
}
}
return nil
}