function breaks if id doesn't come [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Error : Cannot read property id of undefined
How can I re-write this function so that it doesn't break foundApplication[0].id, if id doesn't come or foundApplication array comes empty?
I cannot alter getDocument function
async function getApplicationByCbaxUid(cbaxUid) {
let foundApplication = await dbService.application
.find({ userID: cbaxUid });
return getDocument(foundApplication[0].id);
}

You can validate if the array and the id exist. if you're using latest version of ES, you can use optional chaining (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining):
async function getApplicationByCbaxUid(cbaxUid) {
let foundApplication = await dbService.application
.find({ userID: cbaxUid });
return getDocument(foundApplication?.[0]?.id);
}
if you don't
async function getApplicationByCbaxUid(cbaxUid) {
let foundApplication = await dbService.application
.find({ userID: cbaxUid });
return foundApplication.length && foundApplication[0].id && getDocument(foundApplication[0].id);
}
This is doing all the normal validations which the latest operator (optional chaining is doing)

You can just add a check if the array is empty
return foundApplication.length ? getDocument(foundApplication[0].id) : null;

set an if statement and add whatever you need to do if it fails to the else block
async function getApplicationByCbaxUid(cbaxUid) {
let foundApplication = await dbService.application
.find({ userID: cbaxUid });
if(foundApplication.length){
return getDocument(foundApplication[0].id)
}else{
...do what you want here
}
}

Related

I want to call a single document from my Angular Firestore [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I'm facing a problem in my project, I'm using Nested Children Routing to show data in my project, I want the data of this specific item to be shown once I click the button on it, I did the routing right, it's just I can't get the proper function for the items.
Here's my service
PostsService.service.ts
getPostById(id: string){
let docId = this.afs.collection('posts').doc(id).get()
.subscribe( doc => {
if(doc.exists){
console.log('Document Id => ', doc.id)
console.log('Document data => ', doc.data())
}else {
console.log('Document not found')
}
});
return docId;
}
and Here's my TS function for the single item
.component.ts
posts: Posts[] = [];
post!:any;
constructor(
private PostsService: PostsService,
private route: ActivatedRoute
) {}
ngOnInit(): void {
let id = this.route.snapshot.params['id']
this.PostsService.getPostById(id);
}
You're attempting the get the whole collection with getPostById() and then trying to find a single document from the results. Getting the whole colletion means you will read n amount of times for n amount of documents - which is wasteful and slow.
If you ask something with getPostById() then you should do something with the return as well. Right now your asking, but not doing anything with the return.
How about we just get the single document? It will return an Observable, so we can keep monitoring the document, or just use the face value as it is.
getPostById(id: string) {
const itemDoc = this.afs.doc<any>('posts/' + id);
return itemDoc.valueChanges();
}
And in your component, don't forget to unsubscribe from the Observable.
ngOnInit() {
let id = this.route.snapshot.params['id'];
this.PostsService.getPostById(id).subscribe(post => {
console.log(post);
})
}

TypeError: Cannot read properties of undefined (reading 'equal') [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I have created 2 TESTS --
In 2nd TEST, I have enclosed owner, addr1, addr2 in [] as per the Official Hardhat Documentation, like this const [owner,addr1,addr2] = await ethers.getSigners();,
But the problem is when I use [] bracket, it shows me the error TypeError: Cannot read properties of undefined (reading 'equal') and the test also failed,
Here is the Code --->
const { expect } = require('chai');
// const { ethers } = require('hardhat');
describe('Token contract', function () {
//1st TEST
it('Deployment should assign the total supply of the tokens to the owner', async function () {
const [owner] = await ethers.getSigners();
const Token = await ethers.getContractFactory('Token');
const hardhatToken = await Token.deploy();
const ownerBalance = await hardhatToken.balanceOf(owner.address);
expect(await hardhatToken.totalSupply()).to.equal(ownerBalance);
});
//2nd TEST
it('Should Transfer Tokens between accounts', async function () {
const [owner,addr1,addr2] = await ethers.getSigners();
const Token = await ethers.getContractFactory('Token');
const hardhatToken = await Token.deploy();
//Transfer 10 tokens from Owner to addr1
await hardhatToken.transfer(addr1.address,10);
expect(await hardhatToken.balanceOf(addr1.address).to.equal(10));
//Transfer 5 tokens from addr1 to addr2
await hardhatToken.connect(addr1).transfer(addr2.address,5);
expect(await hardhatToken.balanceOf(addr2.address).to.equal(5))
});
});
But if U see in the 1st TEST, I haven't used [], for owner, so the test passed.
Below is the Official Hardhat documentation if U want to check the code --->
https://hardhat.org/tutorial/testing-contracts.html
Please help me to solve this Problem
Thanks
enter image description here
You didn't close the parenthesis around the expect calls in the second test correctly. You're accessing .to on the number returned by .balanceOf.
Replace with:
expect(await hardhatToken.balanceOf(addr1.address)).to.equal(10);
// ...
expect(await hardhatToken.balanceOf(addr2.address)).to.equal(5);

How can I run a function at a particular point in the future? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a schedule option in my API what I did with Expressjs and NodeJS. Our backend calls this API with two parameters (userID & timestamp). The goal is to delete user informations (folders, documents, etc) at the specified time (..or few minutes later). The timestamp can be 5 minutes to 2 days from now.
When it happened the job is done and the API is waiting for an other call. The API can receive 1000 calls per day, so the performance is very important. What's the best way to run the function in the future?
async function scheduledAction(userId, timestamp) {
var actionInFuture = await checkDate(timestamp);
if(actionInFuture) {
console.log('Action triggered');
}
}
async function checkDate(timestamp) {
await new Promise(resolve => {
setTimeout(resolve, 1000)
});
// timestamp = 1627311533000
if(Date.now() >= timestamp) {
return true;
} else {
return checkDate(timestamp);
}
}
app.get('/action', (req, res) => {
scheduledAction(req.query.userId, req.query.timestamp);
}
scheduledAction(req.query.userId, req.query.timestamp);
You can use Node Schedule package, https://www.npmjs.com/package/node-schedule
For example:
var schedule = require('node-schedule');
const date = new Date(1627309531*1000);
var j = schedule.scheduleJob(date, function(){
console.log('Action triggered');
});

null value for firestore [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So basically, I can't display the collection on my html. I get a null value error for gamesList. But when I log it to the console, I can see the contents just fine, no problems there.
// get data
db.collection('games').get().then(snapshot => {
setupGames(snapshot.docs);
});
// DOM elements
const gamesList = document.querySelector('.games');
// setup games
const setupGames = (data) => {
let html = '';
data.forEach(doc => {
const game = doc.data();
const li = `
<li>
<div class="collapsible-header grey lighten-4">${game.title}</div>
<div class="collapsible-body white">${game.content}</div>
`;
html += li
});
gamesList.innerHTML = html;
}
So here something goes wrong and for the life of me I can't figure it out.
but when I use this the data does display correctly in the console, title and content:
// setup guides
const setupGames = (data) => {
let html = '';
data.forEach(doc => {
const game = doc.data();
console.log(game);
});
}
I think, when you use get() function on a collection, it already returns you the document list, so you don't need to call snapshot.docs
There's an example here:
https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection
If you want to use real time data with snapshots, try it this way:
db.collection('games').onSnapshot(snapshot => {
setupGames(snapshot.docs);
});

`await` command causes variable to lose scope [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am using await to pull data from the database. There's a variable secuity_ok that is true on one line, and then false on the next. Can anyone see what the issue is?
Note – if I comment out the line: let session = ..., then it all works.
Controller.prototype.changePassword = async function(request, response) {
let model = request.body;
var secuity_ok = false;
var user = await userService.getUserByEmail(model.email);
if (user && this.isAuthenticatedUser(request, user.id)) {
secuity_ok = true;
} else {
let session = await authenticationService.createSessionByEmailPassword(model.email, model.oldpassword),
secuity_ok = !!session;
console.log( 'A', secuity_ok ); // true
}
console.log( 'B', secuity_ok ); // false
if (!secuity_ok) {
this.sendForbiddenError(response, {
error: 'Cannot change password: Application safeguards are preventing this action'
});
return new Promise(() => {});
}
...
}
Output:
A true
B false
Output should be:
A true
B true
You have a comma at the end of the first line here:
let session = await authenticationService.createSessionByEmailPassword(model.email, model.oldpassword), // <--- Note comma here
secuity_ok = !!session;
That makes secuity_ok part of the let statement, so it's an extra, inner declaration of secuity_ok that only has scope inside the parentheses of the else clause.

Categories