I need to convert some JSON to XML with this library, I need to do that in order to send some data to the Database in a post request I am working on.
This is what req.body returns
{ DealerName: 'amrcl',
CardId: '123',
Nickname: 'mkm123',
Picture: 'http://lorempixel.com/150/150/',
Active: '1',
LegalId: '1',
TypeId: '1'
}
is dynamic data. Let me show you the code
export default function (req, res) {
try {
const connection = new sql.Connection(spConfig, function spConnection (errSpConnection) {
const request = connection.request();
if (errSpConnection) {
res.status(401);
}
request.input('Dealer_Param', sql.VarChar(1000), req.body);
request.input('param_IS_DEBUG', sql.Bit, null);
request.output('output_IS_SUCCESSFUL', sql.Bit);
request.output('output_STATUS', sql.VarChar(500));
request.execute('[mydbo].[StoredProcedure]', function spExecution (errSpExecution, dataset) {
connection.close();
if (errSpExecution) {
res.status(401);
} else {
if (request.parameters.output_IS_SUCCESSFUL.value) {
res.status(200).json({
success : 'New dealer successfully inserted.',
});
}
}
});
});
}
}
that is for Stored Procedure method which is with the mssql module.
As you see the code above, there is a failure error, because in request.input('Dealer_Param', sql.VarChar(1000), req.body); I am sending the JSON I paste at the beginning of the question. But if instead of req.body I put this XML with Dummy data '<Dealers><Detail DealerName = "TESTING123" CardId = "1222" NickName = "tester123" Active = "1" LegalId = "16545" TypeId = "1"></Detail></Dealers>' then everything works fine because the DB need to receive an XML.
So, what are your recommendations, what should I do to put the JSON data as a XML ?
I would just load the json2xml library...
install $ npm install json2xml
import the module in your code: var json2xml = require("json2xml");
and then convert the json to xml like so:
var key,
attrs=[];
for (key in req.body) {
if (req.body.hasOwnProperty(key)) {
var obj = {};
obj.key = req.body.key;
attrs.push(obj);
}
}
var dealerXml = json2xml({dealer:req.body, attr:attrs}, { attributes_key:'attr'});
request.input('Dealer_Param', sql.VarChar(1000), dealerXml);
Related
The user has a form. He submits a file for his profile picture. The instance of Blob is being received by the server and its role is to upload in a document with MongoDB.
If I'm not mistaken, it is something like this:
import { serialize } from "bson";
// ...
// with `db` my database
// and `picture` the Blob.
await db
.collection("users")
.updateOne({ email: user.email }, { $set: { picture: serialize(picture) } });
So far, storing data seems to be working fine. The problem occurs when I want to retrieve the data in order to display it on the client side.
I fetch the data and get this in my "users" collection :
{
email: "randomuser#foobar.com",
picture : BinData(0, 'LgAAAAJuYW1lAAkAAABsb2dvLnBuZwABbGFzdE1vZGlmaWVkAADQM5z8XHhCAA==')
}
I'm not sure to understand what any of this means. All I want is to be able to transfer the data to the client side and then reconstruct the image in order to display it.
Note that the data is fetched server-side, using SvelteKit load function :
export const load: PageServerLoad = async ({cookies}) => {
const { user } = await getUser(cookies);
console.log("user.picture =", user.picture);
return {
user: {
picture: user.picture, // throws an error here because `picture` is non-serialisable
email: user.email
},
}
}
In the console it looks like this :
user.picture = new Binary(Buffer.from("2e000000026e616d6500090000006c6f676f2e706e6700016c6173744d6f6469666965640000d0339cfc5c784200", "hex"), 0)
What I tried
I tried to send the JSON of the buffer :
export const load: PageServerLoad = async ({cookies}) =>{
const { user } = await getUser(cookies);
console.log("user.picture =", user.picture);
console.log("user.picture =", user.picture!.buffer);
return {
user: {
picture: user.picture!.buffer.toJSON(),
email: user.email
},
}
}
And then, on the client side :
onMount(() => {
if (user.picture != undefined) {
const arr = new Uint8Array(user.picture.data);
console.log("on the client side : ", user.picture);
console.log("in Uint8Array : ", arr);
pictureURL = URL.createObjectURL(new Blob([arr], { type: "image/png" }));
console.log("pictureURL = ", pictureURL);
}
});
In the console, it gives something like this :
pictureURL = blob:http://localhost:5173/0ed581fc-87be-46ab-ade7-f44d78b98646
Therefore, I give that to the img element :
<img src={pictureURL} alt="Profile picture" />
But the image is not displayed, only the alt description.
To sum up
I have the binary data of an image in a document of my database. How do I display the corresponding image with the fetched data?
I'm trying to build a fake api with json-server and facing an issue. I don't know if I'm missing something or if I just hit a bug.
Basically, if I send a url parameter when requesting data received as a single object, I can then read my parameter just fine when I'm trying to render that data.
But if the data that I receive is an array, then I get undefined trying to read that parameter.
These are my files (don't mind the logic behind this, I simplified things to reduce unnecessary information).
server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router(require('./db.js')())
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
router.render = (req, res) => {
console.log("User try query: " + req.query.user)
console.log("User try param: " + req.params['user'])
if (req.url.startsWith('/slack_users_info')) {
res.jsonp({
user: res.locals.data
})
} else if (req.url.startsWith('/slack_users_info2')) {
res.jsonp({
user: res.locals.data
})
} else {
res.jsonp(res.locals.data)
}
}
server.use(router)
// Run server on indicated port.
server.listen(port = 3000, () => {
console.log('JSON Server is running')
console.log('http://localhost:' + port)
})
db.js
var faker = require('faker');
module.exports = function () {
var data = {
slack_users_info: slack_users_info(),
slack_users_info2: slack_users_info2()
}
return data;
}
function slack_users_info() {
subdata = []
for (var i = 0; i < 10; i++) {
subdata.push({
id: "user_id_" + i,
})
}
return subdata;
}
function slack_users_info2() {
subdata = {
id: "user_id"
}
return subdata;
}
I'm running with npm start.
If I request the array, I get undefined:
GET http://localhost:3000/slack_users_info?user=user_id_0
Then I get:
User try query: undefined
User try param: undefined
If I request the single object I get the expected parameter:
GET http://localhost:3000/slack_users_info2?user=user_id_0
Then I get:
User try query: user_id_0
User try param: undefined
In both cases the response body is received correctly, I just can't read the parameter in the first case.
Is there a reason for this?
Looking at https://www.npmjs.com/package/json-server#generate-random-data it seems like you need to return an object, but can include your array inside that object.
For example, try:
function slack_users_info() {
const data = {
users: []
}
for (var i = 0; i < 10; i++) {
data.users.push({
id: "user_id_" + i,
})
}
return data;
}
I have a small JSON file
{
"users": [
{
"id": 1111,
"name": "Foo",
"gold": 2
},{
"id": 2222,
"name": "Bar",
"gold": 7
}
]
}
and want to manipulate the data of one specific object, selected by its id.
I want to
read the data from the file
manipulate the data
write the new data back to the file
send a response to the client
so I went for this route, called by using Ajax
app.get('/incG/:id', function (req, res) {
fs.readFile('./database.json', 'utf8', function (err, data) {
var json = JSON.parse(data); // Read the data
var users = json.users; // Get all users
var user = users.find(u => u.id === Number(req.params.id)); // get the user by id
user.gold++; // increase his value
fs.writeFile('./database.json', , (err) => { // the second parameter is missing!
res.send(user.gold); // send a response to the client
});
});
});
As you can see, when using fs.writeFile(database, , (err) => { the second parameter is missing.
What do I have to pass in there? I just want to update one specific user object (one specific value).
EDIT
When passing in JSON.stringify(user) as a parameter I delete all the data in the file and just write down the new object. So this might not work this way.
Try this,
fs.readFile('./database.json', 'utf8', function (err, data) {
var json = JSON.parse(data); // Read the data
var users = json.users; // Get all users
var userGold;
users.find(u => {
if (u.id === Number(req.params.id)) {
userGold = u.gold++;
}
});
users = JSON.stringify(users);
fs.writeFile('./database.json', users, (err) => {
res.send(userGold);
});
});
fs.writeFile(file, data[, options], callback)
Pass stringified JSON as second argument.
app.get('/incG/:id', function(req, res) {
fs.readFile('./database.json', 'utf8', function(err, data) {
var json = JSON.parse(data); // Read the data
var users = json.users; // Get all users
var user = users.find(u => u.id === Number(req.params.id)); // get the user by id
user.gold++; // increase his value
var dataToWrite = JSON.stringify(user);
fs.writeFile('./database.json', dataToWrite, (err) => { // the second parameter is missing!
res.send(user.gold); // send a response to the client
});
});
});
I'm trying to retrieve a profile picture from the Microsoft Azure API. The code below shows how.
private getProfilePicture(bearerToken: string, tenantId: string): void {
let command = CommandHelper.createRestBlobCommand([
{ name: 'https://graph.microsoft.com/beta'},
{ name: 'me/photo/$value' }
]);
command.Headers.push({ name: 'Authorization', value: 'bearer ' + bearerToken });
// load the photo from graph api.
this._gateway.send(command).subscribe(result => {
let info = result.payload;
var Base64 = require('js-base64').Base64;
var temp = 'data:image/bmp;base64,' + Base64.encode('info');
console.log(temp);
let action = actions.AuthenticationActions.photoLoaded(info);
this._store.dispatch(action);
});
}
The problem however is, that when I look at the output it returns :
data:image/bmp;base64,W29iamVjdCBCbG9iXQ==
Which translates to [object Blob].
My question is how to get the image object here?
with PHP is much simple in nodejs you have to put this to the function who return req as param and do it like this :
app.get('/...', function(req, res){ ...
var base64Data = req.rawBody.replace(/^data:image\/bmp;base64,/, "");
require("fs").writeFile("out.bmp", base64Data, 'base64', function(err) {
console.log(err);
});
I'm currently working with Node.js using the watson-developer-cloud Node.js SDK and I'm having problems when sending a query that includes an entity.
This is my code:
// require watson's node sdk and fs
var watson = require('watson-developer-cloud');
var fs = require('fs');
// Define output file
var outputJSONFile = '/home/vagrant/Desktop/node/dir/data.json';
// Create alchemy_data_news object using our api_key
var alchemy_data_news = watson.alchemy_data_news({
api_key: ''
});
// Define params for the query and what values to return
// Accepted returne values:
// docs.alchemyapi.com/v1.0/docs/full-list-of-supported-news-api-fields
var params = {
start: 'now-1m',
end: 'now',
count: 2,
qs: ['q.enriched.url.enrichedTitle.entities.entity.text=apple'],
return: ['enriched.url.url,enriched.url.title']
};
// Call getNews method and return json
alchemy_data_news.getNews(params, function (err, news) {
if (err) {
console.log('error:', err);
} else {
fs.writeFile(outputJSONFile, JSON.stringify(news, null, 2), function(err) {
if (err) {
console.log('WriteFile Error:', err);
} else {
console.log("JSON saved to " + outputJSONFile);
}
});
}
});
I'm still trying to figure out how to send the entities parameters using the params object.
While digging up through some code I came across qs so I have been using that to test but I haven't had success at all.
Any suggestions are greatly appreciated.
P.S: I'm trying to pass:
q.enriched.url.enrichedTitle.entities.entity.text=apple
q.enriched.url.enrichedTitle.entities.entity.type=company
If you look at the node-sdk source code for AlchemyDataNews, you will see that the top level parameters are being sent as query strings.
Then params map should be:
var params = {
start: 'now-1m',
end: 'now',
count: 2,
return: ['enriched.url.url,enriched.url.title'],
// fields here
'q.enriched.url.enrichedTitle.entities.entity.text': 'apple',
'q.enriched.url.enrichedTitle.entities.entity.type': 'company'
};