Querying MySQL Database from User Input - javascript

I'm working on a VueJS web app, in which I need to query a db of peoples names based off user input.
In my server.js file I have my API endpoint which I want to query and have it hosted on localhost:4000
//Staff
app.get('/staff', (req,res) => {
connection.query(SELECT_CERTAIN_STAFF, (error,results) => {
if(error){
return res.send(error)
}
else {
console.log('Selected STAFF from People')
return res.json({
data: results
})
}
})
})
In my Search.vue this is my search method
//Data
data(){
return {
input: '',
errors: ''
}
},
//Methods
methods:{
search(keyboard){
console.log(this.input)
axios.get('http://localhost:4000/staff?username='+this.input)
.then(response => {
console.log(JSON.stringify(response.data.data))
})
.catch(error => {
console.log(error)
this.errors = error
})
console.log(keyboard.value)
}
},
I added console.log(this.input) + console.log(keyboard.value) to test the correct input is being taken from the user, which it is
In my response, the console.log(JSON.stringify(response.data.data)) is just returning the data in the endpoint /staff, and is not filtering any of the data based on user input.
Anyone have any idea why it's doing this/ different approach? Have I set up the API endpoints correctly?
Thanks

Related

Sveltekit Post Request how to return a Response Object with non blocking database access?

I'm trying to send a POST request to a +server.js endpoint that saves the data to the database without blocking my code from execution
/** #type {import('./$types').RequestHandler} */
export async function POST({ request }) {
request.json()
.then((data) => {
console.log("data: ", data);
getConnection()
.then((conn) => {
let sql = "INSERT INTO accounts (username, password, socialMediaPlatform, accountLink) VALUES (?, ?, ?, ?)";
let result = conn.query(sql, [data.username, data.password, data.socialMediaPlatform, data.accountLink]);
conn.release();
return new Response(JSON.stringify(result), {
status: 200,
});
})
.catch((err) => {
return new Response(JSON.stringify({error: err}), {
status: 400,
});
});
})
.catch((err) => {
return new Response(JSON.stringify({error: err}), {
status: 400,
});
});
}
However I'm getting this error:
Invalid response from route /api/account: handler should return a Response object
But it somehow works and writes the data to the database.
Bonusquestion:
I'm also getting this errormessage from vscode when hovering over the POST function
Shouldn't this be typescript specific?
And shouldn't the error only come if
You are not actually returning anything, as all the return statements are inside functions. You have to add a return at the very start (return request.json()...) and before getConnection or use await instead of chaining (which I would recommend).
TS can check JS as well, there are the flags allowJs and checkJs.

Querying Firebase Collection with UID

On logging on via my signin page and navigating to my dashboard, I am trying to query a collection calls 'hotels' based upon the uid of the logged in user.
The issue I have is the uid I am using to query the collection, appears blank or as per the previous user logged in.
I am calling the data service after signin at my dashboard:
Dashboard.ts
this.getAllStudents();
}
// register() {
// this.auth.logout();
// }
getAllStudents() {
this.data.getAllStudents().subscribe(res => {
this.studentsList = res.map((e: any) => {
const data = e.payload.doc.data();
data.id = e.payload.doc.id;
return data;
})
}, err => {
alert('Error while fetching student data');
})
The dataserivce (data.ts) has the below code, which works, but the uid is either blank on first login or the previous user:
getAllStudents() {
return this.afs.collection('/hotels',ref=>ref.where('userid','==',this.auth.userState.uid)).snapshotChanges();
//return this.afs.collection('/hotels',ref=>ref.where('userid','==',)).snapshotChanges().subscribe(res =>
}
Help! I assume login is not set at the point of querying the database. Cheers

Manipulate MySql timestamp value in JavaScript

I'm working with a MySql database and a web application; I use Firebase Functions (Google Cloud Functions) to retrieve data from tables and send it to the web app. When the record's create_dt and update_dt fields make it to the web application, they're an object that doesn't have any accessible properties.
I'm trying to display the create and update date values in my application, but whenever I try to display one of the values, the web application displays [object Object]. Looking at the object in the console, it looks like an empty object with nothing but prototype properties
I've looked around here and other places on the Internet and found a bunch of articles that show how to manipulate a MySql Timestamp (as a time string) in JavaScript, but none that shows how to actually access the timestamp value.
My goal right now is just to display the time/date value in my app, but ultimately I want to get it as a JavaScript Date object so I can format the output the way I want in my app. Can someone please show me how to do this? I don't get why the timestamp shows up in the browser as an object with no accessible properties.
My function looks like this:
export const get = functions
.runWith({
vpcConnector: 'myapp-connector',
vpcConnectorEgressSettings: 'PRIVATE_RANGES_ONLY'
})
.https.onCall((data, context) => {
// Checking that the user is authenticated.
if (!context.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError(AUTHCODE, AUTHMSG);
}
const idx = data.idx;
if (idx) {
let cmd = `SELECT * FROM companies WHERE id=${idx}`;
return sqlStuff.executeQuery(cmd)
.then(result => {
functions.logger.log('Query result', result);
return { result: result };
}).catch(err => {
functions.logger.log('ERROR', err);
return { err: err };
});
} else {
functions.logger.log('Missing index');
return { result: {} };
}
});
The query code looks like this:
export async function executeQuery(cmd: string) {
const mySQLConfig = {
connectionLimit: 10,
host: functions.config().sql.prodhost,
user: functions.config().sql.produser,
password: functions.config().sql.prodpswd,
database: functions.config().sql.proddatabase,
}
var pool: any;
if (!pool) {
pool = mysql.createPool(mySQLConfig);
}
return new Promise(function (resolve, reject) {
pool.query(cmd, function (error, results) {
if (error) {
return reject(error);
}
resolve(results);
});
});
}
On the client, I'm using AngularFireFunctions since this is an Angular (Ionic) app.
getCompany(idx: number) {
const companyGet = this.fireFunc.httpsCallable('companyGet');
companyGet({ idx }).subscribe(
data => {
if (data.result && data.result.length > 0) {
this.company = Object.assign({}, data.result[0]);
} else {
this.alertController.create({
header: 'Company Lookup',
message: `The specified company record (${idx}) does not exist`,
buttons: ['OK']
}).then(alert => {
alert.present();
this.router.navigate(['/companies']);
});
}
},
err => {
this.alertController.create({
header: 'Company Refresh',
message: `The process reported the following error: ${err.message}`,
buttons: ['OK']
}).then(alert => alert.present());
},
() => {
console.log('CompanyPage: Company request completed');
}
);
});
}

How can I use an array with req.query?

My problem is how can I bring my data structure into the query? I want to be able to search everything via one query. How can I implement this?
I tried to enter the query so => ?basicData.tasks.title=Fleetmanagement. With it I can find all the data that fleet management has in it. But now I want to search with two titles.
Example:
?basicData.tasks.title=Fleetmanagement&basicData.tasks.title=OCPP Backend
But it doesn't work. How can i implement that right?
This is my data structure:
"basicData": {
"tasks":[
{"title": "Fleetmanagement"},
{"title": "OCPP Backend"}
]
}
My Code:
export const allCompanyData = (req: Request, res: Response) => {
if (req.query) {
Company.find(req.query).then(docs => {
logger.info(`Query works ${req.query}`);
res.json({
query: req.query
})
res.status(200).json(docs);
}).catch(err => {
logger.error(`Error ${err}`);
res.status(400).json(`Error ${err}`)
})
} else {
Company.find()
.then((items: any) => {
logger.info("Successful finding");
res.status(200).json(items);
})
.catch((err: any) => {
logger.error(`Error ${err}`);
res.status(400).json(`Error ${err}`);
});
}
};
You append [] to the param name on the client side to indicate that you are providing an array:
?basicData.tasks.title[]=Fleetmanagement&basicData.tasks.title[]=OCPP%20Backend
Then req.query will be:
{ 'basicData.tasks.title': ['Fleetmanagement', 'OCPP Backend'] }

vue w/ axios should get-request with a variable retrieved from another get-request

When building a component that contains 3D print information named a fabmoment, I succeeded using the $route.params filling an author-object and a fabmoment-object with information, like so:
<script>
import SingleSummarized from './SingleSummarized'
// import Comments from '#/components/Comments/Multiple'
export default {
name: 'Single',
data () {
return {
author: null,
fabmoment: null,
tempLicenseID: null,
license: null
}
},
created () {
this.$http.get(`/users/${this.$route.params.author_id}`)
.then(request => { this.author = request.data })
.catch(() => { alert('Something went wrong when trying to retrieve this user!') })
this.$http.get(`/users/${this.$route.params.author_id}/fabmoments/${this.$route.params.fabmoment_id}`)
.then(request => { this.fabmoment = request.data })
.catch(() => { alert('Something went wrong when trying to retrieve the fabmoment attribute data!') })
this.$http.get(`/licenses/${this.fabmoment.license_id`)
.then(request => { this.license = request.data })
.catch(() => { alert('Something went wrong when trying to retrieve the license!') })
},
components: {
SingleSummarized
// Comments
}
}
</script>
In the created part you can see I also am trying to retrieve a license for the fabmoment using this.fabmoment.license_id. It fails on this line.
Is a tempLicenseID an idea? Because I suspect the this.fabmoment is not available yet. And how would I use this to make the request work? Or any other more sensible solution?
You have to make the request for the licenses after you have retrieved the fabmoment object:
this.$http.get(`/users/${this.$route.params.author_id}/fabmoments/${this.$route.params.fabmoment_id}`)
.then(request => { return this.fabmoment = request.data })
.then( fabmoment => this.$http.get(`/licenses/${fabmoment.license_id`)
.then(request => { this.license = request.data })
.catch(() => { alert('Something went wrong when trying to retrieve the fabmoment attribute data!') })

Categories