Parcourir la source

added p5WFS_GetFeatureFromXml

Piotr Labudda il y a 8 ans
Parent
commit
5c72e86149
1 fichiers modifiés avec 39 ajouts et 4 suppressions
  1. 39 4
      SE/static/p5WFS/GetFeature.js

+ 39 - 4
SE/static/p5WFS/GetFeature.js

@@ -1,6 +1,7 @@
 // @require WFS_URL
 if (!WFS_URL) throw "Missing WFS_URL"
 var DBG = DBG || false
+var httpFetch = window.fetch
 
 // wfsFeature json format:
 /*
@@ -178,7 +179,7 @@ function p5WFS_GetFeature(typeName, query) { // @returns Promise
 	}
 	var method = (postData) ? 'POST' : 'GET'
 
-	return window.fetch(link, Object.assign({
+	return httpFetch(link, Object.assign({
 		method: method,
 		credentials: 'include',
 	}, ('POST' === method)
@@ -213,6 +214,40 @@ function p5WFS_GetFeature(typeName, query) { // @returns Promise
 	})
 }
 
-global.p5WFS_ParseFeatureMember = p5WFS_ParseFeatureMember
-global.p5WFS_ParseFeatureFieldRecurse = p5WFS_ParseFeatureFieldRecurse
-global.p5WFS_GetFeature = p5WFS_GetFeature
+function p5WFS_GetFeatureFromXml(url) {
+	return httpFetch(url, {
+		method: 'GET',
+		credentials: 'include',
+	}).then(function (response) {
+		return response.text()
+	}).then(function (responseText) {
+		return (new DOMParser()).parseFromString(responseText, "text/xml");
+	}).then(function (xmlResponse) {
+		if (!xmlResponse.children.length) throw "Missing response xml root element"
+		return xmlResponse.children[0]
+	}).then(function (xmlRoot) {
+		if ('html' === xmlRoot.localName) {
+			console.log(xmlRoot) // html / body / parseerror / div
+			throw "Parse xml error"
+		}
+		if ('FeatureCollection' !== xmlRoot.localName) {
+			if ('ServiceExceptionReport' === xmlRoot.tagName) {
+				if (xmlRoot.children[0] && xmlRoot.children[0].textContent) throw xmlRoot.children[0].textContent
+				throw "WFS API Exception"
+			}
+			throw "Missing FeatureCollection as root element in wfs response"
+		}
+		var features = []
+		for (var i = 0; i < xmlRoot.children.length; i++) {
+			features.push(p5WFS_ParseFeatureMember(xmlRoot.children[i]))
+		}
+		return features.filter(function (item) { return !!item; })
+	})
+}
+
+module.exports = {
+	p5WFS_ParseFeatureMember: p5WFS_ParseFeatureMember,
+	p5WFS_ParseFeatureFieldRecurse: p5WFS_ParseFeatureFieldRecurse,
+	p5WFS_GetFeature: p5WFS_GetFeature,
+	p5WFS_GetFeatureFromXml: p5WFS_GetFeatureFromXml,
+}