Acidias
Acidias
Explore posts from servers
PPrisma
Created by Acidias on 2/16/2025 in #help-and-questions
findMany() vs findMany({...})
// src/lib/db/db.ts
import { PrismaClient } from '@prisma/client';

const globalForPrisma = global as unknown as { prisma?: PrismaClient };

export const prisma = globalForPrisma.prisma ?? new PrismaClient();

if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma;
}

async function listCounties() {
try {
console.log("DATABASE_URL:", process.env.DATABASE_URL);

const counties = await prisma.county.findMany();
console.log("Counties:", counties);
} catch (error) {
console.error("Error listing counties:", error);
}
}

void listCounties();
// src/lib/db/db.ts
import { PrismaClient } from '@prisma/client';

const globalForPrisma = global as unknown as { prisma?: PrismaClient };

export const prisma = globalForPrisma.prisma ?? new PrismaClient();

if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma;
}

async function listCounties() {
try {
console.log("DATABASE_URL:", process.env.DATABASE_URL);

const counties = await prisma.county.findMany();
console.log("Counties:", counties);
} catch (error) {
console.error("Error listing counties:", error);
}
}

void listCounties();
//src/lib/db/list.ts
export async function getUKCounties(): Promise<County[]> {
console.log('Fetching UK counties...');
try {
const counties = await prisma.county.findMany();
console.log('FindMany result:', counties);
return counties;
} catch (error) {
console.error('Error fetching UK counties:', error);
throw error;
}
}
//src/lib/db/list.ts
export async function getUKCounties(): Promise<County[]> {
console.log('Fetching UK counties...');
try {
const counties = await prisma.county.findMany();
console.log('FindMany result:', counties);
return counties;
} catch (error) {
console.error('Error fetching UK counties:', error);
throw error;
}
}
In the db.ts its nicely returns the counties as expected. However in the lists.ts its empty. I've tried lot of versions and directy query or if i pass {where, selecet..} details to findMany, then it works in the getUKCounties too. So these works well:
const counties = await prisma.$queryRaw<County[]>`SELECT * FROM "County"`;
const counties = await prisma.county.findMany({
where: {},
select: {
id: true,
name: true
}
});
const counties = await prisma.$queryRaw<County[]>`SELECT * FROM "County"`;
const counties = await prisma.county.findMany({
where: {},
select: {
id: true,
name: true
}
});
I just started to use prisma, and while I found solution, I would be curious why in db.ts works simpty findMany, but not in the lists.ts
6 replies
RRefine
Created by stormy-gold on 5/31/2023 in #ask-any-question
After adding a parent to my menuItem in the sidebar the create: AddEmployee is giving 404 error
I have an element called My Business which is a parent element in the sidebar and I have under it Employees and Roles.
{
name: "business",
key: "business",
icon: <ArchitectureOutlined
color="action"
/>,
meta: {
label: "My Business",
},
},

{
name: "employees",
list: EmployeeList,
create: AddEmployee,
icon: <PeopleIcon />,
meta: {
parent: "business",
},
},
//Roles
{
name: "roles",
list: ManageRoles,
icon: <StarOutlineIcon />,
meta: {
parent: "business",
},
},
{
name: "business",
key: "business",
icon: <ArchitectureOutlined
color="action"
/>,
meta: {
label: "My Business",
},
},

{
name: "employees",
list: EmployeeList,
create: AddEmployee,
icon: <PeopleIcon />,
meta: {
parent: "business",
},
},
//Roles
{
name: "roles",
list: ManageRoles,
icon: <StarOutlineIcon />,
meta: {
parent: "business",
},
},
However the AddEmployee showing 404 if its have parent element
13 replies
RRefine
Created by sensitive-blue on 5/31/2023 in #ask-any-question
How to place my submenus on the right from the sider instead of placing them under it
Is there a simple way to do that?
15 replies
RRefine
Created by foreign-sapphire on 5/27/2023 in #ask-any-question
Add a home/landing page to my app
At the moment I have a logingPage added where the user can logging in and see the dashboard, I would Like to add a home page to it where I will do a landing page. How can I achieve that?
<ColorModeContextProvider>
<CssBaseline />
<GlobalStyles styles={{ html: { WebkitFontSmoothing: "auto" } }} />
<RefineSnackbarProvider>
<Refine
dataProvider={dataProvider("https://b.com/api/v1")}
notificationProvider={notificationProvider}
ReadyPage={ReadyPage}
catchAll={<ErrorComponent />}
resources={[
{
name: "building-plans",
list: BuildingPlan,
show: BuildingsDetail,
create: CreateBuildingPlan,
edit: EditBuildingPlan,
icon: <ArticleOutlined />,
},
{
name: "employees",
list: EmployeeList,
create: AddEmployee,
icon: <PeopleIcon />,
},
{
name: "contracts",
list: AllContracts,
icon: <AddHomeWorkOutlinedIcon />,
},
{
name: "my-profile",
icon: <AccountCircleOutlined />,
options: {
label: "My Profile",
},
list: MyProfile,
},
]}
Title={Title}
Sider={Sider}
Layout={Layout}
Header={Header}
routerProvider={routerProvider}
authProvider={authProvider}
LoginPage={Login}
DashboardPage={BusinessDetails}
/>
</RefineSnackbarProvider>
</ColorModeContextProvider>
<ColorModeContextProvider>
<CssBaseline />
<GlobalStyles styles={{ html: { WebkitFontSmoothing: "auto" } }} />
<RefineSnackbarProvider>
<Refine
dataProvider={dataProvider("https://b.com/api/v1")}
notificationProvider={notificationProvider}
ReadyPage={ReadyPage}
catchAll={<ErrorComponent />}
resources={[
{
name: "building-plans",
list: BuildingPlan,
show: BuildingsDetail,
create: CreateBuildingPlan,
edit: EditBuildingPlan,
icon: <ArticleOutlined />,
},
{
name: "employees",
list: EmployeeList,
create: AddEmployee,
icon: <PeopleIcon />,
},
{
name: "contracts",
list: AllContracts,
icon: <AddHomeWorkOutlinedIcon />,
},
{
name: "my-profile",
icon: <AccountCircleOutlined />,
options: {
label: "My Profile",
},
list: MyProfile,
},
]}
Title={Title}
Sider={Sider}
Layout={Layout}
Header={Header}
routerProvider={routerProvider}
authProvider={authProvider}
LoginPage={Login}
DashboardPage={BusinessDetails}
/>
</RefineSnackbarProvider>
</ColorModeContextProvider>
5 replies
RRefine
Created by national-gold on 5/25/2023 in #ask-any-question
How to limit the display of resources from users parameters?
I have two type of users. One without ParentUserID (admin) Another with parenUserId (employee who has parentUserId from the invitator(admin)) I would like to set up something like this:
resources={
identity.hasParent
? [
// Resources for users with a parent
{
name: "my-profile",
icon: <AccountCircleOutlined />,
options: {
label: "My Profile",
},
list: MyProfile,
},
]
: [
// Resources for users without a parent
{
name: "building-plans",
list: BuildingPlan,
show: BuildingsDetail,
create: CreateBuildingPlan,
edit: EditBuildingPlan,
icon: <ArticleOutlined />,
},
{
name: "employees",
list: EmployeeList,
create: AddEmployee,
icon: <PeopleIcon />,
},
{
name: "contracts",
list: AllContracts,
icon: <AddHomeWorkOutlinedIcon />,
},
{
name: "my-profile",
icon: <AccountCircleOutlined />,
options: {
label: "My Profile",
},
list: MyProfile,
},
]
}
resources={
identity.hasParent
? [
// Resources for users with a parent
{
name: "my-profile",
icon: <AccountCircleOutlined />,
options: {
label: "My Profile",
},
list: MyProfile,
},
]
: [
// Resources for users without a parent
{
name: "building-plans",
list: BuildingPlan,
show: BuildingsDetail,
create: CreateBuildingPlan,
edit: EditBuildingPlan,
icon: <ArticleOutlined />,
},
{
name: "employees",
list: EmployeeList,
create: AddEmployee,
icon: <PeopleIcon />,
},
{
name: "contracts",
list: AllContracts,
icon: <AddHomeWorkOutlinedIcon />,
},
{
name: "my-profile",
icon: <AccountCircleOutlined />,
options: {
label: "My Profile",
},
list: MyProfile,
},
]
}
20 replies
RRefine
Created by wise-white on 5/22/2023 in #ask-any-question
How do I pass invitation token with google auth to my backend?
import { CredentialResponse } from "../interfaces/google"; export const Login: React.FC = () => { const { mutate: login } = useLogin<CredentialResponse>(); //http://localhost:3000/login?to=%2Flogin%2F754c8673492ef41ba151b4ed526e74dab4cf6151c5126d89c43c0bee8f765aab const location = useLocation(); const queryParams = new URLSearchParams(location.search); const token = queryParams.get("to")?.split("/login/")[1]; console.log(token); const { loginWithRedirect } = useAuth0(); const GoogleButton = (): JSX.Element => { const divRef = useRef<HTMLDivElement>(null); useEffect(() => { if (typeof window === "undefined" !window.google !divRef.current) { return; } try { window.google.accounts.id.initialize({ ux_mode: "popup", client_id: "*-.apps.googleusercontent.com", callback: async (res: CredentialResponse) => { if (res.credential) { res.token = token; login(res); } }, }); window.google.accounts.id.renderButton(divRef.current, { theme: "filled_blue", size: "medium", type: "standard", }); } catch (error) { console.log(error); } }, []); // you can also add your client id as dependency here return <div ref={divRef} />; }; return ( ..... <Box mt={4}> <GoogleButton /> </Box> ); }; The token what it should be passed to my backend. and call this function: router.route('/login/:token').post(createUser); I tested with postman and from backend part it was working well and created the user I expected
6 replies
RRefine
Created by genetic-orange on 5/14/2023 in #ask-any-question
Receive data from database
How can I receive data from mongoDB with refine? user.routes.js: router.route('/invite').post(sendInvitation).get(getAllInvitations);; user.controller.js: const getAllInvitations = async (req, res) => { const { _end, _order, _start, _sort, email_like = "" } = req.query; const query = {}; if (email_like) { query.email = { $regex: email_like, $options: "i" }; } try { const count = await Invitation.countDocuments(query); const invitations = await Invitation .find(query) .populate("parentUserID") .limit(parseInt(_end, 10)) .skip(parseInt(_start, 10)) .sort({[_sort]: _order === "ASC" ? 1 : -1});
res.header("x-total-count", count); res.header("Access-Control-Expose-Headers", "x-total-count"); res.status(200).json(invitations); } catch (error) { res.status(500).json({ message: error.message }); } } invitation schema: import mongoose from 'mongoose'; const invitationSchema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, // Auto-generated by MongoDB parentUserID: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, name: { type: String, required: true }, surname: { type: String, required: true }, email: { type: String, required: true }, token: { type: String, required: true }, }); export default mongoose.model('Invitation', invitationSchema); Whatever I'm trying on front-end it is not working, the request keeps loading
16 replies
RRefine
Created by harsh-harlequin on 5/13/2023 in #ask-any-question
How to set the success pop up message on front end?
When I succesfull submit I would like the pop up message. const handleAddEmployee = async (values: EmployeeValues) => { setLoading(true); try { const response = await axios.post('http://localhost:8080/api/v1/users/invite', { name: values.name, surname: values.surname, email: values.email, parentUserID: identity.userid, });
if (response.status === 201) { console.log('Invitation sent successfully'); console. navigate("/employees/create");
} else { console.log('Failed to send invitation'); } } catch (error) { console.error(error); } finally { setLoading(false); } };
18 replies
RRefine
Created by rare-sapphire on 5/12/2023 in #ask-any-question
How to adding Resource type?
I managed to work with current resources. However I have a list: EmployeeList, where I have create opportunity (by admin), when admin wants to create a new Employee it is actually sends an invitation link to the email (saves the invitation to db, the email (where was sent), the Token (random generated) and parentUserId (senders Id). I would like to make a new page for registration by invitation. So for now a page where it is displayed if the token exist in the db (invitation is valid) and if so who is the inviter. Where and how should I add this page? I assume it is not resources, or it is?
17 replies