Fetching records corresponding to a user, when queried from admin role/user which has access to all records - parse-server

I need to fetch a particular class (say Class A) records corresponding to each user in my parse server, when queried with admin role which have access to all the records in that particular class (Class A).
How can I do that?
Quick help would be greatly appreciated. :-)

I'm assuming that you want these records on the client, but the client doesn't have "permission" to get all class a records?
If I've got the problem right, then here's a solution. Create a cloud code function that can use the master key to query objects of class a.
// this is the cloud function that you can call with
// whichever client SDK you are using....
const fetchClassA = function (request, response) {
const result = [];
const userId = request.params.fetchForUser;
// the test here should be against role, just an example....
if (request.user.get('username') !== 'admin') {
response.error('you are not authorized.');
return;
}
if (!userId) {
response.error('no user supplied');
return;
}
const user = new Parse.User();
user.id = userId;
new Parse.Query('ClassA')
.equalTo('user', user)
// depending on the use case, you may want to use
// find here instead?
.each((object) => {
result.push(object);
}, { useMasterKey: true })
.then(() => response.success(result))
.catch(response.error);
}
// the rest of this is just a unit test to "lightly" test
// our cloud function....
describe('fetch record with a cloud function', () => {
const userA = new Parse.User();
const userB = new Parse.User();
beforeEach((done) => {
userA.setUsername('userA');
userA.setPassword('abc');
userB.setUsername('userB');
userB.setPassword('def');
Parse.Object.saveAll([userA, userB])
.then(() => Parse.Object.saveAll([
new Parse.Object('ClassA').set('user', userA),
new Parse.Object('ClassA').set('user', userA),
new Parse.Object('ClassA').set('user', userA),
new Parse.Object('ClassA').set('user', userB),
new Parse.Object('ClassA').set('user', userB),
new Parse.Object('ClassA').set('user', userB),
]))
.then(() => Parse.User.signUp('admin', 'foo'))
.then(done)
.catch(done.fail);
});
it('should fetch class a', (done) => {
Parse.Cloud.define('fetchClassA', fetchClassA);
Parse.Cloud.run('fetchClassA', { foo: 'bar', fetchForUser: userA.id })
.then(result => expect(result.length).toBe(3))
.then(done)
.catch(done.fail);
});
});

Related

Mikro-Orm - ManyToMany Relationship how can I delete reference in PivotTable?

I'm using NestJS with mikro-Orm and have a weird behaviour on all of my manyToMany relations.
#ObjectType()
#Entity()
export class Realty {
#Field(() => ID)
#PrimaryKey({ columnType: "uuid" })
id: string = v4();
#Field(() => [Contact])
#ManyToMany(() => Contact, (contact) => contact.realties)
contacts: Collection<Contact>;
}
#ObjectType()
#Entity()
export class Contact {
#Field(() => ID)
#PrimaryKey({ columnType: "uuid" })
id: string = v4();
#Field(() => [Realty])
#ManyToMany(() => Realty, (realty) => realty.contacts, { owner: true })
realties: Collection<Realty>;
}
When I want to delete a realtyReference from a contact, that works fine and the row from the Contact_Realty PivotTable gets removed. But when I try to delete a contactReference from a realty, nothing happens. Does that only work on the owning side?
ContactsService (works):
async update(updateContactInput: UpdateContactInput) {
const { id, realtyIds } = updateContactInput;
const contact = await this.findOneOrFail(id);
const updated = this.contactsRepository.assign(contact, {
realties: await this.realtiesService.find(realtyIds),
});
await this.contactsRepository.persistAndFlush(updated);
return updated;
}
RealtiesService (returns correct updated entity but doesnt remove row in PivotTable):
async update(updateRealtyGeneralInput: UpdateRealtyGeneralInput) {
const { id, contactIds } = updateRealtyGeneralInput;
const realty = await this.realtiesService.findOneOrFail(id);
const updated = this.realtiesRepository.assign(realty, {
contacts: await this.contactsService.find(contactIds),
});
await this.realtiesRepository.persistAndFlush(updated);
return updated;
}
Both return the correct updated entity but only the ContactsService actually removes the row in the pivotTable.
Would really appreciate some help, thanks alot!
I want to remove one or more contacts from a realty and cannot get it to work. Am I doing something wrong?
You always need to have the owning side of your M:N collection initialized/populated, which you apparently don't in the second example. In your case it is Contact.realties, so if you want to manipulate this collection from the inverse side, all the entities you add/remove from the inverse need to have the owning side populated. Only owning side is what is taken into account when computing changesets. I will need to revisit this a bit, we might be able to improve on this thanks to the recent changes like the reference updates added in v5.5.
Also, there is some misunderstanding in your code. assign mutates the parameter, it does not return "modified entity", it mutates the one you pass in the first argument. If that entity is already managed (as in your case), there is no point in re-persisting it again, just flush.
async update(updateRealtyGeneralInput: UpdateRealtyGeneralInput) {
const { id, contactIds } = updateRealtyGeneralInput;
const realty = await this.em.findOneOrFail(Realty, id);
this.realtiesRepository.assign(realty, {
contacts: await this.em.find(Contact, contactIds, { populate: ['realties'] }),
});
await this.em.flush(updated);
return realty;
}

Shopify Storage Redis Issue with Node React App

I have added session storage in serve.js as follows :-
import SessionHandler from "./SessionHandler";
const sessionStorage = new SessionHandler();
Shopify.Context.initialize({
API_KEY: process.env.SHOPIFY_API_KEY,
API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
SCOPES: process.env.SCOPES.split(","),
HOST_NAME: process.env.HOST.replace(/https:\/\//, ""),
API_VERSION: ApiVersion.October21,
IS_EMBEDDED_APP: false,
// This should be replaced with your preferred storage strategy
//SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
SESSION_STORAGE: new Shopify.Session.CustomSessionStorage(
sessionStorage.storeCallback,
sessionStorage.loadCallback,
sessionStorage.deleteCallback
),
});
My router get function is
router.get("(.*)", async (ctx) => {
const shop = ctx.query.shop;
let documentQuery = { shop: shop };
let data = await SessionStorage.findOne(documentQuery); //this finds the store in the session table
if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
if (data == null) {
ctx.redirect(`/auth?shop=${shop}`);
} else {
await handleRequest(ctx);
}
} else {
await handleRequest(ctx);
}
});
and than in the SessionHandler file added code as attached in file ,
but when I run install the app it goes to the storeCallback , loadcallback and deletecallback function multiple times
StoreCallback Function Code
Load and delete callback function code
sorry I have edited my answer as I think its incorrect . all I can say for now is to look at this example:https://github.com/Shopify/shopify-api-node/blob/main/docs/usage/customsessions.md
if you havent already..

how to create a Custom User in strapi.js

I am working on a strapi-app and I have 3 content-types:
- User (the one that comes with strapi)
- profile
- Employee (has one User, has one Profile)
this is my code:
async create(data, { files } = {}) {
const profileObj = data.profile
const employeeObj = {
salary_type: data.salarytype,
salary: data.salary
}
const userObj = data.user
profileObj.address = data.address
const user = await strapi.query('user').create(userObj);
const profile = await strapi.query('profile').create(profileObj);
const employee = await strapi.query('employee').create(employeeObj);
employee.user = user
employee.profile = profile
if (files) {
// automatically uploads the files based on the entry and the model
await strapi.entityService.uploadFiles(employee, files, {
model: 'profile',
});
return this.findOne({ id: employee.id });
}
return employee;
},
it's working but I created another user Controller/service and model because when I tried without creating a new user C/S/M it gave me an error.
Wny suggestions please?
Refer
The create user query should be like this.
const user = await strapi.query('user', 'users-permissions').create(userObj);
This way you need not create a new User API and use the one that comes with Strapi.

Why can I add, but not remove an element from a set

I’m trying to update the notification count in my database.
I’m doing this by creating a set, which I add a UID to when I want to add to the notification count and removes a UID from the set when I want to subtract from the notification count.
I then take the size of the set and update the notification count.
the updateNotificationCount function is triggered by a lower order component.
However I can only get the database to update when isNewMatch is true. Why won’t it update the database when isNewMatch is false?
state = {notificationSet: new Set()}
updateNotificationCount = (uid, isNewMatch) => {
if (isNewMatch) {
this.setState(({ notificationSet }) => ({
notificationSet: new Set(notificationSet).add(uid)
}));
}
else {
this.setState(({ notificationSet }) => {
const newNotificationSet = new Set(notificationSet);
newNotificationSet.delete(uid);
return {
notificationSet: newNotificationSet
};
});
};
}
You don't need to do new Set() every time because you already initialize the state with new Set() so now you just do as follow:
state = {notificationSet: new Set()}
updateNotificationCount = (uid, isNewMatch) => {
let notificationSet;
if (isNewMatch) {
notificationSet=this.state.notificationSet;
notificationSet.add(uid);
this.setState({
notificationSet: notificationSet
});
} else {
notificationSet=this.state.notificationSet;
notificationSet.delete(uid);
this.setState({
notificationSet : notificationSet
});
};
}

How to get a collection from firestore using data from another collection in react-Native.....What Am i Doing Wrong?

I have tried searching everywhere, from stackoverflow to GitHub but i can get a solution. I am trying to get list of users by using their userid that I get from a collection of businesses. What Am i doing wrong?
componentWillMount() {
//Loading all the business collections.
firebase.firestore().collection("business").onSnapshot((snapshot) => {
var bizs = [];
snapshot.forEach((bdt) => {
var userdt = [];
//get document id of a certain user in the business collections
firebase.firestore().collection('users').where("userid", "==", bdt.data().userid).get()
.then((snap) => {
snap.forEach(dc => {
//loading details of the user from a specific ID
firebase.firestore().collection("users").doc(dc.id).onSnapshot((udt) => {
userdt.push({
name: udt.data().fullname,
photourl: udt.data().photoURL,
location: bdt.data().location,
openhrs: bdt.data().openHrs,
likes: '20',
reviews: '3002',
call: bdt.data().contacts
});
console.log(userdt); //this one works
})
console.log(userdt); // but this one doesnt diplay anything just []
})
}).catch((dterr) => {
console.log(dterr)
})
});
this.setState({bizdata: bizs,loading: false
});
});
}
I am using react-native and firestore
Put log with some number,
like,
console.log('1',userdt);
console.log('2',userdt);
and check weather which one is appearing first, Maybe '2' is executing before updating the data