I am using MySQL X DevAPI
for relational tables in MySQL.
// Working with Relational Tables
var mysqlx = require('@mysql/xdevapi');
var myTable;
// Connect to server using a connection URL
mysqlx
.getSession({
user: 'user',
password: 'password',
host: 'localhost',
port: 33060
})
.then(function (session) {
// Accessing an existing table
myTable = session.getSchema('test').getTable('my_table');
// Insert SQL Table data
return myTable
.insert(['name', 'birthday', 'age'])
.values(['Laurie', '2000-5-27', 19])
.execute()
})
.then(function () {
// Find a row in the SQL Table
let columns = ['name', 'birthday']
return myTable
.select(columns)
.where('name like :name && age < :age)')
.bind('name', 'L%')
.bind('age', 30)
.execute();
})
.then(function (myResult) {
let rows = myResult.fetchAll() // this is array of array
let columns = ['name', 'birthday']
rows = rows.map((row) => columns.reduce((a, column, index) => Object.assign(a, { [column]: row[index] }), {}))
console.log(rows); // this is array of JSON object which is usefull for WEB API reposnse.
});
In this code I have to convert array of arrays into array of json object all the time
function (myResult) {
let rows = myResult.fetchAll() // this is array of array
let columns = ['name', 'birthday']
rows = rows.map((row) => columns.reduce((a, column, index) => Object.assign(a, { [column]: row[index] }), {}))
console.log(rows); // this is array of JSON object which is usefull for WEB API reposnse.
}
X Dev API is good library so there would be some good way to get results in JSON format directly.
What are the ways to get rows in JSON format in MySQL X DevAPI
?