SOAP request without server-side - javascript

I'm making a website that checks the European VAT numbers, using the SOAP request on the official website of European Commission
I just created a script on VSCode that works perfectly inside the Terminal with Node.js
Using the "soap" node package.
The moment i try it in the browser it obviously doesn't work.
I tryed using other packages like "node-soap" and "jquery.soap" (i saw somewhere that this package should work, but i think it was years ago) with no success.
Is there a way to be able to make it work without the need for a server-side?
const soap = require('soap');
const url = 'https://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl';
const args = [
{
countryCode: 'SE',
vatNumber: '556243997501'
},
{
countryCode: 'IE',
vatNumber: '6388047V'
}
]
;
let results = [];
let index = 0;
args.forEach((arg) => {
soap.createClient(url, (err, client) => {
if (err) throw err;
client.checkVat(arg, (err, result) => {
if (err) throw err;
let obj = {
countryCode: arg.countryCode,
vatNumber: arg.vatNumber,
requestDate: result.requestDate,
valid: result.valid,
name: result.name,
address: result.address
}
results.push(obj);
console.log(results);
});
});
index++;
});

You use wrong URL, so if you switch it will works.
From
'https://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl'
To
'https://ec.europa.eu/taxation_customs/vies/services/checkVatService.wsdl'
Test Result
$ node get-vat.js
[
{
countryCode: 'IE',
vatNumber: '6388047V',
requestDate: Invalid Date,
valid: true,
name: 'GOOGLE IRELAND LIMITED',
address: '3RD FLOOR, GORDON HOUSE, BARROW STREET, DUBLIN 4'
}
]
[
{
countryCode: 'IE',
vatNumber: '6388047V',
requestDate: Invalid Date,
valid: true,
name: 'GOOGLE IRELAND LIMITED',
address: '3RD FLOOR, GORDON HOUSE, BARROW STREET, DUBLIN 4'
},
{
countryCode: 'SE',
vatNumber: '556243997501',
requestDate: Invalid Date,
valid: true,
name: 'IKEA Components AB',
address: 'BOX 600,SÖDRA RINGVÄGEN 4 \n343 24 ÄLMHULT'
}
]
Update
Demo code
#1 save as get-vat.js
const soap = require('soap');
const url = 'https://ec.europa.eu/taxation_customs/vies/services/checkVatService.wsdl';
const args = [
{
countryCode: 'SE',
vatNumber: '556243997501'
},
{
countryCode: 'IE',
vatNumber: '6388047V'
}
];
let results = [];
let index = 0;
args.forEach((arg) => {
soap.createClient(url, (err, client) => {
if (err) throw err;
client.checkVat(arg, (err, result) => {
if (err) throw err;
let obj = {
countryCode: arg.countryCode,
vatNumber: arg.vatNumber,
requestDate: result.requestDate,
valid: result.valid,
name: result.name,
address: result.address
}
results.push(obj);
console.log(results);
});
});
index++;
});
#2 install soap and run it
npm install soap
node get-vat.js

Related

How to search nested property in mongoose

hi I have mongodb document like below:
{
_id: ObjectId("63df40c651f1358f2b60f24a"),
origin: {
country: 'Usa',
state: 'Washington',
city: 'Washington',
type: 'Point',
coordinates: [ 12.555, 18.645 ]
},
destination: {
country: 'Usa',
state: 'Montana',
city: 'Yellowstone',
type: 'Point',
coordinates: [ 12.555, 20.645 ]
},
date: 'mon 2023-12-16',
seats: 4,
status: 'pending',
driver: {
firstName: 'sam',
lastName: 'johnson',
phoneNumber: '92823831736',
socialNumber: '1381222327',
driverId: '63d8f94202653dc3592a0aa4'
},
I use below url and code for finding location base on destination:
URL: "localhost:3000/api/v1/travel/?state=Montana&city=Yellowstone"
and my code is:
const Travel = require("../models/travel-model");
const getAllTravelsByDestination = async (req, res) => {
const { country, state, city } = req.query;
const queryObject = {};
if (country) {
queryObject.destination.country = country;
}
if (state) {
queryObject.destination.state= state;
}
if (city) {
queryObject.destination.city = city;
}
const travelList = await Travel.find({ destination:queryObject });
res.status(StatusCodes.OK).json({ status: "success", travelList });
};
I expect to get my document back but instead i get empty list as response:
{
"status": "success",
"travelList": []
}
please help me for this problam
You created a filter properly. But, instead of find({ destination: queryObject }), you should only do find(queryObject), since the queryObject already contains the destination property.
const travelList = await Travel.find(queryObject);
Check this line of your code:
const travelList = await Travel.find({ destination:queryObject });
You defined destination already in the queryObject. So you should just do
await Travel.find(queryObject);
Please note that queries are by default case-sensitive. So upper & lowercase matters.

GraphQL query return NULL in GraphiQL, but data appears in console log

I have a GraphQL API which is supposed to return data from MySQL and PostGres database. In the resolvers, I have console.log the results and can view the data in the terminal.
address: {
type: AddressType,
description: "An Address",
args: {
id: { type: GraphQLInt },
},
resolve: (parent, args) => {
// Make a connection to MySQL
let result;
connection.query(
`SELECT * FROM addresses WHERE id = ${args.id}`,
(err, res, fields) => {
if (err) console.log(err);
console.log("========");
console.log(res);
console.log("+++++++++");
console.log(res[0]);
// console.log(result);
}
);
return result;
},
},
In the terminal, I can see the results when I run the query on GraphiQL:
[nodemon] starting `node schema.js`
Server is running
Connected to PSQL database.
Connected to mySQL database.
========
[
RowDataPacket {
id: 1,
address_type: 'House',
status: 'Inactive',
entity: 'Building',
number_and_street: 'PO BOX 276',
suite_and_apartment: 'PO',
city: 'Ennis',
postal_code: '59729-0276',
country: 'USA',
notes: 'Dolorem quia repellendus et et nobis.',
created_at: 2020-12-18T05:00:00.000Z,
updated_at: 2021-05-21T04:00:00.000Z,
latitude: null,
longitude: null
}
]
+++++++++
RowDataPacket {
id: 1,
address_type: 'House',
status: 'Inactive',
entity: 'Building',
number_and_street: 'PO BOX 276',
suite_and_apartment: 'PO',
city: 'Ennis',
postal_code: '59729-0276',
country: 'USA',
notes: 'Dolorem quia repellendus et et nobis.',
created_at: 2020-12-18T05:00:00.000Z,
updated_at: 2021-05-21T04:00:00.000Z,
latitude: null,
longitude: null
}
However on GraphiQL, I get null for data.
Input:
{
address(id: 1) {
address_type
}
}
output:
{
"data": {
"address": null
}
}
I am very new to GraphQL. What could I be missing here? I am attempting to get this information from the terminal to show upon query in GraphiQL. Just trying to learn more.
The classic problem with inattention:
You use the res variable for the console. And nowhere are you assigning a value to result.
And the return result is executed before the query is executed. (out of context where you have data)
See the documentation for how to use the async / await syntax. You are currently using callbacks - which is not a recommended syntax.
Not sure, but should be something like, you should use async/await, and await the return of query data. Also be sure to assign the value to the variable you have:
address: {
type: AddressType,
description: "An Address",
args: {
id: { type: GraphQLInt },
},
resolve: async (parent, args) => {
const result = await connection.query('SELECT * FROM addresses WHERE id = $1', [args.id]);
return result;
},
},
What ended up working for me was the following:
address: {
type: AddressType,
description: "An Address",
args: {
id: { type: GraphQLInt },
},
resolve: async (parent, args) => {
const [rows, fields] = await promisePool.query(
`SELECT * FROM addresses WHERE id = ${args.id}`
);
console.log(rows[0]);
return rows[0];
},
},

Display One-to-Many result in a JSON with nodejs

Hello I have this model:
Gateways
-serial
-name
-ip
Devices
-uui
-vendor
-name
-gw_serial
Where a Gateway has 1 or many devices
I need to show a result like this in my rest/api in nodejs with SQLITE3:
{
serial: 123,
name: Huawei,
ip: 192.168.12.1,
devices:[
{
uuid: 888,
vendor: Intel,
name: mouse,
},
{
uuid: 999,
vendor: Intel,
name: keyboard,
}
],
serial: 345,
name: Apple,
ip: 192.168.12.3,
devices:[
{
uuid: 567,
vendor: Intel,
name: mouse,
},
{
uuid: 893,
vendor: Intel,
name: keyboard,
}
]
}
I presume you are using node-sqlite3. I haven't tested it with real database, but here I did some kind of mocking and demo of the function.
Perhaps this is what you need:
const get_grouped = async (db) => {
return new Promise((resolve, reject) => {
const sql = `
SELECT serial,
gateways.name AS gw_name,
uuid,
vendor,
devices.name
FROM gateways
JOIN devices
ON gateways.serial = gw_serial
`;
const acc = {};
db.each(sql, (error, gw_dev) => {
if(error) return reject(error);
acc[gw_dev.serial] = acc[gw_dev.serial] || {
serial: gw_dev.serial,
name: gw_dev.gw_name,
ip: gw_dev.ip,
devices: []
};
acc[gw_dev.serial].devices.push({
uuid: gw_dev.uuid,
vendor: gw_dev.vendor,
name: gw_dev.name,
});
}, (error, rows) => error ? reject(error) : resolve(Object.values(acc)));
});
};
Basically you pass the database instance to this function.
On every row the result is stored in the acc variable. If there is no gateway with that serial it is initialized. Then the device is just pushed to it's collection. Of course this assumes that the serial is unique per gateway but it should be.
When the oncomplete callback is called if there are no errors the result is presented as the values of the acc.

Getting input from console

I have this code
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/clboTest';
// this could have comed from a form from the browser
var objToInsert = {
_id: 2,
price: 20000,
name: stdin,
description: "20 carat gold ring. ",
//schoolID: { name: 'RUC', address: 'Roskilde', country: 'Denmark' }
};
MongoClient.connect(url, function (err, db) {
var collection = db.collection('products');
collection.insert(objToInsert, function (err, result) {
console.log(result);
db.close();
});
});
I don't want to have the information hardcoded (such as price, name). How can I input something new in the console instead of having to hardcore my insert.js file with new information over and over again?
You could use a package called readline-sync. Then you could wait for the user input before you insert the object:
var readlineSync = require('readline-sync');
var name = readlineSync.question('name: ');
var price = readlineSync.questionInt('price: ');
console.log(name);
console.log(price);
var objToInsert = {
_id: 2,
price: price,
name: name,
description: "20 carat gold ring. ",
//schoolID: { name: 'RUC', address: 'Roskilde', country: 'Denmark' }
};
Good luck!

Javascript variable scope when mongoose query

I'm working with node.js, mongoose and foursquare API.
foursquare.getVenues(params, function(err, venues) {
if(err) return res.json(JSON.stringify({status: 'error', returnData: err}));
// variable initialization
var rooms = [];
var vanueItem;
// iterate foursquare return list (venue item)
venues.response.venues.forEach(function(item) {
Room.aggregate(
[
{ "$group": {
"_id": '$mobileUser.genderType',
"genderTypeCount": { "$sum": 1 }
}}
],
function(err,result) {
if(err) return res.json(JSON.stringify({status: 'error', returnData: err}));
// build it to return after
vanueItem =
{
id: item.id,
name: item.name,
description: item.description,
contact: item.contact.formattedPhone,
lat: item.location.lat,
lng: item.location.lng,
distance: item.location.distance,
city: item.location.city
};
// insert it into venue array
rooms.push(vanueItem);
}
);
});
return res.json(JSON.stringify({ status: 'success', returnData: rooms }));
});
I'm having a problem with rooms array. When I remove the 'Room.aggregate' query, works fine (all rooms was ok), but when I use the aggregate, the return function gives me empty room.
I already tried remove var from 'var rooms = [];'
Room.aggregate is asynchronous function, if you want iterate over asynchronous function you can use async library, like this
var async = require('async');
foursquare.getVenues(params, function(err, venues) {
if (err) return res.json(JSON.stringify({
status: 'error',
returnData: err
}));
var rooms = [];
var vanueItem;
async.each(venues.response.venues, function (item, next) {
Room.aggregate(
[{
"$group": {
"_id": '$mobileUser.genderType',
"genderTypeCount": {
"$sum": 1
}
}
}],
function(err, result) {
if (err) {
return next(err);
}
// build it to return after
vanueItem = {
id: item.id,
name: item.name,
description: item.description,
contact: item.contact.formattedPhone,
lat: item.location.lat,
lng: item.location.lng,
distance: item.location.distance,
city: item.location.city
};
rooms.push(vanueItem);
next(null);
}
);
}, function (err) {
if (err) {
return res.json(JSON.stringify({
status: 'error',
returnData: err
}));
}
return res.json(JSON.stringify({
status: 'success',
returnData: rooms
}));
});
});

Categories

Resources