Create a server on Node.js - javascript

I create a server on Node.js. I use SQL server. I want to creata a sql query that find book by the given input. When I wrote my query error was:
name: 'ERROR',
handlerName: 'onErrorMessage',
number: 207,
state: 1,
class: 16,
message: "Invalid column name '%#param4%'.",
serverName: 'DESKTOP-PQSULQS\SQLEXPRESS',
procName: '',
lineNumber: 1
This is a searchMethod:
async function searchBook(input){
let result = await sql.query `SELECT * FROM dbo.Books WHERE Title = ${input} OR Kind = ${input} OR Author = ${input} OR Title LIKE "%${input}%"` ;
return result.recordset;
}
I try to resolve this problem. But I don't know why server throw this exception.Any advices?

the main issue with shared code sample is each nvarchar column value should to be encased in a single quotation '' if you gone use template literal with static vales.
then the code will be as the following:
async function searchBook(input){
let result = await sql.query(`SELECT * FROM dbo.Books WHERE Title = '${input}' OR Kind = '${input}' OR Author = '${input}' OR Title LIKE '%${input}%'`);
return result.recordset;
}
but this code has sql injection vulnerability so to prevent it. use parameters to overcome this issue.
so your code will be as the following:
async function searchBook(input){
let request = new sql.Request();
request.input('input', sql.NVarChar, input);
let result = await request.query(`SELECT * FROM dbo.Books WHERE Title = #input OR Kind = #input OR Author = #input OR Title LIKE '%' + #input + '%'`);
return result.recordset;
}

I think the problem lies in the construction of the request.
The use of parameters should solve the problem.
async function searchBook(input){
let result = await sql.query`SELECT * FROM dbo.Books WHERE Title = #title OR Kind = #kind OR Author = #author OR Title LIKE "%" + #title + "%"`,
{
params: {
title: input,
kind: input,
author: input
}
};
return result.recordset;
}

Related

Recursive function freezing, Jira Forge app

I am trying to do:
pull 50 rows from third party API
create payloads for issues
create issues (bulk)
back to step 1. until I pulled all rows from third party API.
Code:
/**
* Create Jira Issues
*
* #param configuration
* #param assetType
* #param allIds
* #param findingsOffset
*/
export const createJiraIssue = async (configuration: IntegrationConfiguration, assetType: string, allIds: any, findingsOffset: number) => {
//HERE I AM GETTING 50 rows from third party API
const findings: any = await getAllFindings(configuration.assets, 'open', assetType, findingsOffset);
const custom_field: string = await storage.get('whvid_custom_field_id');
let jiraIssuePayloads : any = {"issueUpdates": []};
for (const item of findings.collection) {
const i = findings.collection.indexOf(item);
//Check if we can create the Jira issue
if (!allIds.includes(item.id.toString()) && await isVulnerabilityAllowedToCreate(item)) {
//create payloads for issues
}
//CREATE issues bulk
await createIssues(jiraIssuePayloads);
jiraIssuePayloads = null;
//here I am calling same function but with new offset
if (findings['offset'] > 0) {
await createJiraIssue(configuration, assetType, allIds, findings['offset']);
}
}
Third party API call:
export const getAllFindings = async (assets: [], status: string, assetType: string, startOffset: number) => {
const findings = await getFindingByAssetIdAndAssetType(assets, status, assetType, startOffset.toString());
if(findings.page.totalPage !== findings.page.currentPage){
findings.offset = startOffset + limit.FINDINGS;
}
return findings;
}
My app usually stop working after 18th call. With no error no logs anything. I am very new to JS, so maybe problem is async functions.
Any idea what can be problem?
Thank you

Trying to send data from javascript to python POS odoo using rpc.query

I am trying to send my data in the list to their fields so i can retrieve them into another screen in same module / project.
The list i am trying to send :
var vals = {
'token_number':Token,
'partner_id':customer_name,
'queue_line_ids':queue_lines,
}
where Token is random number generated on custom_button click,customer_name is the id of customer obtained by "this.pos.get_order().cid" and queuelines is array of product and their info obtained from orderlines.
The rpc.query i wrote by referring to point_of_sale in odoo13/addon/ :
return rpc.query({
model: 'pos.queue',
method: 'create',
args: [vals],
}).then(function () {
console.log("Success")
}).catch(function (reason){
var error = reason.message;
console.log(error);
});
The pos.queue in my module's model.py :
class POSOrderQueue(models.Model):
_name = 'pos.queue'
token_number = fields.Integer(string="Token Number", store=True)
partner_id = fields.Char(store=True)
pos_order_id = fields.Char(store=True)
order_progress = fields.Selection([('in_queue', 'In Queue'),
('in_progress', 'In Progress'),
('done', 'Done')], string="Order progress", default='inqueue', store=True)
no_items = fields.Integer(string='No of Items', store=True)
queue_line_ids = fields.One2many('pos.queue.line', 'queue_id')
def create(self):
val = {
"token_number": self.token_number,
"partner_id": self.partner_id,
"queue_line_ids": self.queue_line_ids,
}
self.env['pos.queue'].create(val)
Yes so i was finding solution to pass orderline data in my database along with other as i came a long way from time this question was passed so i felt obliged to share my findings and modification which enable to pass token number Customer id Estimated time & status.
Following are the modification i did so far
The list :
val_list = {
'token_number':Token,
'partner_id':customer_name,
'pos_order_id':torder.name,
'est_time':e_time,
'order_progress':torder.order_progress,
};
where torder is this.pos.get_order().
MY rpc query become like (thanks to my supervisor)
return rpc.query({
model: 'pos.queue',
method: 'create_token',
args:[val_list],
}).then(function () {
console.log("Success")
}).catch(function (reason){
var error = reason.message;
console.log(error);
});
the model became like:
class POSOrderQueue(models.Model):
_name = 'pos.queue'
token_number = fields.Integer(string="Token Number", store=True)
partner_id = fields.Char(store=True)
pos_order_id = fields.Char(store=True)
est_time = fields.Text(string="estimated time", store=True)
order_progress = fields.Selection([('in_queue', 'In Queue'),
('in_progress', 'In Progress'), ('cancel', 'Cancel'),
('done', 'Done')], string="Order progress", default='in_queue', store=True)
no_items = fields.Integer(string='No of Items', store=True)
queue_line_ids = fields.One2many('pos.queue.line', 'queue_id')
#api.model
def create_token(self, val_list):
res = super(POSOrderQueue, self).create(val_list)
print("yes working")
return res
class POSOrderQueueLine(models.Model):
_name = 'pos.queue.line'
queue_id = fields.Many2one('pos.queue')
product_name = fields.Char(store=True)
product_quant = fields.Integer()
product_price = fields.Float()
def create(self, vals):
res = super(POSOrderQueueLine, self).create(vals)
return res
The problem is partially solved but i can't acheive my last objective which is to pass orderline data through rpc query into my model pos.queue.line so it can be viewable in my custom view of odoo13 which is like this
screenshot of my view table

How can I get the highest (and last) number from an API call in JSON?

I'm using the backpack.tf API for a Discord bot. I'm currently attempting to make a price command, using the API to find the prices of the items. Rather than returning the current price, the API returns all of the price updates, as shown below.
Only the last value in this call (85) is currently correct and updated. The code I'm using to send and log the results is as follows:
const Discord = require("discord.js");
const superagent = require("superagent");
String.prototype.toProperCase = function() {
return this.replace(/\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
};
module.exports = {
run: async(client, message, args) => {
let item = args[0]
let quality = args[1]
let { body } = superagent
.get(`https://backpack.tf/api/IGetPriceHistory/v1?appid=440&item=${item}&quality=${quality}&tradable=Tradable&craftable=Craftable&priceindex=0&key=5eeea0c9c995374dc219a4e2`);
message.channel.send(new Discord.MessageEmbed()
.setTitle(`Price info of ${item.toProperCase()} (${quality.toProperCase()})`)
.setDescription(`${response.history[HIGHESTNUMBER].value} refined metal`)
)
},
aliases: ["price", "gp"]
}
Where HIGHESTNUMBER is shown in the code is where I need the highest number from the returned JSON. If and how am I able to complete this? Thanks.

Firebase Push Key Undefined

I am looking to get the the key from a firebase push command when using cloud functions.
const params = {
date: Date.now(),
movie,
movieId: movie.id,
userId: user.uid,
group: 'home',
type: 'watched'
};
const pastRef = event.data.adminRef.root.child(`pastActivity/${user.uid}`);
var newPostRef = pastRef.push().set(params);
var postId = newPostRef.key;
console.log(postId); //undefined
The postId however comes back as undefined. Have try a few other suggested methods without any results.
Reference.set() returns a void promise that resolves when the write operation completes. You can't get the key of it. Instead, split the push() and set(...) into separate statements, so that you can capture the reference
var newPostRef = pastRef.push();
newPostRef.set(params);
var postId = newPostRef.key;
console.log(postId); //undefined
A shorter version can be used if you don't need the newPostRef variable
//var newPostRef = pastRef.push().set(params);
//var postId = newPostRef.key;
const newPostRefKey = pastRef.push(params).key
//this pushes the data and returns the key

how to clone the mongoose query object in javascript

I am facing the problem of clone of the mongoose query object .Javascript the copy the one object into another object by call-by-ref but in my project there is scenario i need to copy one object into another object by call-by-value.
var query=domain.User.find({
deleted: false,
role: role
})
var query1=query;
I have the scenario change in the query object is not reflected in query1. I google and try so many way to clone the object but it does't work.The query object is used in another function for pagination and query1 object is used for count query.
1.I used to Object.clone(query1) error Object.clone is not function
2.I used Object.assign(query1) but it does't works fine.
3.I used other so many ways can anybody help me to sort this problem
Alternative solution using merge method:
const query = domain.User.find({
deleted: false,
role: role
}).skip(10).limit(10)
const countQuery = query.model.find().merge(query).skip(0).limit(0)
const [users, count] = await Promise.all([query, countQuery.count()])
you are trying to clone a cursor, but it is not the right approach, you probably just need to create another
like this:
var buildQuery = function() {
return domain.User.find({
deleted: false,
role: role
});
};
var query = buildQuery();
var query1 = buildQuery();
This is work for me:
const qc = sourceQuery.toConstructor();
const clonedQuery = new qc();
This code work in pagination function where sourceQuery passed as parameter and i dont known what models used. Also it work with aggregations and complex queries.
public async paging(
query: mongoose.DocumentQuery<mongoose.Document[], mongoose.Document>,
params,
transformer: any = null
) {
let page = Number(params.page);
if (!page) page = 1;
let page_size = Number(params.count);
if (!page_size) page_size = 100;
const qc = query.toConstructor();
const cq = new qc();
return cq.countDocuments().exec()
.then(async (total) => {
const s = params.sort;
if (s) {
query.sort(s);
}
query.limit(page_size);
query.skip(page_size * (page - 1));
let results = await query.exec();
if (transformer) {
results = await Promise.all(results.map((i) => transformer(i)));
}
const r = new DtoCollection();
r.pages = Math.ceil(total / page_size);
r.total = total;
(r.results as any) = results;
return r;
});
}
Sergii Stotskyi's answer works just fine and is very elegant, except that count is deprecated.
countDocuments or estimatedDocumentCount should be used instead.
However, this causes the error the limit must be positive. We can walk around this by set limit to a large integer.
const query = domain.User.find({
deleted: false,
role: role
}).skip(10).limit(10)
const countQuery = query.model.find().merge(query).skip(0).limit(Number.MAX_SAFE_INTEGER)
const [users, count] = await Promise.all([query, countQuery.countDocuments()])
Since mongoose v6 you can use Query.prototype.clone
E.g. for your code snippet:
const query = domain.User.find({
deleted: false,
role: role
})
const query1 = query.clone();

Categories