Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add queries, better routing & stores #20

Merged
merged 3 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/frontend/.env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_API_BASE_URL=http://localhost:5000/api
176 changes: 176 additions & 0 deletions apps/frontend/@/components/ui/form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
ControllerProps,
FieldPath,
FieldValues,
FormProvider,
useFormContext,
} from "react-hook-form"

import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"

const Form = FormProvider

type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}

const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)

const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}

const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()

const fieldState = getFieldState(fieldContext.name, formState)

if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}

const { id } = itemContext

return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}

type FormItemContextValue = {
id: string
}

const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)

const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()

return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"

const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()

return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"

const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()

return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"

const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()

return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"

const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message) : children

if (!body) {
return null
}

return (
<p
ref={ref}
id={formMessageId}
className={cn("text-sm font-medium text-destructive", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"

export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}
40 changes: 19 additions & 21 deletions apps/frontend/@/components/ui/input.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
import * as React from "react"
import * as React from 'react';

import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';

export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}

const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
const Input = React.forwardRef<HTMLInputElement, InputProps>(({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
'flex h-12 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
ref={ref}
{...props}
/>
);
});

export { Input }
Input.displayName = 'Input';

export { Input };
24 changes: 24 additions & 0 deletions apps/frontend/@/components/ui/label.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "@/lib/utils"

const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)

const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName

export { Label }
8 changes: 7 additions & 1 deletion apps/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@
"preview": "vite preview"
},
"dependencies": {
"@hookform/resolvers": "^3.3.4",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-slot": "^1.0.2",
"@tanstack/react-query": "^5.24.6",
"@tanstack/react-router": "^1.15.16",
"@tanstack/react-table": "^8.11.8",
"@tanstack/router-devtools": "^1.15.16",
Expand All @@ -22,8 +25,11 @@
"pretty-bytes": "^6.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.51.0",
"tailwind-merge": "^2.2.1",
"tailwindcss-animate": "^1.0.7"
"tailwindcss-animate": "^1.0.7",
"zod": "^3.22.4",
"zustand": "^4.5.2"
},
"devDependencies": {
"@common/contracts": "*",
Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { type UseMutationOptions, useMutation, type UseMutationResult } from '@tanstack/react-query';

import { type LoginUserResponseBody } from '@common/contracts';

import { HttpService } from '../../../../../services/httpService/httpService';
import { UserApiError } from '../../../errors/userApiError';

export const useLoginUserMutation = (
options: UseMutationOptions<LoginUserResponseBody, UserApiError, { email: string; password: string }>,
): UseMutationResult<
LoginUserResponseBody,
UserApiError,
{
email: string;
password: string;
},
unknown
> => {
const loginUser = async (values: { email: string; password: string }): Promise<LoginUserResponseBody> => {
const loginUserResponse = await HttpService.post<LoginUserResponseBody>({
url: '/users/login',
body: {
email: values.email,
password: values.password,
},
});

if (loginUserResponse.success === false) {
throw new UserApiError({
message: mapStatusCodeToErrorMessage(loginUserResponse.statusCode),
apiResponseError: loginUserResponse.body.context,
statusCode: loginUserResponse.statusCode,
});
}

return loginUserResponse.body;
};

return useMutation({
mutationFn: loginUser,
...options,
});
};

const mapStatusCodeToErrorMessage = (statusCode: number): string => {
switch (statusCode) {
case 400:
return 'Email or password are invalid.';

case 401:
return 'Email or password are invalid.';

case 404:
return 'Email or password are invalid.';

case 500:
return 'Internal server error';

default:
return 'Unknown error';
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { type UseMutationOptions, useMutation, type UseMutationResult } from '@tanstack/react-query';

import { type LogoutUserBody, type LogoutUserPathParams } from '@common/contracts';

import { HttpService } from '../../../../../services/httpService/httpService';
import { UserApiError } from '../../../errors/userApiError';

type LogoutUserPayload = LogoutUserBody & LogoutUserPathParams;

export const useLogoutUserMutation = (
options: UseMutationOptions<void, UserApiError, LogoutUserPayload>,
): UseMutationResult<void, UserApiError, LogoutUserPayload, unknown> => {
const logoutUser = async (values: LogoutUserPayload): Promise<void> => {
const { id, refreshToken } = values;

const logoutUserResponse = await HttpService.post<void>({
url: `/users/login/${id}/logout`,
body: {
refreshToken,
},
});

if (logoutUserResponse.success === false) {
throw new UserApiError({
message: mapStatusCodeToErrorMessage(logoutUserResponse.statusCode),
apiResponseError: logoutUserResponse.body.context,
statusCode: logoutUserResponse.statusCode,
});
}

return;
};

return useMutation({
mutationFn: logoutUser,
...options,
});
};

const mapStatusCodeToErrorMessage = (statusCode: number): string => {
switch (statusCode) {
case 400:
return 'Invalid refresh token.';

case 401:
return 'Invalid refresh token.';

case 500:
return 'Internal server error';

default:
return 'Unknown error';
}
};
Empty file.
Empty file.
Loading
Loading