How can I know if the save method worked in mongo - reactjs

im new using mongo and when i save a new object in my db i use the save method, but when using it and then printing the result, if it was successful i get the object, not someting that i can use to handle any error in the front end
router.post("/post_recipe", async (request, response) => {
const {title, content, author} = request.body;
const new_post = new Posts({title, content, author});
new_post.save(sdfs).then((response) => {
response.json(response);
}).catch(error => response.json(error));
});
doing this on purpose i get the error in the console but its not sending it to the front end to handle it and tell the user that there was a problem
Posts its a scheme, dont know if it has something to do with

Problem is you are using same variable name for your router response and save method response.
Solution
router.post("/post_recipe", async (req, res) => {
const {title, content, author} = req.body;
const new_post = new Posts({title, content, author});
// Getting rid of .then and .catch method
new_post.save((err, savedPost) => {
// Your custom error message
if (err) return res.status(400).json('post not saved due to some problem! Please try again');
// Post that you just saved in db
return res.json(savedPost);
});
This happen due to scope of variable.
For more detail check this article from w3schools.com

Related

Can URL API endpoint self-correct?

I am using fetch API inside a React application to retrieve and display some quiz questions.
This is my url endpoint: https://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple
I have noticed that:
-when I misspell part of the URL before "?" then the response doesn't get back.
example:https://opentdb.com/api.ph?amount=${amount}&difficulty=${difficulty}& (missing "p" of php)
-when I misspell part of the url after "?" then, sometimes I get an empty array back, sometimes I get the data back. How can I get data back with a wrong URL?
example: https://opentdb.com/api.php?amoun=${amount}&difficulty=${difficulty}&type=multiple (missing "t" in amount)
I haven't deployed the application yet, I am using vsc and run npm start to develop the application.
Is it possible that the URL auto-corrects? or maybe it gets cached?
my code:
export const fetchQuizQuestions = async (
amount: number,
difficulty: Difficulty
) => {
const endPoint = `https://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple`;
try {
const response = await fetch(endPoint);
console.log(response);
const data = await response.json();
console.log(data);
if (data.results.length === 0) {
throw new Error("The part after ? contains some mistake");
}
//below I create the new property "all_answers" and make sure the answers order is never the same
return data.results.map((question: Question) => ({
...question,
all_answers: shuffleArray([
...question.incorrect_answers,
question.correct_answer,
]),
}));
} catch (error: any) {
console.log(error.name);
console.log(error.message);
}
};
Before the ? It's the url. So if you make a mistake there, basically it's like sending a letter to a different adress, so you will not get any answers.
After the ? it's the query string. So you're asking for a result, with some parameters (your query)
So if you're saying like "ok, send me back answers with amount = XXX" but you misspell amount, it's just like "ok send me back answers" because you're not asking for amount anymore (but amoun which is nothing for the endpoint)

How to use Axios.post() in a post request containing a json object request-body and a multipart form data (MP4)

Hi I Was wondering how I can send a a single axios post request containing a json object as the request body and also multipart form data (Mp4 file).
In my example I want to send 'details' and 'file'. I have tried sending details and file as 2nd and 3rd arguments to the axios.post() method but from what I can tell axios.post only accepts 2 args.
I have also tried appending the details and then the file, to the form data, but this does not work either.
If I split these into 2 seperate post calls, it works fine, but my application requires these to happen together.
I am getting the following error in my spring console:
[org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundaryqKyZ0R2SyFeDNCVp;charset=UTF-8' not supported]
Here is the error in my web dev tools console:
xhr.js:210 POST http://localhost:9191/api/123/file/upload 415
Id really appreciate any suggestions
const FileUpload = () => {
const [file, setFile]= useState(null)
const[details, setDetails] = useState({consent:false,
idConfirmed:false,
label:"",
roundId:""})
const changeHandler=(e)=>{
setFile(e.target.files[0]);
setDetails(prevDetails=>({
...prevDetails,
consent:true,
idConfirmed:true,
label:"test_Label"
}));
};
const handleSubmission=(e)=>{
e.preventDefault();
const data = new FormData();
data.append("file", file)
data.append("file", details)
console.log("Data: ", data)
axios.post(`${process.env.REACT_APP_URL_NEW_ROUND_VID}/123/file/upload`, data,
{
headers:{
"Content-Type":"multipart/form-data"
}
})
.then(res=>{
console.log("Data: ",res.data)
console.log("success")
})
.catch((e)=>{
console.log("Error", e)
})
//})
};
Here is my rest end point in Springboot:
#PostMapping(
path = "{patientId}/file/upload",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public void addWardRound(#PathVariable("patientId") String patientId,
#RequestParam("file") MultipartFile file,
#RequestBody WardRequest wardRequest){
WardRoundService.isFileEmpty(file);
WardRound round = service.saveRound(wardRequest);
String roundId = round.getRoundId();
service.uploadVid(patientId, roundId, file);
}
you can stringify and send the JSON data. but by using this method you need to parse it in the server!. it could be difficult
The best method is splitting it into 2 APIs
you can merge both API requests in UI by merging both APIs using promise.All
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
const promise1 = axios.get(URL1);
const promise2 = axios.post(URL2, data);
Promise.all([promise1, promise2]).then(function(values) {
console.log(values);
});
or else if you need to use the result of first API
then call the second API inside the response of first API itself

How do you delete certain messages from a specific username not ID

twitchClient.on('timeout', async (channel, username, user, reason, duration) => {
discordClient.on('message', async (message, messages) => {
async function deleteMessage() {
await discordClient.channels.cache.get("901568598538063932")
.messages.fetch({limit: null})
.then(message.delete(messages.first(user["display-name"]).author.name))
}
await deleteMessage()
})
async function sendMessage() {
const request = new XMLHttpRequest();
request.open("POST", "API url");
request.setRequestHeader('Content-type', 'application/json');
const users = {
username: "User Timed Out",
avatar_url: 'https://i.imgur.com/GUrbNsB.jpg',
content: `**${username} has been timed out for ${duration} seconds.**`
}
request.send(JSON.stringify(users));
}
await sendMessage()
});
I have this code for twitch chat to sync in discord and I want to do on event timeout on twitch
I want it to delete the messages of a certain name on the channel is it possible without ID
I am lost on how to do it like I can delete the last message but not from a specific user and I
only have one webhook so the id of all usernames will be the same
TypeError: Cannot read properties of undefined (reading 'first')
Note: This code is for Discord.js v13.3.0
As stated by the error, you're trying to access an undefined variable called messages. This is because you did not define it in the then() arguments, you instantly went to a callback.
then() is a function that allows for you to provide parameters to add. You can simply put the collection of messages as one variable called messages and pass it to the callback accordingly.
// DON'T do this
messages.fetch({limit: null})
.then(message.delete(messages.first(user["display-name"]).author.name))
// DO this
messages.fetch({limit: null})
.then((messages) => message.delete(messages.first(user["display-name"]).author.name))

Invalid character found in method name error when fetching an api using React

I have implemented a table using ag-grid react. I fetch data from an api to fill in that table.
const getDataForTable = async () => {
try {
//apis to fetch the data
setGridData(apiData);
}
catch (err) {
console.error(err);
}
}
useEffect(() => {
getDataForTable();
}, []);
Now, I have also created an onClick method for deleting selected rows of the table. I am removing the rows from api as well. Once the rows are deleted, I just want to refresh the grid with updated data. Currently it only works if I explicitly reload the page.
const onClickRemoveRowsByIds = async () => {
selectedRows.forEach(d => {
listOfIds.push(d.Id);
});
if (window.confirm("Are you sure ?")) {
await listOfIds.map((ele) => removeActiveList(ele));
getDataForTable()
}
}
But when I make a call to getDataForTable function, I get bad request error for the apis. On looking at the reponse body of the api : I get Invalid character found in method name. HTTP method names must be tokens. The authToken and rest of the information remains same but still fetch is not working again. Am I missing some step, or doing it completely wrong? The delete works fine, just the refresh is not happening.

How to send a message based on event Google PubSub?

I need some help with PubSub...
I need to send a message to a topic every time someone accept cookies in my website. This message should contain the encodedURL that contains the services accepted.
I have this script:
const topicName = "myTopic";
const data = JSON.stringify({
encodeConsentURL:""
});
// Imports the Google Cloud client library
const { PubSub } = require("#google-cloud/pubsub");
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function publishMessageWithCustomAttributes() {
// Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
const dataBuffer = Buffer.from(data);
// Add two custom attributes, origin and username, to the message
const customAttributes = {};
const messageId = await pubSubClient
.topic(topicName)
.publish(dataBuffer, customAttributes);
console.log(`Message ${messageId} published.`);
console.log(customAttributes);
}
publishMessageWithCustomAttributes().catch(console.error);
This code works, it sends the message, what I'm finding very hard to do is how to set everything right for running this code in my cookie script. In my cookie script I have a function that writes the cookie, in the same function I would like to send the message, is this possible? Thanks in advance!
It is a bit late, but I don't get it, if you already have a working cookie script and a working publish script, isn't it just about putting them together?
If you still need help I'll be happy to help you
Something like
const runEverything = async () => {
try {
await checkCookiesThing()
await publishMessage()
} catch (e) {
console.error(e)
}
}

Resources