Why do we add req.user object before using a method? - javascript

I am understanding some basic CRUD operations on MongoDB, I am having difficulty in understanding why we use req.user before using a method inside the promise below -
Why can't we use return addToProduct() instead of req.user.AddToProduct()
exports.postCart = (req, res, next) => {
const prodId = req.body.productId;
Product.findById(prodId)
.then(product => {
return req.user.addToCart(product);
})
.then(result => {
console.log(result);
})

Because addToCart is a method of the user object and not a variable in scope for the current module.
(And speculating, you are probably adding to the cart of a specific user so you need to tell the method which user's cart to add to.)

Related

How to get the user id of the newly created user in firebase

This project is done using angular, I want to get the user id of the newly created user and set it to a variable so i can use it to identify the particular user using that id.
The Code:
submit()
{
this.Auth.createUserWithEmailAndPassword(this.form.Eemail, this.password).then( res => {
this.user.addnotice(this.form);
this.cancel();
this.succesToast();
}, err =>{
this.failToast();
})
}
The above code creates the user but i want to get the id of the created user so how do i do that.
As you can see in the doc, the createUserWithEmailAndPassword() method returns a Promise that resolves with a UserCredential.
You should therefore do as follows:
this.Auth.createUserWithEmailAndPassword(this.form.Eemail, this.password)
.then( res => { // res is a UserCredential
const userId = res.user.uid;
// ...
} ...

Set on firebase and then set firebase claims

So i working with firebase auth and database in order to set new user to data base, if set successful i want to set claims for that user.
So it means i have a promise within a promise:
function setUser(user){
// no need for the database code before this, but userRef is set properly
return userRef.set(user)
.then(succ => {
return firebase.firebase.auth().setCustomUserClaims(user.key, {admin: true})
.then(() => {
console.log("setting claims")
return true;
});
})
.catch(err => {
return err
})
}
calling function:
app.post("/register_user",jsonParser,async (req, res) => {
var user = req.body.user;
let result = await fireBase.setUser(user);
res.send(result);
})
What happens is that i get the set on the database but claims are not set nor i can i see the log. I know its a js question and not firebase one. I tried many different ways (with await) but non worked.
firebase.firebase does not seem correct. You need to be using the admin object which can be initialised using const admin = require('firebase-admin'); This is not part of the firebase db sdk, but the admin one. You can also use the userRef.uid as that gives you the id of the document of the user, if that is what you want, else use your user.key
return admin.auth().setCustomUserClaims(userRef.uid, {
admin: true
}).then(() => {
//on success
});

How to make list of emits with intervals from Node.js to React using socket.io?

I need to make kind of «movie» (by «movie» I mean changing pages every N seconds) with JS.
I have array of objects coming from node.js and using socket.io I want to emit their content every N seconds to React.
Here is my API endpoint:
router.get("/start/:handle", (req, res) => {
Game
.findOne({ url: req.params.handle })
.then(game => {
let questionList = [];
game.blocks.map(block => {
block.questions.map(question => {
questionList.push(question)
})
})
questionList.map(question => {
return setInterval(
res.status(200).send(question)
, 5000);
})
})
.catch(err => console.log("start game, err =>", err))
})
But it doesn’t work. I have error
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
Probably I need to do it somehow else. But I don’t have any idea how to make it.
You need to wrap your interval logic in annynymous function as suggested by Chris.
Something like below should work.
var sendDataOnInterval = function (req, res) {
// place all existing code
res.send(question);
sendDataOnInterval(recursive, 5000);
};
app.get('/start/:handle', sendDataOnInterval);

How can I insert an object graph by using MikroORM?

I'm trying to create and update multiple entities (models) at once. I did this in objection ORM by using insertGraph API which actually inserts entity if it has no id and updates if it has id.
Is there a similar API in MikroORM?
Currently I'm doing this:
app.put('/articles', async (req, res) => {
const save = req.body.articles.map(async (dto) => {
const article = Object.assign(new Article(), dto)
await req.em.persistAndFlush(article)
})
await Promise.all(save)
res.send({ ok: true })
})
but it generates multiple transactions and I want to everything in single transaction.
The problem here is that when using persistAndFlush method, you immediately persist the entity to database by awaiting the promise. Instead you can call em.persistLater(article) to mark it for persisting. Then call em.flush() afterwards, which will commit all changes to database inside single transaction.
app.put('/articles', async (req, res) => {
req.body.articles.forEach(dto => {
const article = Object.assign(new Article(), dto)
req.em.persistLater(article)
})
await req.em.flush() // save everything to database inside single transaction
res.send({ ok: true })
})
You can make it even simpler by preparing all entities into one array, and persistAndFlush that instead:
app.put('/articles', async (req, res) => {
const articles = req.body.articles.map(dto => Object.assign(new Article(), dto))
await req.em.persistAndFlush(articles) // save everything to database inside single transaction
res.send({ ok: true })
})
Also, instead of using Object.assign(), you can use IEntity.assign() method on the entity, which will also take care of creating references from plain identifiers:
const article = new Article().assign(dto)
More about IEntity.assign() can be found in the docs:
https://b4nan.github.io/mikro-orm/entity-helper/
You could also use EntityManager.create() helper, which will construct the entity for you - the benefit of this is that it will automatically handle constructor parameters, passing them to constructor instead of assigning them directly.
const article = req.em.create(Article, dto)

Sequelize join on where condition returned from first table or return object values in an array derrived from foreach coming up empty

I've been trying to figure out this for a while now so any help would be very much appreciated.
I have one table called Interaction that searches with the client user's id and returns all interactions where they are the target user. Then I want to return the names of those users who initiated the interaction through the User table.
I tried using include to join the User table but I can't get the user's names using the where clause because it is based on a value returned in the first search of the Interaction table and don't know if I can search on a value that isn't the primary key or how?
The closest I've gotten is to use foreach and add the users to an array but I can't get the array to return in my response, because outside of the loop it is empty. I've tried suggestions I've found but can't figure out how to return the array outside of the foreach, if this is the best option. I am sure it is something really stupid on my behalf. TIA.
This is my attempt at include function:
getInvited: (req, res, next) => {
var user = {}
user = req.user;
let usrId = user[0]['facebookUserId'];
var userObjArray = [];
Interaction.findAll({
where: {
targetUserId: usrId,
status: 'invited',
},
include: [{
model: User,
attributes: [
'firstName'
],
where: {
facebookUserId: IwantToJoinOnInteraction.userId // replace with working code?
}]
}).then(function (users) {
res.send(users);
}).catch(next);
}
Or my attempt at foreach:
getInvited: (req, res, next) => {
var user = {}
user = req.user;
let usrId = user[0]['facebookUserId'];
var userObjArray = [];
Interaction.findAll({
where: {
targetUserId: usrId,
status: 'invited',
}
}).then(function (interactions) {
interactions.forEach((interaction) => {
User.findOne({
where: {
facebookUserId: interaction.userId // this is the where clause I don't know how to add in my first attempt with include
},
attributes: ['firstName', 'facebookUserId']
}).then(function (user) {
userObjArray.push(user['dataValues']);
console.log(userObjArray); // on the last loop it contains everything I need
})
})
res.status(200).send(userObjArray); // empty
}).catch(next);
},
You have to wait for all promises before sending the response. Your code runs async. With the forEach you are calling User.findOne async but you don't wait for all User.findOne to finish. A convenient way to make this work is Promise.all. You can pass an array of promises and the returned promise resolves to an array of all the resolved promises.
Promise.all(interactions.map(interaction => User.findOne(...)))
.then(users => {
res.status(200).send(users.map(user => user.dataValues))
})
You could write this much more easy to read woth async/await
getInvited: async (req, res, next) => {
...
const interactions = await Interaction.findAll(...)
const users = await Promise.all(interactions.map(interaction => User.findOne(...)))
res.status(200).send(users.map(user => user.dataValues))
}

Categories

Resources