Skip to content

Commit

Permalink
feat: add react-query to super admin (#182)
Browse files Browse the repository at this point in the history
* feat: add react-query to super admin

* feat: remove unnecessary async
  • Loading branch information
comoser authored Sep 18, 2023
1 parent 039736c commit 680020a
Show file tree
Hide file tree
Showing 18 changed files with 306 additions and 188 deletions.
31 changes: 31 additions & 0 deletions packages/web-ui/api/requests/super-admin/admin-add-ai-model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Endpoints from '@/api/endpoints';
import { superAdminApiClient } from '@/api/superAdminApiClient';
import { SuperAdminAddAiModelRequestDto } from '@/contract/ai/super-admin-add-ai-model.request.dto.d';
import { SuperAdminAiModelResponseDto } from '@/contract/ai/super-admin-ai-model.response.dto.d';

export const adminAddAiModel = async (
values: SuperAdminAddAiModelRequestDto,
superAdminEmail: string,
superAdminPassword: string
) => {
return new Promise<SuperAdminAiModelResponseDto>(async (resolve, reject) => {
const res = await superAdminApiClient({
url: Endpoints.admin.addAiModel(),
options: {
method: 'POST',
body: JSON.stringify({
...values,
}),
},
superAdminEmail,
superAdminPassword,
});

if (!res.ok) {
const { error } = JSON.parse(await res.text());
return reject(error);
}

resolve(await res.json());
});
};
28 changes: 28 additions & 0 deletions packages/web-ui/api/requests/super-admin/admin-get-ai-models.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import Endpoints from '@/api/endpoints';
import { superAdminApiClient } from '@/api/superAdminApiClient';
import { SuperAdminAiModelResponseDto } from '@/contract/ai/super-admin-ai-model.response.dto.d';

export const ADMIN_GET_AI_MODELS_REQ_KEY = 'admin-ai-models';

export const adminGetAiModels = async (
superAdminEmail: string,
superAdminPassword: string
) => {
return new Promise<SuperAdminAiModelResponseDto[]>(
async (resolve, reject) => {
const res = await superAdminApiClient({
url: Endpoints.admin.getAiModels(),
options: { method: 'GET' },
superAdminEmail,
superAdminPassword,
});

if (!res.ok) {
const { error } = JSON.parse(await res.text());
return reject(error);
}

resolve(await res.json());
}
);
};
26 changes: 26 additions & 0 deletions packages/web-ui/api/requests/super-admin/admin-get-all-users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import Endpoints from '@/api/endpoints';
import { superAdminApiClient } from '@/api/superAdminApiClient';
import { UserResponseDto } from '@/contract/auth/user.response.dto.d';

export const ADMIN_GET_ALL_USERS_REQ_KEY = 'admin-all-users';

export const adminGetAllUsers = async (
superAdminEmail: string,
superAdminPassword: string
) => {
return new Promise<UserResponseDto[]>(async (resolve, reject) => {
const res = await superAdminApiClient({
url: Endpoints.admin.getUsers(),
options: { method: 'GET' },
superAdminEmail,
superAdminPassword,
});

if (!res.ok) {
const { error } = JSON.parse(await res.text());
return reject(error);
}

resolve(await res.json());
});
};
33 changes: 33 additions & 0 deletions packages/web-ui/api/requests/super-admin/update-user-roles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import Endpoints from '@/api/endpoints';
import { superAdminApiClient } from '@/api/superAdminApiClient';
import { SuperAdminUpdateUserRoleRequestDto } from '@/contract/auth/super-admin-update-role.request.dto.d';
import { UserResponseDto } from '@/contract/auth/user.response.dto.d';

export const updateUserRoles = async (
userId: string,
values: Omit<SuperAdminUpdateUserRoleRequestDto, 'userId'>,
superAdminEmail: string,
superAdminPassword: string
) => {
return new Promise<UserResponseDto>(async (resolve, reject) => {
const res = await superAdminApiClient({
url: Endpoints.admin.updateUserRoles(),
options: {
method: 'POST',
body: JSON.stringify({
userId,
...values,
}),
},
superAdminEmail,
superAdminPassword,
});

if (!res.ok) {
const { error } = JSON.parse(await res.text());
return reject(error);
}

resolve(await res.json());
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import Endpoints from '@/api/endpoints';
import { superAdminApiClient } from '@/api/superAdminApiClient';
import { SuperAdminValidateCredentialsRequestDto } from '@/contract/auth/super-admin-validate-credentials.request.dto.d';

export const validateAdminCredentials = async (
values: SuperAdminValidateCredentialsRequestDto
) => {
return new Promise<void>(async (resolve, reject) => {
const res = await superAdminApiClient({
url: Endpoints.admin.validateCredentials(),
options: { method: 'POST', body: JSON.stringify(values) },
});

if (!res.ok) {
const { error } = JSON.parse(await res.text());
return reject(error);
}

resolve();
});
};
9 changes: 4 additions & 5 deletions packages/web-ui/app/admin/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import '@/styles/globals.css';
import { cookies, headers } from 'next/headers';
import { redirect } from 'next/navigation';
import Endpoints from '@/api/endpoints';
import { superAdminApiClient } from '@/api/superAdminApiClient';
import { getSuperAdminCookieOnServer } from '@/utils/get-super-admin-cookie-server';
import { getUrlPath } from '@/utils/get-url-path';

import { StateProvider } from '@/components/state-provider';

Expand All @@ -27,10 +28,8 @@ const validateSuperAdminCredentials = async (
};

export default async function SuperAdminLayout({ children }: RootLayoutProps) {
const nextCookies = cookies();
const { get: getHeader } = headers();
const adminCredentialsCookie = nextCookies.get('__admin');
const urlPath = getHeader('x-invoke-path');
const { adminCredentialsCookie } = getSuperAdminCookieOnServer();
const { urlPath } = getUrlPath();

// If no cookie credentials -> redirect for login (but if in login already, don't redirect again)
if (!adminCredentialsCookie && urlPath !== '/admin/login') {
Expand Down
37 changes: 20 additions & 17 deletions packages/web-ui/app/admin/login/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
'use client';

import { useRouter } from 'next/navigation';
import Endpoints from '@/api/endpoints';
import { superAdminApiClient } from '@/api/superAdminApiClient';
import { validateAdminCredentials } from '@/api/requests/super-admin/validate-admin-credentials';
import { SuperAdminValidateCredentialsRequestSchema } from '@/contract/auth/super-admin-validate-credentials.request.dto';
import { SuperAdminValidateCredentialsRequestDto } from '@/contract/auth/super-admin-validate-credentials.request.dto.d';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';

import { Button } from '@/components/ui/button';
Expand All @@ -23,6 +23,19 @@ import { useToast } from '@/components/ui/use-toast';
export default function SuperAdminLogin() {
const { toast } = useToast();
const router = useRouter();
const { mutate: validateAdminCredentialsReq, isLoading } = useMutation({
mutationFn: (values: SuperAdminValidateCredentialsRequestDto) =>
validateAdminCredentials(values),
onError: (error: any) => {
toast({
title: error,
variant: 'destructive',
});
},
onSuccess: (room) => {
router.push('/admin/manage/users');
},
});
const form = useForm<SuperAdminValidateCredentialsRequestDto>({
resolver: zodResolver(SuperAdminValidateCredentialsRequestSchema),
defaultValues: {
Expand All @@ -31,21 +44,9 @@ export default function SuperAdminLogin() {
},
});

async function onSubmit(values: SuperAdminValidateCredentialsRequestDto) {
function onSubmit(values: SuperAdminValidateCredentialsRequestDto) {
try {
const res = await superAdminApiClient({
url: Endpoints.admin.validateCredentials(),
options: { method: 'POST', body: JSON.stringify(values) },
});
if (!res.ok) {
const { error } = JSON.parse(await res.text());
toast({
title: error,
variant: 'destructive',
});
return;
}
router.push('/admin/manage/users');
validateAdminCredentialsReq(values);
} catch (e) {
console.log(e);
}
Expand Down Expand Up @@ -84,7 +85,9 @@ export default function SuperAdminLogin() {
)}
/>
<div className="flex w-full justify-end">
<Button type="submit">Login</Button>
<Button disabled={isLoading} type="submit">
Login
</Button>
</div>
</form>
</Form>
Expand Down
14 changes: 5 additions & 9 deletions packages/web-ui/app/admin/manage/ai-models/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import '@/styles/globals.css';
import { ReactNode } from 'react';

import { AdminHeader } from '@/components/admin/admin-header';

export default function AdminUsersLayout({
children,
params,
}: {
children: ReactNode;
params: { room: string };
}) {
interface RootLayoutProps {
children: React.ReactNode;
}

export default function AdminUsersLayout({ children }: RootLayoutProps) {
return (
<div className="flex h-full w-full">
<div className="flex h-full w-full flex-col">
Expand Down
42 changes: 13 additions & 29 deletions packages/web-ui/app/admin/manage/ai-models/page.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React from 'react';
import { cookies } from 'next/headers';
import Endpoints from '@/api/endpoints';
import { superAdminApiClient } from '@/api/superAdminApiClient';
import { SuperAdminAiModelResponseDto } from '@/contract/ai/super-admin-ai-model.response.dto.d';
import {
ADMIN_GET_AI_MODELS_REQ_KEY,
adminGetAiModels,
} from '@/api/requests/super-admin/admin-get-ai-models';
import { getSuperAdminCookieOnServer } from '@/utils/get-super-admin-cookie-server';

import { Card } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
Expand All @@ -17,34 +18,17 @@ import {
} from '@/components/ui/table';
import { AddAiModelsForm } from '@/components/admin/add-ai-models-form';
import { HoverableTableCell } from '@/components/admin/hoverable-table-cell';

const getAiModels = async (
superAdminEmail: string,
superAdminPassword: string
): Promise<SuperAdminAiModelResponseDto[]> => {
try {
const res = await superAdminApiClient({
url: Endpoints.admin.getAiModels(),
options: { method: 'GET' },
superAdminEmail,
superAdminPassword,
});
return res.json();
} catch (e) {
console.log(e);
}
return [];
};
import getQueryClient from '@/app/get-query-client';

export default async function AdminAiModels() {
const nextCookies = cookies();
const adminCredentialsCookie = nextCookies.get('__admin');
const { adminCredentialsCookie } = getSuperAdminCookieOnServer();
const adminCredentials = JSON.parse(adminCredentialsCookie!.value);

const aiModels = await getAiModels(
adminCredentials.email,
adminCredentials.password
);
const queryClient = getQueryClient();
const aiModels = await queryClient.fetchQuery({
queryKey: [ADMIN_GET_AI_MODELS_REQ_KEY],
queryFn: () =>
adminGetAiModels(adminCredentials.email, adminCredentials.password),
});

return (
<div className="flex h-full w-full flex-col p-4">
Expand Down
14 changes: 5 additions & 9 deletions packages/web-ui/app/admin/manage/users/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import '@/styles/globals.css';
import { ReactNode } from 'react';

import { AdminHeader } from '@/components/admin/admin-header';

export default function AdminUsersLayout({
children,
params,
}: {
children: ReactNode;
params: { room: string };
}) {
interface RootLayoutProps {
children: React.ReactNode;
}

export default function AdminUsersLayout({ children }: RootLayoutProps) {
return (
<div className="flex h-full w-full">
<div className="flex h-full w-full flex-col">
Expand Down
42 changes: 13 additions & 29 deletions packages/web-ui/app/admin/manage/users/page.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React from 'react';
import { cookies } from 'next/headers';
import Endpoints from '@/api/endpoints';
import { superAdminApiClient } from '@/api/superAdminApiClient';
import { UserResponseDto } from '@/contract/auth/user.response.dto.d';
import {
ADMIN_GET_ALL_USERS_REQ_KEY,
adminGetAllUsers,
} from '@/api/requests/super-admin/admin-get-all-users';
import { getSuperAdminCookieOnServer } from '@/utils/get-super-admin-cookie-server';
import { getUserEmail } from '@/utils/get-user-email';
import { alphaAscSortPredicate } from '@/utils/sort-predicates';

Expand All @@ -19,34 +20,17 @@ import {
TableRow,
} from '@/components/ui/table';
import { UpdateRolesForm } from '@/components/admin/update-roles-form';

const getUsers = async (
superAdminEmail: string,
superAdminPassword: string
): Promise<UserResponseDto[]> => {
try {
const res = await superAdminApiClient({
url: Endpoints.admin.getUsers(),
options: { method: 'GET' },
superAdminEmail,
superAdminPassword,
});
return res.json();
} catch (e) {
console.log(e);
}
return [];
};
import getQueryClient from '@/app/get-query-client';

export default async function AdminUsers() {
const nextCookies = cookies();
const adminCredentialsCookie = nextCookies.get('__admin');
const { adminCredentialsCookie } = getSuperAdminCookieOnServer();
const adminCredentials = JSON.parse(adminCredentialsCookie!.value);

const users = await getUsers(
adminCredentials.email,
adminCredentials.password
);
const queryClient = getQueryClient();
const users = await queryClient.fetchQuery({
queryKey: [ADMIN_GET_ALL_USERS_REQ_KEY],
queryFn: () =>
adminGetAllUsers(adminCredentials.email, adminCredentials.password),
});

return (
<div className="flex h-full w-full p-4">
Expand Down
Loading

0 comments on commit 680020a

Please sign in to comment.