Introduction:
In my website, I added a private parameter which users can set in their profile. This parameter affects the display of the website, so it is a variable that needs to be fetched from the backend to customize the way the website displays.
The problem is, I did not know how to fetch this value.
After a lot of searching and trying, I got to the solution I needed, so I thought I might as well share it with anyone that might need to do something similar. There might be easier solutions, but at least this worked for me, so it’s worth giving it a try if you are facing a similar problem.
How I did it:
The code is as follows. I’m skipping error checks and logs so it becomes shorter and straight to the point.
import { Permissions, webMethod } from 'wix-web-module';
import { currentUser } from 'wix-users-backend';
import { contacts } from 'wix-crm-backend';
export const getUserGamesPerPage = webMethod(Permissions.Anyone, async () => {
try {
const user = currentUser;
// Get the current user email, so we can compare with the contacts
const userEmail = await user.getEmail();
// Query contacts by email to get the contact ID
const queryResults = await contacts.queryContacts()
.eq("primaryInfo.email", userEmail)
.find({ suppressAuth: true });
const contactsResult = { items: queryResults.items };
// Use the contact data directly from the query results
const contact = contactsResult.items[0];
// Extract the custom field value for "Games per page" from extendedFields
const gamesPerPage = contact.info?.extendedFields?.["custom.games-per-page"];
if (gamesPerPage !== undefined && gamesPerPage !== null) {
const value = parseInt(gamesPerPage);
return value;
}
return 0;
} catch (error) {
console.error("Error in getUserGamesPerPage:", error);
return 0;
}
});
Tools, Documentation and APIs:
Here are some of the pages I checked: