Skip to content

Commit

Permalink
Merge pull request #5 from andersonluisribeiro/master
Browse files Browse the repository at this point in the history
Fix import/export
  • Loading branch information
andersonluisribeiro committed Mar 21, 2019
2 parents 30c30ea + bffcea2 commit 25fbae5
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 293 deletions.
139 changes: 4 additions & 135 deletions src/docs/apiary.apib
Expand Up @@ -21,13 +21,15 @@ Returns all currently configured flows
],
"attrs": [
{
"id": 673,
"label": "temp",
"static_value": "",
"template_id": "296",
"type": "dynamic",
"value_type": "float"
},
{
"id": 674,
"label": "Name",
"static_value": "Device",
"template_id": "296",
Expand Down Expand Up @@ -123,145 +125,12 @@ Returns all currently configured flows
]
}

+ Response 200 (application/json; charset=utf-8)
+ Response 201 (application/json; charset=utf-8)

+ Body

{
"devices": [
{
"id": "b59044",
"label": "device"
}
],
"templates": [
{
"attrs": [
{
"created": "2018-11-27T11:40:50.755884+00:00",
"id": 47,
"label": "model-id",
"static_value": "model-001",
"template_id": "24",
"type": "static",
"value_type": "string"
},
{
"created": "2018-11-27T11:40:50.813644+00:00",
"id": 48,
"label": "temperature",
"template_id": "24",
"type": "dynamic",
"value_type": "float"
}
],
"config_attrs": [],
"created": "2018-11-27T11:40:50.754898+00:00",
"data_attrs": [
{
"created": "2018-11-27T11:40:50.755884+00:00",
"id": 47,
"label": "model-id",
"static_value": "model-001",
"template_id": "24",
"type": "static",
"value_type": "string"
},
{
"created": "2018-11-27T11:40:50.813644+00:00",
"id": 48,
"label": "temperature",
"template_id": "24",
"type": "dynamic",
"value_type": "float"
}
],
"id": 24,
"label": "Template"
}
],
"flows": [
{
"message": "ok",
"flow": {
"name": "Flow",
"enabled": true,
"id": "7339c7b7-bd30-4515-991c-e576e76bd184",
"flow": [
{
"id": "b032cba2.69981",
"type": "tab",
"name": "Sample flow"
},
{
"id": "f7ae7ff1.f3f3f",
"type": "device in",
"z": "b032cba2.69981",
"name": "device",
"device": "{\"id\":\"d4c8f5\"}",
"status": "false",
"_device_id": "d4c8f5",
"_device_label": "",
"_device_type": "",
"x": 102.5,
"y": 164,
"wires": [
[
"d4d0b51f.60b0b"
]
]
},
{
"id": "d4d0b51f.60b0b",
"type": "switch",
"z": "b032cba2.69981",
"name": "",
"property": "payload",
"propertyType": "msg",
"rules": [
{
"t": "eq",
"v": "",
"vt": "str"
}
],
"checkall": "true",
"outputs": 1,
"x": 308,
"y": 196,
"wires": [
"ad106680.4d93e8"
]
},
{
"id": "ad106680.4d93e8",
"type": "change",
"z": "b032cba2.69981",
"name": "",
"rules": [
{
"t": "set",
"p": "payload",
"pt": "msg",
"to": "",
"tot": "str"
}
],
"action": "",
"property": "",
"from": "",
"to": "",
"reg": false,
"x": 434,
"y": 263,
"wires": []
}
],
"created": 1543318850887,
"updated": 1543318850887
}
}
]
"message": "data imported!"
}

+ Response 400 (application/json; charset=utf-8)
Expand Down
2 changes: 1 addition & 1 deletion src/routers/import.js
Expand Up @@ -40,7 +40,7 @@ router.post('/import', [

return requestImport.post(rawToken, req.body)
.then((ret) => {
res.status(200).json(ret);
res.status(201).json(ret);
})
.catch((err) => {
const error = {
Expand Down
178 changes: 21 additions & 157 deletions src/services/requestsImport.js
@@ -1,181 +1,45 @@
import { logger } from '@dojot/dojot-module-logger';
import requestsDevice from './requestsDevice';
import requestsTemplate from './requestsTemplate';
import requestFlow from './requestsFlow';
import Requests from '../utils/requests';
import config from '../config';

async function deleteAllData(token) {
logger.debug('Deleting all devices.');
await Requests._delete(token, `${config.device_manager_url}/device`);
logger.debug('Deleting all templates.');
await Requests._delete(token, `${config.device_manager_url}/template`);
async function deleteAllFlows(token) {
logger.debug('Deleting all flows.');
await Requests._delete(token, `${config.flow_broker_url}/v1/flow`);
}

function improveDeviceToBeCreated(newsIdTemplate, devices) {
const deviceList = devices;
deviceList.forEach((device, indexDevice) => {
device.templates.forEach((templateId, index) => {
newsIdTemplate.forEach((item) => {
if (parseInt(item.oldId, 0) === parseInt(templateId, 0)) {
deviceList[indexDevice].templates[index] = item.newId;
}
});
});

device.attrs.forEach((attr) => {
const changeattr = attr;
newsIdTemplate.forEach((item) => {
if (parseInt(attr.template_id, 0) === parseInt(item.oldId, 0)) {
changeattr.template_id = item.newId.toString();
}

item.newObject.attrs.forEach((attrTemplate) => {
if (attrTemplate.label === changeattr.label) {
delete changeattr.created;
changeattr.id = attrTemplate.id;
}
});

if (attr.metadata !== undefined) {
attr.metadata.forEach((meta) => {
const data = meta;
if (data.id !== undefined) {
delete data.id;
}
});
}
});
});
});
return deviceList;
}

function changeIdDeviceFlow(newDevices, flows) {
const flowsList = flows;
flowsList.forEach((flow) => {
flow.flow.forEach((nodeIn) => {
const node = nodeIn;
if ((node.type === 'device in') || (node.type === 'actuate')) {
newDevices.forEach((device) => {
if (device.oldId === node._device_id) {
node._device_id = device.newId;
node.device_source_id = `Device (${device.newId})`;
}
});
} else if (node.type === 'device out') {
newDevices.forEach((device) => {
let newDevicesIds = [];
node.devices_source_configured.forEach( (deviceId) => {
if (device.oldId === deviceId) {
newDevicesIds.push(device.newId);
}
});
node.devices_source_configured = newDevicesIds;
});
}
});
});
return flowsList;
}

function removeMetadataIDTemplate(templates) {
const temp = templates;
temp.forEach((template) => {
template.attrs.forEach((attr) => {
const oneAttr = attr;
delete oneAttr.id;
if (oneAttr.metadata !== undefined) {
oneAttr.metadata.forEach((meta) => {
const data = meta;
if (data.id !== undefined) {
delete data.id;
}
});
}
});
});
return templates;
}

function changeIdTemplateFlow(newflows, flows) {
const flowsList = flows;
flowsList.forEach((flow) => {
flow.flow.forEach((objIn) => {
const obj = objIn;
if (obj.type === 'device template in') {
newflows.forEach((item) => {
if (item.oldId === obj.device_template_id) {
obj.device_template_id = item.newId;
obj.device_template.id = item.newId;
}
});
}
});
});
return flowsList;
}

/**
* @param {array} data data array to be imported on dojot, like the exported object.
* @returns {array} return the imported objects on dojot.
*/
const post = (token, data) => new Promise(async (resolve, reject) => {
logger.debug('Will import data.');
try {
await deleteAllData(token);
await deleteAllFlows(token);
} catch (error) {
reject(error.toString());
return;
}
const body = data;
body.templates = removeMetadataIDTemplate(body.templates);
requestsTemplate.post(token, body.templates)
.then((templates) => {
logger.debug('Templates imported.');
body.templates = templates;
body.devices = improveDeviceToBeCreated(templates, body.devices);
requestsDevice.post(token, body.devices)
.then((devices) => {
logger.debug('Devices imported.');
body.devices = devices;
body.flows = changeIdDeviceFlow(devices, body.flows);
body.flows = changeIdTemplateFlow(templates, body.flows);
requestFlow.post(token, body.flows)
.then((newflows) => {
logger.debug('Flows imported.');
const bodyTemplates = body.templates;
body.templates = [];
bodyTemplates.forEach((item) => {
body.templates.push(item.newObject);
});

const bodyDevices = body.devices;
body.devices = [];
bodyDevices.forEach((item) => {
body.devices.push(item.newObject[0]);
});

body.flows = newflows;
logger.debug('Resolving importation.');
resolve(body);
})
.catch((err) => {
logger.debug(`Received error on import flows, ${err}. Rejecting the request`);
reject(err);
});
})
.catch((err) => {
logger.debug(`Received error on import Devices, ${err}. Rejecting the request`);
reject(err);
});
})
.catch((err) => {
logger.debug(`Received error on import Templates, ${err}. Rejecting the request`);
reject(err);
});
const body = data;

requestFlow.post(token, body.flows).then((newflows) => {
logger.debug('Flows imported.');

Requests.post(token, `${config.device_manager_url}/import`, {templates: body.templates, devices: body.devices}).then(res => {
logger.debug('Devices and templates imported.');
resolve({'message': 'data imported!'});
})
.catch((err) => {
logger.debug(`Received error on import templates and devices, ${err}. Rejecting the request`);
reject(err);
});
})
.catch((err) => {
logger.debug(`Received error on import flows, ${err}. Rejecting the request`);
reject(err);
});

});

export default { post };
4 changes: 4 additions & 0 deletions src/tests/api.js
Expand Up @@ -28,6 +28,10 @@ app.post('/template', (req, res) => {
res.json({ template: postTemplate });
});

app.post('/import', (req, res) => {
res.json({message: "data imported!"});
});

app.delete('/template', (req, res) => {
res.sendStatus(200);
});
Expand Down

0 comments on commit 25fbae5

Please sign in to comment.