Using node mssql how do I create a database? - javascript

I tried the execute method:
const sql = require('../node_modules/mssql');
var dbname = 'AddressBook';
sql.connect('mssql://sa:1234#localhost/').then(pool => {
return pool.request().input('db_name', sql.TYPES.Text, dbname).query`select db_id(#db_name) as idn`.then(result => {
if (result[0].idn === null) {
return pool.request().input('db_name', sql.TYPES.Text, dbname).execute`create database #db_name`;
}
}).catch(err => {throw(err)});
}).catch(err => console.log(err));
I get:
message: 'The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. The RPC name is invalid.',
Also tried the query method:
return pool.request().input('db_name', sql.TYPES.Text, dbname).query`create database #db_name`;
I get
message: 'Incorrect syntax near \'#db_name\'.',
Is there a different method or am I missing something?

Related

Storing JSON objects in the postgreSQL using parameterized query

I am having problems with saving JSON objects in the database using parameterized queries. I am using postman to send this object on red.body
enter image description here
On my server side I havet his code:
queryController.createQuery = (req, res, next) => {
const { info }= req.body;
const sqlQuery = 'INSERT INTO test (info) VALUES ($1) RETURNING *';
db.query(sqlQuery, [info])
.then(result => {
console.log(result);
if (result) res.locals.message = "Saved the query successfully";
next();
})
.catch(err => {
return next({
log: `queryController.createQuery: ERROR: ${typeof err === 'object' ? JSON.stringify(err) : err}`,
message: { err: 'Error occurred in queryController.createQuery. Check server log for more details.'},
})
})
Why is that I still get this error: enter image description here
throw new TypeError('Client was passed a null or undefined query')
^
TypeError: Client was passed a null or undefined query
Here is my table schema:
CREATE TABLE test (
id serial NOT NULL PRIMARY KEY,
info json NOT NULL
);
How do I format $1 correctly to get it accept it as JSON file?
Query example:
EXECUTE 'INSERT INTO test (info) VALUES ($1) RETURNING *' USING '[{"size": "Small", "quantity": 1, "product_id": 1}]'::jsonb;

Node.js getting Uncaught error: invalid input syntax for type integer: "NaN"

I am very new to JS and I'm trying to create an API using node.js however I'm getting the error:
Uncaught error: invalid input syntax for type integer: "NaN"
The requests are fine when I do a GET and POST request but I'm having trouble with the PUT and DELETE. I get the same error with both requests. Here is my code:
const getProfiles = (request, response) => {
pool.query('SELECT * FROM profiles', (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
const addProfiles = (request, response) => {
const {name, bio} = request.body
pool.query(
'INSERT INTO profiles (name, bio) VALUES ($1, $2) RETURNING id',
[name, bio],
(error) => {
if (error) {
throw error
}
response.status(201).json({status: 'success', message: 'Profile added.'})
})
}
const updateProfiles = (request, response) => {
const id = parseInt(request.params.id)
const {name, bio} = request.body
pool.query(
'UPDATE profiles SET name = $1, bio = $2 WHERE id = $3 RETURNING id',
[name, bio, id],
(error) => {
if (error) {
throw error
}
response.status(202).json({status: 'success', message: 'Profile updated with ID: ${id}'})
})
}
const deleteProfiles = (request, response) => {
const id = parseInt(request.params.id)
pool.query(
'DELETE FROM profiles WHERE id = $1', [id],
(error, results) => {
if (error) {
throw error
}
response.status(203).send(`Profile deleted with ID: ${id}`)
})
}
app
.route('/profiles')
// GET endpoint
.get(getProfiles)
// POST endpoint
.post(addProfiles)
//UPDATE endpoint
.put(updateProfiles)
// DELETE endpoint
.delete(deleteProfiles)
// Start server
app.listen(process.env.PORT || 3002, () => {
console.log(`Server listening`)
})
I am very much new to this and if you spot where I went wrong I would very much appreciate and explanation for me to better understand it and never make this mistake again. Thank you.
As far as I can see, req.params.id is undefined, because you are not telling express that route should receive a param.
Change this:
app
.route('/profiles')
// GET endpoint
.get(getProfiles)
// POST endpoint
.post(addProfiles)
//UPDATE endpoint
.put(updateProfiles)
// DELETE endpoint
.delete(deleteProfiles)
To this:
app
.route('/profiles')
// GET endpoint
.get(getProfiles)
// POST endpoint
.post(addProfiles)
app
.route('/profiles/:id') // :id means we are expecting that param
//UPDATE endpoint
.put(updateProfiles)
// DELETE endpoint
.delete(deleteProfiles)
And when you do the PUT or DELETE request, the endpoint should look like this: /profiles/
The error means you'r providing a "Not a Number" (NaN) where your app expects a number (integer).
It's most probably the id in the updateProfiles or deleteProfiles, because you haven't defined it your route
app
.route('/profiles/:id')
// GET endpoint
.get(getProfiles)
// POST endpoint
.post(addProfiles)
//UPDATE endpoint
.put(updateProfiles)
// DELETE endpoint
.delete(deleteProfiles)

PG-Promise Proc Erroring Out with Unknown Parameter Type

We are attempting to write a PostgreSQL Procedure to insert data into a table. We have created the procedure and ran said procedure with the variables below and it inserts just fine. However, when we try to use pg-promise with our express server, our string parameters are being read as unknown. When we iterate over the post body, we see that each parameter is reading as the type we expect to go in, and PostgreSQL is reading integer correctly, but it isn't reading string correctly. I've attempted to use the as.text function and it sends in the parameter value as "''" but that still reads as unknown. Is there something we are missing to successfully post the data?
let createInspection = async (req, res, next) => {
try {
let params = [];
for (let prop in req.body) {
console.log(typeof req.body[prop]);
params.push(req.body[prop]);
}
console.log(params)
let data = await db.proc('Inspections_Create', params);
res.status(200)
.json({
status: 'success',
data: data,
message: 'Inserted Inspection'
});
}
catch (error) {
return next(error);
}
}

How to get receipt-data from Post request in Node.js

I'm trying to send a receipt to my Node.js server. At the moment It prints out the receipt-data in firebase which indicates its gotten it from the POST request I sent from my iOS App. However i can't pass properly in my code to be validated in const receipt = request.body;. How can I pass it along in the correct way?. Thanks.
exports.receiptValidation = functions.https.onRequest((request, response) => {
const receipt = request.body;
console.log(receipt);
iap.config({
applePassword: 'MySharedAppleKey',
test: true
});
iap.setup((error) => {
if (error) {
console.log('Failed to validate receipt', error);
}
});
iap.validate(receipt).then((pResponse) => {
//Check if receipt is valid
if (iap.isValidated(pResponse)) {
console.log('The receipt is valid', pResponse);
response.send(pResponse);
}
return pResponse;
})
.catch((error) => {
console.log(`Sorry couldn't validate receipt`, error);
response.send(error);
return error
});
});
Here is my output in Firebase. I'm using a firebase function
I solved it by changing my receipt-data string in both Swift and Server code
Swift
let receiptData = receipt!.base64EncodedString()
let requestReceiptDict = ["receipt": receiptData]
Node.js
const receipt = request.body.receipt;
console.log(receipt);

How to add results from a promise based API call with message.addReply using Recast.ai?

I'm making a bot that searches restaurants based on location. Can anyone help me why this doesnt show up in FB messenger?:
restaurants(result.getMemory('location').raw)
.then(res=>{
message.addReply(res);
message.reply();
});
}
The call to the restaurants function returns the results from a YELP API call (an array of restaurants) but when I add it as a reply to message, nothing happens in FB messenger.
Here is the full code for message.js:
const recastai = require('recastai');
const restaurants = require('./restaurants');
// This function is the core of the bot behaviour
const replyMessage = (message) => {
// Instantiate Recast.AI SDK, just for request service
const request = new recastai.request(process.env.REQUEST_TOKEN,
process.env.LANGUAGE);
// Get text from message received
const text = message.content;
console.log('I receive: ', text);
// Get senderId to catch unique conversation_token
const senderId = message.senderId;
// Call Recast.AI SDK, through /converse route
request.converseText(text, { conversationToken: senderId })
.then(result => {
//Recast takes text analyses that, returns a result object, generates replies adds messages to reply stack and then sends the replies
//Call Yelp API with when the intent is Location. When Yelp returns result we add it to the result.replies array.
//Then we add everything in result.replies to the messaging queue that sends the responses to FB
if (result.action) {
console.log('The conversation action is: ', result.action.slug);
}
// If there is not any message return by Recast.AI for this current conversation
if (!result.replies.length) {
message.addReply({ type: 'text', content: 'I don\'t have the reply to this yet :)' });
} else {
// Add each reply received from API to replies stack
result.replies.forEach(replyContent => message.addReply({ type: 'text', content: replyContent }));
}
// Send all replies
message.reply()
//send initial reply generated by Recast first
.then(() => {
//call restaurant function that returns a list of results from API
//if the action is location and done
if(result.action && result.action.slug === 'location' && result.action.done){
restaurants(result.getMemory('location').raw)
.then(res=>{
console.log(res);
message.addReply(res);
message.reply();
});
}
})
.catch(err => {
console.error('Error while sending message to channel', err);
});
})
.catch(err => {
console.error('Error while sending message to Recast.AI', err);
});
};
module.exports = replyMessage;
And here is my restaurants.js code that is imported into the message.js file for the bot behavior:
const rp = require('request-promise');
// Load configuration
require('./config');
const restaurants = (location) => {
return Promise.all([
yelpCall(location)
]).then(result => {
//result contains the return value from Yelp call
return result;
});
};
const yelpCall = (location) => {
const auth = {
method: 'POST',
url: 'https://api.yelp.com/oauth2/token?grant_type=client_credentials&client_id='+ process.env.YELP_APP_ID +'&client_secret='+process.env.APP_SECRET
};
return rp(auth)
.then(result => {
const tokens = JSON.parse(result);
return tokens;
})
.then(result=>{
const options = {
url: 'https://api.yelp.com/v3/businesses/search?location=' + location + "&term=thai",
headers: {Authorization: "Bearer " + result.access_token}
};
return rp(options).then(findings =>{
return findings;
});
});
};
module.exports = restaurants;
A few thoughts :
message.reply is thenable, therefore return message.reply() in two places.
request.converseText() is thenable, therefore return request.converseText(...).
restaurants is thenable, therefore return restaurants(...).
in message.js, message.addReply() is passed object of the form {type:..., content:...} in two places but finally just res. Is that correct?
in restaurants.js, Promise.all() appears to be unnecessary. It will cause its result to be wrapped in an array. module.exports = location => yelpCall(location); seems more appropriate.

Categories

Resources