|
| 1 | + |
| 2 | + |
| 3 | +const BASE_PATH = process.env.CONTEXT_BROKER || 'http://localhost:1026/ngsi-ld/v1'; |
| 4 | +const JSON_LD_HEADER = 'application/ld+json'; |
| 5 | +const Context = process.env.IOTA_JSON_LD_CONTEXT || 'http://context/ngsi-context.jsonld'; |
| 6 | +const LinkHeader = '<' + Context + '>; rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json">'; |
| 7 | + |
| 8 | + |
| 9 | +async function parse(response) { |
| 10 | + let text = ''; |
| 11 | + try { |
| 12 | + text = await response.text(); |
| 13 | + const data = JSON.parse(text); |
| 14 | + return data; |
| 15 | + } catch (err) { |
| 16 | + return text; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +function setHeaders(accessToken, link, contentType) { |
| 21 | + const headers = {}; |
| 22 | + if (accessToken) { |
| 23 | + // If the system has been secured and we have logged in, |
| 24 | + // add the access token to the request to the PEP Proxy |
| 25 | + headers['X-Auth-Token'] = accessToken; |
| 26 | + } |
| 27 | + if (link) { |
| 28 | + headers.Link = link; |
| 29 | + } |
| 30 | + if (contentType) { |
| 31 | + headers['Content-Type'] = contentType || JSON_LD_HEADER; |
| 32 | + } |
| 33 | + return headers; |
| 34 | +} |
| 35 | + |
| 36 | +// This is a promise to make an HTTP GET request to the |
| 37 | +// /ngsi-ld/v1/entities/ end point |
| 38 | +function listEntities(opts, headers = {}) { |
| 39 | + |
| 40 | + console.log(`${BASE_PATH}/entities/?${new URLSearchParams(opts)}`) |
| 41 | + return fetch(`${BASE_PATH}/entities/?${new URLSearchParams(opts)}`, { |
| 42 | + method: 'GET', |
| 43 | + headers |
| 44 | + }) |
| 45 | + .then((r) => parse(r).then((data) => ({ status: r.status, body: data }))) |
| 46 | + .then((data) => { |
| 47 | + if (data.status !== 200) { |
| 48 | + throw new Error(data.body); |
| 49 | + } |
| 50 | + return data.body; |
| 51 | + }); |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +exports.findNeighbour = async function (lat, lng, type){ |
| 56 | + const headers = setHeaders(null, LinkHeader); |
| 57 | + const entities = await listEntities( |
| 58 | + { |
| 59 | + type, |
| 60 | + pick: 'id', |
| 61 | + limit: 2, |
| 62 | + geometry: "Point", |
| 63 | + coordinates: `[${lat},${lng}]`, |
| 64 | + georel: "near;maxDistance==8000" |
| 65 | + }, |
| 66 | + headers |
| 67 | + ); |
| 68 | + |
| 69 | + return entities[1].id; |
| 70 | +} |
| 71 | + |
| 72 | +exports.findTargetInField = async function (type, locatedAt){ |
| 73 | + const headers = setHeaders(null, LinkHeader); |
| 74 | + const entities = await listEntities( |
| 75 | + { |
| 76 | + type, |
| 77 | + pick: 'id,location', |
| 78 | + limit: 6 |
| 79 | + }, |
| 80 | + headers |
| 81 | + ); |
| 82 | + |
| 83 | + console.log(entities); |
| 84 | +} |
| 85 | + |
| 86 | + |
0 commit comments