How to delete object from firebase database - javascript

I'm trying to figure out how to delete information submitted to the firebase database.
I am trying to delete information under the requests. Example
Here are my actions used to fetch the data:
export default {
async contactArtist(context, payload) {
const newRequest = {
userEmail: payload.email,
message: payload.message
};
const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${payload.artistId}.json`, {
method: 'POST',
body: JSON.stringify(newRequest)
});
const responseData = await response.json();
if (!response.ok) {
const error = new Error(responseData.message || 'Failed to send request.');
throw error;
}
newRequest.id = responseData.name;
newRequest.artistId = payload.artistId;
context.commit('addRequest', newRequest);
},
async fetchRequests(context) {
const artistId = context.rootGetters.userId;
const token = context.rootGetters.token;
const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${artistId}.json?auth=` + token);
const responseData = await response.json();
if (!response.ok) {
const error = new Error(responseData.message || 'Failed to fetch requests.');
throw error;
}
const requests = [];
for (const key in responseData) {
const request = {
id: key,
artistId: artistId,
userEmail: responseData[key].userEmail,
message: responseData[key].message
};
requests.push(request);
}
context.commit('setRequests', requests);
},
};
I'm trying to set up a button that will delete the selected request object.

Your code is sending a POST request, which tells Firebase to generate a unique key. From the documentation on saving data:
POST: Add to a list of data in our Firebase database. Every time we send a POST request, the Firebase client generates a unique key, like fireblog/users/<unique-id>/<data>
The delete a node, send the DELETE verb/method to that path:
const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${payload.artistId}.json`, {
method: 'DELETE'
});

Related

TypeError when instantiaing SpotifyWebApi object

im trying to write a bot to do some playlist handling in spotify. I'm using the spotify-web-api-node package : https://github.com/thelinmichael/spotify-web-api-node
I installed the package and whenever I try to create an object with the following code:
const SpotifyWebApi = require('spotify-web-api-node');
const spotifyApp = SpotifyWebApi();
I keep getting this error:
this._credentials = credentials || {};
^
TypeError: Cannot set properties of undefined (setting '_credentials')
this is the contructor signature in the src file:
constructor(credentials?: Credentials);
Any thoughts ?
You need an access-token for access API call.
In the documentation,
If you've got an access token and want to use it for all calls, simply use the API object's set method. Handling credentials is described in detail in the Authorization section.
spotifyApi.setAccessToken('<your_access_token>');
Demo code: get access token then get Elvis' albums
const SpotifyWebApi = require('spotify-web-api-node');
const axios = require('axios')
const getToken = async () => {
try {
const response = await axios.post(
url = 'https://accounts.spotify.com/api/token',
data = '',
config = {
params: {
'grant_type': 'client_credentials'
},
auth: {
username: '<your client id>',
password: '<your client secret>'
}
}
);
return Promise.resolve(response.data.access_token);
} catch (error) {
return Promise.reject(error);
}
}
getToken()
.then(token => {
const spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken(token);
// Passing a callback - get Elvis' albums in range [0...1]
spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', { limit: 2, offset: 0 }).then(
(data) => {
console.log('Artist albums', data.body);
},
(err) => {
console.error(err);
}
);
})
.catch(error => {
console.log(error.message);
});
Result

Getting following error while fetching data in react Uncaught (in promise) TypeError: Failed to fetch

I have create backend using express and mongodb database. I am trying to fetch data in react but getting an error while fetching the data as show. Please can anyone tell what the solution of above error is and how can i fetch data from the backend
const Register = () => {
const [values, setValues] = useState({
name: "",
age: "",
country: "",
email: "",
});
const setData = (e) => {
console.log(e.target.value);
const { name, value } = e.target;
setValues((val) => {
return {
...val,
[name]: value,
};
});
};
const addData = async (e) => {
e.preventDefault();
const { name, age, country, email } = values;
const res = await fetch("/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name,
age,
country,
email,
}),
});
const data = await res.json();
console.log(data);
if (res.status === 404 || !data) {
console.log("Error");
} else {
console.log("Data added successfully");
}
};
Here below is the backend code where the post function is performed.
router.post("/register", async (req, res) => {
const { name, age, country, email } = req.body;
if (!name || !age || !country || !email) {
res.status(404).send("Some data is missing");
}
try {
const preuser = await Crud.findOne({ email: email });
console.log(preuser);
if (preuser) {
res.status(404).send("The user already exists");
} else {
let addUser = new Crud({
name,
age,
country,
email,
});
addUser = await addUser.save();
res.status(201).json(addUser);
console.log(addUser);
}
} catch (error) {
res.status(404).send(error);
}
});
await fetch leads to an exception when the HTTP status is ≥ 400. You must add a try-catch block to handle such exceptions:
try {
const res = await fetch("/register", {...});
} catch(exception) {
// Handle the exception
}
Also, HTTP status 404 should be used when a resource is not found. You use it when a user already exists (where status 400 would be more appropriate) or in case of a database error (when 500 would be more appropriate).

Need help sending DELETE request with firebase Rest API with Vuex

I'm trying to delete some information from firebase and having some trouble getting it to work.
What i'm trying to do is have the deleteRequest button delete the data pulled from the fetch link.
This is the button and method
<div class="actions">
<base-button #click="deleteRequest">Delete</base-button>
</div>
async deleteRequest() {
await this.$store.dispatch('requests/deleteRequest', {
email: this.email,
message: this.message,
artistId: this.$route.params.id,
});
async deleteRequest(context, payload) {
const removeRequest = {
userEmail: payload.email,
message: payload.message
};
const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${payload.artistId}.json`, {
method: 'DELETE',
body: JSON.stringify(removeRequest)
});
const responseData = response.json();
if (!response.ok) {
const error = new Error(responseData.message || 'Failed to send request.');
throw error;
}
context.commit('deleteRequests', removeRequest);
},

Trying to dynamically set .find() parameters from client input - mongodb:Atlas

I am trying to use data from the client, which they would type into an input box. The idea is to use this for finding in my database to pull the data with the same username. on my Mongo DB:Atlas collection.
So its to use it like this to get the names from the database, .find({"username": request.body})
However, I keep getting the error "CastError: Cast to string failed for value "{ username: '' }" (type Object) at path "username" for model "Db1" on my terminal.
But when I try to hard code it onto the .find({"username": "name"), it works fine. Does anyone have any ideas?
**Javascript app**
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
};
```
-----------------------------------------------------
**Node Server**
app.post('/database', (request,response) => {
const info = request.body;
postModel.find({"username": info}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});
----------------------------------------------
***client side DB***
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
Actually, you're passing the object {username : "value"} to the find method. You need to pass the string.
app.post('/database', (request,response) => {
const info = request.body; // object {username : "value"}
const username = info.username; // the string to search by username
postModel.find({"username": username}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});

How to optimize an API fetch to be less redundant

I'm building a React App which consumes an API and what I build for now is 2 functions which both GET the same URL but changing the second part of the API Endpoint like URL/?search or URL/?i=123 but what I would like to achieve is to have less redundant code so I was wondering to make one function which just takes the same URL and change the second part of the URL based on the call.
By the way, this approach gives me problems.
The code I did originally was this:
import {API_MOVIE_URL, API_KEY} from "./ApisConst";
export const getMoviesBySearch = async search => {
try {
const url = `${API_MOVIE_URL}?apikey=${API_KEY}&${search}`;
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};
export const getMoviesInfo = async movieID => {
try {
const url = `${API_MOVIE_URL}?apikey=${API_KEY}&i=${movieID}&plot`;
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};
And the change I tried is:
const fetchAPI = async ({type, query}) => {
const queryParams = {
byString: `&${query}`,
byMovieId: `&i=${query}&plot`,
};
const endpoint = `${API_MOVIE_URL}?apikey=${API_KEY}${queryParams[type]}`;
console.log("fetching", endpoint);
return fetch(endpoint)
.then(res => res)
.catch(() => ({
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
}));
};
export const getMoviesBySearch = async search =>
await fetchAPI({type: "byString", query: search});
export const getMoviesInfo = async movieID =>
await fetchAPI({type: "byMovieId", query: movieID});
But this second approach gives me an error in the console which is:
Response {type: "cors", url: "https://www.omdbapi.com/?apikey=API_KEY&s=harry+potter&type=movie", redirected: true, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: true
status: 200
statusText: ""
type: "cors"
url: "https://www.omdbapi.com/?apikey=API_KEY&s=harry+potter&type=movie"
The first approach works perfectly but the second one none and trying to get a solution but cannot really think what to do to get this code better optimized.
Since the queries are identical except for the url, create a query generator (createMoviesQuery) that accepts a function that generates the url (urlGenerator), and returns a query function
Example (not tested):
import {API_MOVIE_URL, API_KEY} from "./ApisConst";
const createMoviesQuery = urlGenerator => async (...params) => {
try {
const url = urlGenerator(...params);
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};
export const getMoviesBySearch = createMoviesQuery((search) => `${API_MOVIE_URL}?apikey=${API_KEY}&${search}`);
export const getMoviesInfo = createMoviesQuery((movieID) => `${API_MOVIE_URL}?apikey=${API_KEY}&i=${movieID}&plot`);

Categories

Resources