I'm trying to send an "entity" obtained from MySQL to RabbitMQ.
I'm able to make the connection to the database and return data. Example:
dbConnection.query("SELECT * FROM customer WHERE Id = ?", customerId, (err, rows, fields) => {
...
res.status(200).json(rows)
...
}
After this I am able to watch in Postman the "JSON result", so, I want to send this "JSON result" as an string to RabbitMQ.
I can send to RabbitMq a fake data object with no problem:
const fakeData = {
name: "Elon Musk",
company: "SpaceX",
};
channel.sendToQueue("message-queue", Buffer.from(JSON.stringify(fakeData)));
So, how must I convert the "rows" object returned from MySQL to send it to the queue?
Thank you in advance!
The solution to my problem is as follows:
rows.forEach(function (row) {
channel.sendToQueue("message-queue", Buffer.from(JSON.stringify(row)));
});
Related
Trying to setup an Express API server to grab some data for a portfolio site. I have set up the MySQL table with an JSON data type for my 'images' column. 'images' is supposed to have multiple image links for a gallery. However, the server outputs the images array as a string instead of an array of strings.
Javascript Code on the API Server
app.get("/getWorks", (req, res) => {
let sql = "select * from works";
db.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
res.send(result);
});
});
The Results
[
{
"workID": 1,
"title": "example",
"images": "[\"https://SERVER_IP/images/example.png\", \"https://SERVER_IP/images/example.png\"]"
}
]
Workaround
I found out a work around to get the desired output adding this:
result = result.map((row) => ((row.images = JSON.parse(row.images)), row));
[
{
"workID": 1,
"title": "example",
"images": ["https://SERVER_IP/images/example.png", "https://SERVER_IP/images/example.png"]
}
]
How come the query is not outputting the data in a JSON array in the first place even though I specified that particular column to be JSON data type in the table?
I figured it out the problem. I was using the wrong MySQL node package. Need MySQL2 for the json formatting.
npm install mysql2
const mysql = require("mysql2");
i'm learning loopback 4, i have created model, repository and datasource, it also connected
to mysql and i can retrieve results from http://127.0.0.1:3000/myapi/{id}
in my default example getting by id is :
#get('/citySchedule/{id}', {
responses: {
'200': {
description: 'Schedule model instance',
content: {'application/json': {schema: {'x-ts-type': Schedule}}},
},
},
})
async findById(#param.path.number('id') id: number): Promise<Schedule> {
return await this.ScheduleRepository.findById(id);
}
However, i didnt found any tutorial for getting data with more parameters.
let say mysql table of schedule has contain column id, city_name, city_code, date, task, item.
for example, i want to get "SELECT task, item FROM schedule WHERE city_code=123 AND date=2019-05-01"
my question, how to write code to get those data at loopback controller ?
any example code...
my expectations, i can query from my api :
http://127.0.0.1:3000/myapi/{city_code}/{date}/ to get data results or
http://127.0.0.1:3000/myapi/{city_name}/{date}/
If you have generated your controller using loopback cli, you must have got another method in controller class like this
#get('/citySchedule', {
responses: {
'200': {
description: 'Array of Schedule model instances',
content: {
'application/json': {
schema: {type: 'array', items: {'x-ts-type': Schedule}},
},
},
},
},
})
async find(
#param.query.object('filter', getFilterSchemaFor(Schedule)) filter?: Filter,
): Promise<Schedule[]> {
return await this.ScheduleRepository.find(filter);
}
You can use this API to fetch more filtered data.
Considering your example
SELECT task, item FROM schedule WHERE city_code=123 AND
date=2019-05-01
for this query, you need to hit the API like this.
GET /citySchedule?filter=%7B%22where%22%3A%7B%22city_code%22%3A123%2C%22date%22%3A%222019-05-01%22%7D%2C%22fields%22%3A%7B%22task%22%3Atrue%2C%22item%22%3Atrue%7D%7D
Here, the filter query parameter value is actually url encoded string for the below json string
{
"where":{
"city_code":123,
"date":"2019-05-01"
},
"fields":{
"task":true,
"item":true
}
}
I have a simple NodeJS app which is running a http server that is collecting data from a MongoDB instance and presenting the result as JSON:
db.collection(collectionName).findOne({ '_id': id }, function (err, result) {
if (err) {
reportError(err, res);
return;
} else {
outPut(result, res);
}
});
In the outPut function I'm calling JSON.stringify() on the 'result' variable and writing it in the response.
However much of the data is missing, and an empty $db object is included from somewhere. Here is a subset of the data:
"Kommun":1292,
"Lansdel":28,
"Delyta":[
{
"$id":"2",
"$db":""
},
{
"$ref":"691"
},
{
"$ref":"247"
}
Looking at the record using Studio 3T it seems that all the data I expect has been saved.
Why am I not getting all my data in the JSON object? Where is the $db coming from? What is it?
My guess is that you are using DBRefs. In order to include the referenced data from different collections, you must query those yourself. I cannot show you a code example without some more info on the data schema.
At the moment I have a list of employees as a json file.
{
"id": 1,
"departments": "1",
"name": "Bill Smith",
"profilePic": "/img/people/Office/bill-smith.jpg",
"title": "Office Manager"
},
I now want to store these in the database but still return them as JSON.
How do I set this up with my routes? It will be a very basic filter, by department id.
I presume I would do a get request
Route::get('people/{department}', function () {
});
How do I return the json?
If you have an Employee model, it would look like this:
Route::get('people/{department}', function ($departmentId) {
return Employee::where('department_id', $departmentId)->get();
});
Laravel converts objects to JSON before writing them to the client.
As you said you have list of employees in a json file then First create a DB Seed to store your data in the DATABASE from that particular json file with the help of Seeding.
Lets say you made a table departments in the database and stored your data in all 5 columns(id, departments, name, profilePic, title), Then make a model that with the following command
php artisan make:model Department
For more details about models please visits on https://laravel.com/docs/5.4/eloquent#eloquent-model-conventions
Then simple detect that request through route and return the data as json:
Route::get('people/{department}', function ($departmentId) {
$data = Department::where('departments', $departmentId)->first();
return response()->json($data);
});
The very basic model query would be
Route::get('people/{department}', function ($department) {
return Employee::where('departments',$department)->get();
}
assume Employee is your model
.
Then Laravel automatically will convert your query to json.
FYI: You can also send this request to controller method the return like above
My JSON file is:
[
{'name': name,
'birthday': birthday,
'telephone': telephone,
'details': details},
....
]
My application will be able to accept name, birthday and telephone values, and these three values combined are going to be unique for each entity. I am hoping to retrieve an entity based on these three values, say http://localhost:8000/name?=mary&birthday?=19880902&telephone?=2234324567 will return the json object of Mary.
I am looking at the examples available on using mongodb and nodejs, most of them suggest creating a completely new _id field using new BSON.ObjectID(id) and do something similar to app.get('/users/:id', users.findById) to find the id. Is it possible not to create a separate id field?
Try using a callback with the (req, res) parameters. See here:
app.get('/', function(req, res) {
var findCursor = Users.find({
"name": req.query.name,
"birthday": req.query.birthday,
"telephone": req.query.telephone
});
cursor.each(function(err, doc) {
if (err) console.log("Oh no!");
if (doc != null) {
// Do stuff
res.send('GET request to user page?');
}
}
});