I need to prepare JSON by fetching the data from MYSQL. I have data in MYSQl in tree structure. I am trying to make recursive function to prepare JSON to meet the requirement but getting errors, I have following two files
main.js
/* jshint node: true */
"use strict";
var db = require('./helpers/db');
var list_worker = require('./workers/list');
var Q = require("q");
module.exports = function (app) {
/**
* return the profiles list
*/
app.get('/api/lists/get_list_tree_by_user/:user_id', function (req, res) {
list_worker.fetch_list_tree(req.params.user_id, 0).done(function (out) {
console.log(out);
res.send(out);
});
});
};
list.js
/* jshint node: true */
"use strict";
var db = require('../helpers/db');
var Q = require("q");
var output = {
data: []
};
var fetch_list_tree = function (user_id, list_id) {
// prepare query to fetch lists assosiated with a user.
var query = "SELECT b.`id`, b.`name` FROM `lists_users` a JOIN `lists` b ON(a.`list_id` = b.`id`) WHERE a.`user_id` = " + user_id + " AND a.`user_role` = 'owner' AND b.`parent_id` = " + list_id + " AND b.`deleted` = 'N';";
return db.query(query).then(function (result) {
if (result.length > 0) {
var lists = result.map(function (list, index) {
output.data[index] = {
label: list.name,
data: {
id: list.id
}
};
return fetch_list_tree(user_id, list.id).then(function (leaf_childs) {
output.data[index].children = [];
output.data[index].children.push(leaf_childs);
return leaf_childs;
});
});
return Q.all(lists).then(function (data) {
return output;
}, function (err) {
throw err;
});
} else {
return [];
}
}, function (err) {
throw err;
});
};
module.exports = {
fetch_list_tree: fetch_list_tree
};
data in database I am having is item 1 item 1.1 item 1.1.1 item 2
Output I want
{
"label": "item 1",
"data": {
"id": "1"
},
"children": [{
"label": "item 1.1",
"data": {
"id": "2"
},
"children": [{
"label": "item 1.1.1",
"data": {
"id": "3"
},
"children": []
}]
}]
}
I am getting the following error
TypeError: Converting circular structure to JSON