|
| 1 | +const fs = require('fs'); |
| 2 | +const csv = require('fast-csv'); |
| 3 | +const BatchUpdate = require('../lib/batchUpdate'); |
| 4 | +const debug = require('debug')('tutorial:csv'); |
| 5 | +const _ = require('lodash'); |
| 6 | +const Status = require('http-status-codes'); |
| 7 | +const path = require('path'); |
| 8 | +const moment = require('moment-timezone'); |
| 9 | + |
| 10 | +/* |
| 11 | + * Delete the temporary file |
| 12 | + */ |
| 13 | +function removeCsvFile(path) { |
| 14 | + fs.unlink(path, (err) => { |
| 15 | + if (err) { |
| 16 | + throw err; |
| 17 | + } |
| 18 | + }); |
| 19 | +} |
| 20 | + |
| 21 | +/* |
| 22 | + * Read the CSV data from the temporary file. |
| 23 | + * This returns an in memory representation of the raw CSV file |
| 24 | + */ |
| 25 | +function readCsvFile(path) { |
| 26 | + return new Promise((resolve, reject) => { |
| 27 | + const rows = []; |
| 28 | + |
| 29 | + fs.createReadStream(path) |
| 30 | + .pipe(csv.parse({ headers: true })) |
| 31 | + .on('error', (error) => { |
| 32 | + reject(error.message); |
| 33 | + }) |
| 34 | + .on('data', (row) => { |
| 35 | + rows.push(row); |
| 36 | + }) |
| 37 | + .on('end', () => { |
| 38 | + resolve(rows); |
| 39 | + }); |
| 40 | + }); |
| 41 | +} |
| 42 | + |
| 43 | +/* |
| 44 | + * Strip the id and an key from the header row. |
| 45 | + */ |
| 46 | +function parseId(input) { |
| 47 | + const regexId = /^[^\s]+/; |
| 48 | + const regexKey = /[\w]+$/; |
| 49 | + const id = regexId.exec(input)[0]; |
| 50 | + const key = regexKey.exec(input)[0]; |
| 51 | + |
| 52 | + return { id, key }; |
| 53 | +} |
| 54 | + |
| 55 | +function createEntitiesFromRows(rows) { |
| 56 | + const allEntities = []; |
| 57 | + const timestamp = new Date().toISOString(); |
| 58 | + |
| 59 | + rows.forEach((row) => { |
| 60 | + const timestamp = moment.tz(row.annee, 'Etc/UTC').toISOString(); |
| 61 | + const entity = { |
| 62 | + id: row.id, |
| 63 | + type: row.type |
| 64 | + }; |
| 65 | + |
| 66 | + Object.keys(row).forEach((key, index) => { |
| 67 | + const value = row[key]; |
| 68 | + if (value !== '') { |
| 69 | + switch (key) { |
| 70 | + case 'birthdate': |
| 71 | + case 'comment': |
| 72 | + case 'fedWith': |
| 73 | + case 'giveName': |
| 74 | + case 'legalId': |
| 75 | + case 'name': |
| 76 | + case 'species': |
| 77 | + entity[key] = { value: value, type: 'Property' }; |
| 78 | + break; |
| 79 | + |
| 80 | + case 'temperature': |
| 81 | + entity[key] = { |
| 82 | + value: Number(value), |
| 83 | + type: 'Property', |
| 84 | + unitCode: 'CEL', |
| 85 | + observedAt: timestamp |
| 86 | + }; |
| 87 | + break; |
| 88 | + case 'heartRate': |
| 89 | + entity[key] = { value: Number(value), type: 'Property', unitCode: '5K', observedAt: timestamp }; |
| 90 | + break; |
| 91 | + case 'weight': |
| 92 | + entity[key] = { |
| 93 | + value: Number(value), |
| 94 | + type: 'Property', |
| 95 | + unitCode: 'KGM', |
| 96 | + observedAt: timestamp |
| 97 | + }; |
| 98 | + break; |
| 99 | + |
| 100 | + case 'jobTitle_name': |
| 101 | + entity.jobTitle = { |
| 102 | + type: 'Property', |
| 103 | + value: { |
| 104 | + name: row.jobTitle_name, |
| 105 | + inDefinedTermSet: row.jobTitle_inDefinedTermSet, |
| 106 | + termCode: row.jobTitle_termCode, |
| 107 | + url: row.jobTitle_url |
| 108 | + } |
| 109 | + }; |
| 110 | + break; |
| 111 | + case 'streetAddress': |
| 112 | + entity.address = { |
| 113 | + type: 'Property', |
| 114 | + value: { |
| 115 | + addressLocality: row.addressLocality, |
| 116 | + addressRegion: row.addressRegion, |
| 117 | + postalCode: row.postalCode, |
| 118 | + streetAddress: row.streetAddress |
| 119 | + } |
| 120 | + }; |
| 121 | + break; |
| 122 | + case 'location_type': |
| 123 | + entity.location = { |
| 124 | + type: 'GeoProperty', |
| 125 | + observedAt: timestamp, |
| 126 | + value: { |
| 127 | + type: row.location_type, |
| 128 | + coordinates: [Number(row.lng), Number(row.lat)] |
| 129 | + } |
| 130 | + }; |
| 131 | + break; |
| 132 | + |
| 133 | + case 'category': |
| 134 | + case 'cropStatus': |
| 135 | + case 'gender': |
| 136 | + case 'healthCondition': |
| 137 | + case 'phenologicalCondition': |
| 138 | + case 'reproductiveCondition': |
| 139 | + case 'sex': |
| 140 | + entity[key] = { vocab: value, type: 'VocabProperty' }; |
| 141 | + break; |
| 142 | + case 'calvedBy': |
| 143 | + case 'cropType': |
| 144 | + case 'owns': |
| 145 | + case 'owner': |
| 146 | + case 'ownedBy': |
| 147 | + case 'siredBy': |
| 148 | + entity[key] = { object: value, type: 'Relationship' }; |
| 149 | + break; |
| 150 | + case 'locatedAt': |
| 151 | + case 'observation': |
| 152 | + case 'prediction': |
| 153 | + entity[key] = { object: value, type: 'Relationship', observedAt: timestamp }; |
| 154 | + break; |
| 155 | + case 'id': |
| 156 | + case 'type': |
| 157 | + break; |
| 158 | + default: |
| 159 | + debug('unknown : ' + key); |
| 160 | + break; |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + }); |
| 165 | + |
| 166 | + allEntities.push(entity); |
| 167 | + }); |
| 168 | + return allEntities; |
| 169 | +} |
| 170 | + |
| 171 | +/* |
| 172 | + * Create an array of promises to send data to the context broker. |
| 173 | + * Each insert represents a series of readings at a given timestamp |
| 174 | + */ |
| 175 | +function createContextRequests(entities) { |
| 176 | + const promises = []; |
| 177 | + entities.forEach((entitiesAtTimeStamp) => { |
| 178 | + promises.push(BatchUpdate.sendAsHTTP(entitiesAtTimeStamp)); |
| 179 | + }); |
| 180 | + return promises; |
| 181 | +} |
| 182 | + |
| 183 | +/** |
| 184 | + * Actions when uploading a CSV file. The CSV file holds an array of |
| 185 | + * measurements each at a given timestamp. |
| 186 | + */ |
| 187 | +const upload = (req, res) => { |
| 188 | + if (req.file === undefined) { |
| 189 | + return res.status(Status.UNSUPPORTED_MEDIA_TYPE).send('Please upload a CSV file!'); |
| 190 | + } |
| 191 | + |
| 192 | + const file = path.join(__dirname, '../resources/', req.file.filename); |
| 193 | + |
| 194 | + return readCsvFile(file) |
| 195 | + .then((rows) => { |
| 196 | + removeCsvFile(file); |
| 197 | + //console.log(rows[0]) |
| 198 | + return createEntitiesFromRows(rows); |
| 199 | + }) |
| 200 | + .then((entities) => { |
| 201 | + //console.log(JSON.stringify(entities[0], null, 2)) |
| 202 | + |
| 203 | + batchEntities = []; |
| 204 | + const chunkSize = 10; |
| 205 | + |
| 206 | + for (let i = 0; i < entities.length; i += chunkSize) { |
| 207 | + const chunk = entities.slice(i, i + chunkSize); |
| 208 | + batchEntities.push(chunk); |
| 209 | + } |
| 210 | + |
| 211 | + return createContextRequests(batchEntities); |
| 212 | + }) |
| 213 | + .then(async (promises) => { |
| 214 | + const results = []; |
| 215 | + for (const promise of promises) { |
| 216 | + const result = await promise; |
| 217 | + results.push(result); |
| 218 | + } |
| 219 | + return results; |
| 220 | + }) |
| 221 | + .then((results) => { |
| 222 | + const errors = _.filter(results, function (o) { |
| 223 | + return o.status === 'rejected'; |
| 224 | + }); |
| 225 | + return errors.length ? res.status(Status.BAD_REQUEST).json(errors) : res.status(Status.NO_CONTENT).send(); |
| 226 | + }) |
| 227 | + .catch((err) => { |
| 228 | + debug(err.message); |
| 229 | + return res.status(Status.INTERNAL_SERVER_ERROR).send(err.message); |
| 230 | + }); |
| 231 | +}; |
| 232 | + |
| 233 | +module.exports = { |
| 234 | + upload |
| 235 | +}; |
0 commit comments