I have
const {data, error, isLoading } = useFetchBulkClassesQuery(something)
to pass data to MySql via this API:
fetchBulkCclasses: builder.query ({
query: (something) => {
return {
url: '/bulkclasses',
params: {
class: something
},
method: 'GET'
at the backend, I have
tyapp.get("/bulkclasses", (req, res) => {
const q = 'select * from recent where ticker in (?)'
db.query(q, [[req.query.ticker]], (err, data) => {
if(err) {return res.json(err)}
return res.json(data)pe here
it al works fine if I use a single variable, like something = 'ClassA'
But I want to use it for multiple entries like ClassA, ClassB, ClassC, ...
But it only takes the first one (or the last one depending on what I try).
What am I doing wrong? Or what haven't I tried (or what do I not know)?
I tries:
Something = ['ClassA', 'ClassB', ...] -> the thing that get passed to the backend is 'ClassA, ClassB' en and it needs to be 'ClassA', 'ClassB', ...
Something = [[ClassA], [ClassB],...] -> same result
It seemed a bit impossible to do, so I did choose the easiest solution: changing the design of my tables and update the query.
Related
I have an array of labels for form inputs named changing_variable, which are dependent on what a user selects from a drop down menu, so these are unknown.
I need to be able to let the property of the Axios.post method, equal to the variable in order to input the correct data into my database.
Any examples I see online have properties like:
name: this.name
age: this.age
However this cannot work for me since I cannot hard code the values since they change depending on the user input, and also there is over a hundred for each user input.
If anyone can help me pass this changing variable to my backend. Thanks
My current code :
var i;
var changing_variable;
for(i=1; i<arr.length; i++)
{
changing_variable = inputValues[i].text
Axios.post(URL, changing_variable)
.then(res => {
console.log(res);
console.log(res.data);
console.log(changing_variable)
})
}
};
EDIT
Node.js code
app.post('/create', (req,res) => {
const test_variable= req.body.changing_variable;
db.query("INSERT INTO iptable (test_variable) VALUES(?)",
[test_variable], (err,result) =>{
if(err){
console.log(err)
}else {
res.send("Values Inserted")
}
}
)
});
Terminal error message
code: 'ER_BAD_NULL_ERROR',
errno: 1048,
sqlMessage: "Column 'test_variable' cannot be null",
sqlState: '23000',
index: 0,
sql: 'INSERT INTO iptable (test_variable) VALUES(NULL)'
The solution is Using application/x-www-form-urlencoded, URLSearchParams
By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use the URLSearchParams API.
const params = new URLSearchParams({ foo: 'bar' });
params.append('extraparam', 'value');
axios.post('/foo', params);
REF https://github.com/axios/axios#urlsearchparams
Good day,
I've been trying to learn a bit of angular and nodejs. I found a tutorial on a realtime chat app and made some few adjustment to some function of the code. But the one aspect that I cannot seem to get right is the ability for the user to post to a feed. The login process works, the user is already logged in but the user can't post. I would also like to be able to get all they data i insert from all the user to show up like a normal feedview will. Please assist.
Here are my files:
FROM MY CONTROLLER HERE IS THE CODE WHEN THE BUTTON IS PRESSED
$scope.postDatatoDd = () => {
appService.httpCall({
url: '/posts',
params: {
'posts': $scope.data.info,
'from_user_id': $scope.data.username
}
})
.then((response) => {
// $scope.$apply();
})
.catch((error) => {
alert(error.message);
});
}
and here is my route file:
this.app.post('/posts', async(request,response) => {
const reqResponse = {}
const data = {
posts : request.body.postDatatoDd,
from_user_id: request.body.username
};
if (data.posts === ''){
reqResponse.error = true;
reqResponse.message = `error, input`;
response.status(412).json(reqResponse);
} else {
const result = await helper.insertFeed(data);
if (result === null) {
reqResponse.error = true;
reqResponse.message = `they was an error.`;
response.status(417).json(reqResponse);
} else {
reqResponse.error = false;
reqResponse.userId = result.insertId;
reqResponse.message = `posted succesfully`;
response.status(200).json(reqResponse);
}
}});
and in my helper file there is this function to insert data:
async insertFeed(params){
try {
return await this.db.query(
`INSERT INTO posts (from_user_id,posts) values (?,?)`,
[params.from_user_id,params.postDatatoDd]
);
} catch (error) {
console.warn(error);
return null;
}
}
On the client side here is the button with :
<label for="postDatatoDd">Post</label>
<input type="text" id="postDatatoDd"
ng-model="data.postDatatoDd"
class="feed form-control"
placeholder="post your data here?"
/>
<button ng-click="postDatatoDd()" class="btn btn-primary">Post</button>
</div>
--- EDIT 1---
Data is being inserted now, but it is receiving the values as (NULL, NULL).
--- EDIT 2 ---
After closely looking at the code and fixing some naming variables the code works fine, the data is being inserted in mysql as it should.
Other than a lot of typos when it comes to the variables reference. The code seem to be fine.
Assuming that you using appservice class somewhere in your code and its functioned, then everything else will work.
You are getting the (NULL, NULL) because you are parsing parameters that are not being properly parsed out to your helper file, please close attention to that.
appService
.httpCall({
url: "/posts",
params: {
posts: $scope.data.postbuzz,
from_user_id: $scope.data.username,
},
})
.then((response) => {
$scope.$apply();
})
.catch((error) => {
alert(error.message);
});
make sure that the data that you calling from this above function is similar to $scope parameter you passing in your route file that your requesting:
const data = {
posts : request.body.posts,
from_user_id: request.body.from_user_id}
and in your database helper class you running:
`INSERT INTO posts (from_user_id,post) values (?,?)`,
[params.from_user_id,params.posts]
Hope this was helpful
You seem to have an understand already. your question may help a lot more people in the future.
params should be as following, since the data object has properties from_user_id and posts
`INSERT INTO posts (from_user_id,posts) values (?, ?)`,
[params.from_user_id,params.posts]
Might be useful https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp
--- EDIT 2 ---
After closely looking at the code and fixing some naming variables the code works fine, the data is being inserted in mysql as it should.
If you are new to Angular you can use the code as reference.
I'm right now working on a web API with expressjs, kotlin and PostgreSQL. I organized my project in an object oriented way. I also created a class for the database that makes all frequently called queries available as a function. Example:
fun addUser(firstName: String, lastName: String, password: String, classId: Int){
client.query("INSERT INTO users(first_name, last_name, password, class_id) values($1, $2, $3, $4)", arrayOf(firstName, lastName, password, classId));
}
This doesn't work however when I'm trying to issue a SELECT query and return the dataset to the function caller since queries are asynchronous. I already tried assigning the result to an attribute of the database object and using it as soon as the value is assigned, but it seems that the value can't be assigned when I'm checking its value permanently. Does anyone know how I could return the value to the function caller?
Thanks in advance for your answers.
Assuming you are using nodejs and the pg module.
As you said since query function is async you cannot return the result to the caller directly. Traditionally in nodejs the caller passes a callback function to handle the result or the error if there is one.
In Kotlin this would look like:
client.query(MY_QUERY_TEMPLATE, params) { err, result ->
if (err != null) {
// do something with the error
} else {
// do something with the result
}
}
To make this a bit neater you could put your result handler in its own function
fun handleResult(err: dynamic, result: dynamic) {
// put your code here
}
And use it like this:
client.query(MY_QUERY_TEMPLATE, params, ::handleResult)
If you don't like this you have another option. The pg library can return Promise. This abstraction allows you to use method chaining like this:
app.get("/promiseStyle") { req, res ->
val params = arrayOf(42) // or something...
fun handleSuccess(result: dynamic) {
for (row in result.rows) {
res.write(row.someField)
}
res.end()
}
fun handleError(error: dynamic) {
res.status(500).send("Something went wrong");
}
client.query(MY_QUERY_TEMPLATE, params)
.then(::handleSuccess)
.catch(::handleError)
}
You may find the following declaration useful for accessing the various pg client functionality:
#JsModule("pg")
external object pg {
class Client {
fun query(query: String, params: Array<Any>): dynamic
fun query(
query: String, params: Array<Any>, cb: (dynamic, dynamic) -> Unit
)
fun connect()
}
}
The postgres client can then be initialized as follows:
val client = pg.Client()
client.connect()
What is the 'meteor'-way to get a document title by a given ID?
Collection (Articles)
{
'_id' : 'Dn59y87PGhkJXpaiZ',
'title' : 'Sample Article',
'slug' : 'sample-article'
}
client
render() {
const data = [
{ _id: 'Dn59y87PGhkJXpaiZ' },
{ _id: 'kJXpaiZDn59y87PGh' }
{ _id: 'y87PGhkJXpaiZDn59' }
]
return (
<List>
{
data.map(r => {
return <List.Item>r._id</List.Item>
})
}
)
}
With this I will get this output:
<List>
<List.Item>Dn59y87PGhkJXpaiZ</List.Item>
<List.Item>kJXpaiZDn59y87PGh</List.Item>
<List.Item>y87PGhkJXpaiZDn59</List.Item>
</List>
Now I want to display the title instead of the id. So normally I would do
data.map(r => {
const title = Articles.findOne({ _id: r._id }).title
return <List.Item>title</List.Item>
})
But the problem is, that data is a dynamic dataset and I can't/don't want to publish the complete Articles collection. Right now there is no subscription, so I don't get any results for the title.
So I think I have to do a server side call.
Meteor.call('getTitle', r._id, function(err, res) {
console.log(res)
})
But then I'll get the result in the callback function. So how do I get these into the list? Also I want to avoid multiple method calls. I think it would be better to send data and get all titles on server side and then build the list.
If you can/want to use a non async call, don't pass a callback to the Meteor.call() method:
data.map(r => {
const title = Meteor.call('getTitle',r._id);
return <List.Item>title</List.Item>
})
As stated in the docs:
If you do not pass a callback on the server, the method invocation will block until the method is complete. It will eventually return the return value of the method, or it will throw an exception if the method threw an exception.
To fetch and render the data meteor way you have to use the package called react-meteor-data to create createContainer.
For example if you were to use it then you would be able to pass it directly to the component as props.
export default createContainer((props) => {
Meteor.subscribe('questions');
return {
questions: Questions.findOne({_id: props.match.params.id})
};
}, QuestionDo);
I'm trying to implement soft delete on a model in a sails.js project by I override the delete action in the respective controller to just update a boolean attribute called isDeleted.
The problem I'm facing is that, I need to override the find action for the respective controller so that it'll ignore the "deleted" records but I need to keep the rest of the original functionality. To do this I'm simply copying the code of the original find action into the override, but it depends on the actionUtil module, and, when doing the require for that module, no matter how I change the route it never manages to find the module.
So, this is what my controller looks like:
var actionUtil = require('/sails/lib/hooks/blueprints/actionUtil'),
_ = require('lodash');
module.exports = {
find: function(req, res){
// Look up the model
var Model = actionUtil.parseModel(req);
if ( actionUtil.parsePk(req) ) {
return require('./findOne')(req,res);
}
// Lookup for records that match the specified criteria
var query = Model.find()
.where( actionUtil.parseCriteria(req) )
.limit( actionUtil.parseLimit(req) )
.skip( actionUtil.parseSkip(req) )
.sort( actionUtil.parseSort(req) );
// TODO: .populateEach(req.options);
query = actionUtil.populateEach(query, req);
query.exec(function found(err, matchingRecords) {
if (err) return res.serverError(err);
// Only `.watch()` for new instances of the model if
// `autoWatch` is enabled.
if (req._sails.hooks.pubsub && req.isSocket) {
Model.subscribe(req, matchingRecords);
if (req.options.autoWatch)
{ Model.watch(req); }
// Also subscribe to instances of all associated models
_.each(matchingRecords, function (record) {
actionUtil.subscribeDeep(req, record);
});
}
res.ok(matchingRecords);
});
},//End .find
destroy: function(req,res){
console.log("Parametro: " + req.param('id') );
Vendedor.update({ id_vendedor: req.param('id') }, { isDeleted: true })
.exec(function (err, goal)
{
if (err)
return res.status(400).json(err);
return res.json(goal[0]);
});
}
};
But, when starting the server I get an error, saying that the module actionUtil couldn't be found. Does anyone know how I could do this?