feat: use RTK Query to get order deails (#73)
This commit is contained in:
parent
e3d316c418
commit
45c4ca16c8
@ -42,7 +42,7 @@
|
||||
"dry-wash.order-create.create-order-query.success.title": "The order is successfully created",
|
||||
"dry-wash.order-create.create-order-query.error.title": "Failed to create an order",
|
||||
"dry-wash.order-view.title": "Your order",
|
||||
"dry-wash.order-view.get-order-query.error.title": "Failed to fetch the details of order #{{number}}",
|
||||
"dry-wash.order-view.get-order-query.error.title": "Failed to fetch the details of order",
|
||||
"dry-wash.order-view.details.title": "Order #{{number}}",
|
||||
"dry-wash.order-view.details.owner": "Owner",
|
||||
"dry-wash.order-view.details.car": "Car",
|
||||
|
@ -82,7 +82,7 @@
|
||||
"dry-wash.order-create.create-order-query.success.title": "Заказ успешно создан",
|
||||
"dry-wash.order-create.create-order-query.error.title": "Не удалось создать заказ",
|
||||
"dry-wash.order-view.title": "Ваш заказ",
|
||||
"dry-wash.order-view.get-order-query.error.title": "Не удалось загрузить детали заказа №{{number}}",
|
||||
"dry-wash.order-view.get-order-query.error.title": "Не удалось загрузить детали заказа",
|
||||
"dry-wash.order-view.details.title": "Заказ №{{number}}",
|
||||
"dry-wash.order-view.details.owner": "Владелец",
|
||||
"dry-wash.order-view.details.car": "Автомобиль",
|
||||
|
@ -3,17 +3,7 @@ import { getConfigValue } from '@brojs/cli';
|
||||
|
||||
import { Master } from '../../models/api/master';
|
||||
|
||||
type SuccessResponse<Body> = {
|
||||
success: true;
|
||||
body: Body;
|
||||
};
|
||||
|
||||
type ErrorResponse = {
|
||||
success: false;
|
||||
message: string;
|
||||
};
|
||||
|
||||
type BaseResponse<Body> = SuccessResponse<Body> | ErrorResponse;
|
||||
import { extractBodyFromResponse } from './utils';
|
||||
|
||||
export const api = createApi({
|
||||
reducerPath: 'api',
|
||||
@ -22,11 +12,7 @@ export const api = createApi({
|
||||
endpoints: (builder) => ({
|
||||
getMasters: builder.query<Master[], void>({
|
||||
query: () => ({ url: '/arm/masters' }),
|
||||
transformResponse: (response: BaseResponse<Master[]>) => {
|
||||
if (response.success) {
|
||||
return response.body;
|
||||
}
|
||||
},
|
||||
transformResponse: extractBodyFromResponse<Master[]>,
|
||||
providesTags: ['Masters'],
|
||||
}),
|
||||
addMaster: builder.mutation<void, Pick<Master, 'name' | 'phone'>>({
|
||||
|
14
src/__data__/service/landing.api.ts
Normal file
14
src/__data__/service/landing.api.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { GetOrder } from "../../models/api";
|
||||
|
||||
import { api } from "./api";
|
||||
import { extractBodyFromResponse, extractErrorMessageFromResponse } from "./utils";
|
||||
|
||||
export const landingApi = api.injectEndpoints({
|
||||
endpoints: ({ query }) => ({
|
||||
getOrder: query<GetOrder.Response, GetOrder.Params>({
|
||||
query: ({ orderId }) => `/order/${orderId}`,
|
||||
transformResponse: extractBodyFromResponse<GetOrder.Response>,
|
||||
transformErrorResponse: extractErrorMessageFromResponse,
|
||||
})
|
||||
})
|
||||
});
|
15
src/__data__/service/utils.ts
Normal file
15
src/__data__/service/utils.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { FetchBaseQueryError } from "@reduxjs/toolkit/query";
|
||||
|
||||
import { BaseResponse } from "../../models/api";
|
||||
|
||||
export const extractBodyFromResponse = <Body>(response: BaseResponse<Body>) => {
|
||||
if (response.success) {
|
||||
return response.body;
|
||||
}
|
||||
};
|
||||
|
||||
export const extractErrorMessageFromResponse = ({ data }: FetchBaseQueryError) => {
|
||||
if (typeof data === 'object' && 'message' in data && typeof data.message === 'string') {
|
||||
return data.message;
|
||||
}
|
||||
};
|
@ -1,12 +1,11 @@
|
||||
import { getConfigValue } from '@brojs/cli';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { CreateOrder, GetOrder } from '../models/api';
|
||||
import { CreateOrder } from '../models/api';
|
||||
|
||||
import { QueryState, Trigger } from './types';
|
||||
|
||||
enum LandingEndpoints {
|
||||
ORDER = '/order',
|
||||
ORDER_CREATE = '/order/create',
|
||||
}
|
||||
|
||||
@ -63,45 +62,4 @@ const useCreateOrderMutation = <D extends CreateOrder.Response>(): [
|
||||
return [createOrder, { isLoading, isSuccess, data, isError, error }];
|
||||
};
|
||||
|
||||
const useGetOrderQuery = <D extends GetOrder.Response>({
|
||||
orderId,
|
||||
}: GetOrder.Params): QueryState<D> => {
|
||||
const [isLoading, setIsLoading] = useState<QueryState<D>['isLoading']>(true);
|
||||
const [isSuccess, setIsSuccess] = useState<QueryState<D>['isSuccess']>();
|
||||
const [data, setData] = useState<QueryState<D>['data']>();
|
||||
const [isError, setIsError] = useState<QueryState<D>['isError']>();
|
||||
const [error, setError] = useState<QueryState<D>['error']>();
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${endpoint}${LandingEndpoints.ORDER}/${orderId}`,
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorResponseObject =
|
||||
(await response.json()) as QueryState<D>['error'];
|
||||
setIsError(true);
|
||||
setError(errorResponseObject);
|
||||
throw errorResponseObject;
|
||||
}
|
||||
|
||||
const dataResponseObject =
|
||||
(await response.json()) as QueryState<D>['data'];
|
||||
setIsSuccess(true);
|
||||
setData(dataResponseObject);
|
||||
} catch (error) {
|
||||
setIsError(true);
|
||||
setError(error);
|
||||
throw error;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
return { isLoading, isSuccess, data, isError, error };
|
||||
};
|
||||
|
||||
export { useCreateOrderMutation, useGetOrderQuery };
|
||||
export { useCreateOrderMutation };
|
||||
|
@ -19,7 +19,7 @@ import { OrderStatus } from './status';
|
||||
|
||||
type OrderDetailsProps = Pick<
|
||||
Order.View,
|
||||
| 'id'
|
||||
| 'orderNumber'
|
||||
| 'status'
|
||||
| 'phone'
|
||||
| 'carNumber'
|
||||
@ -32,7 +32,7 @@ type OrderDetailsProps = Pick<
|
||||
>;
|
||||
|
||||
export const OrderDetails: FC<OrderDetailsProps> = ({
|
||||
id,
|
||||
orderNumber,
|
||||
status,
|
||||
phone,
|
||||
carNumber,
|
||||
@ -58,7 +58,7 @@ export const OrderDetails: FC<OrderDetailsProps> = ({
|
||||
gap={2}
|
||||
>
|
||||
<Heading as='h2' size='lg'>
|
||||
{t('title', { number: id })}
|
||||
{t('title', { number: orderNumber })}
|
||||
</Heading>
|
||||
<OrderStatus value={status} />
|
||||
</HStack>
|
||||
|
@ -15,19 +15,19 @@ const getPropsByStatus = (
|
||||
colorScheme: 'red',
|
||||
children: t('canceled'),
|
||||
};
|
||||
case 'progress':
|
||||
return {
|
||||
colorScheme: 'yellow',
|
||||
children: t('progress'),
|
||||
};
|
||||
case 'pending':
|
||||
return {
|
||||
colorScheme: 'yellow',
|
||||
children: t('pending'),
|
||||
};
|
||||
case 'progress':
|
||||
return {
|
||||
colorScheme: 'orange',
|
||||
children: t('progress'),
|
||||
};
|
||||
case 'working':
|
||||
return {
|
||||
colorScheme: 'yellow',
|
||||
colorScheme: 'orange',
|
||||
children: t('working'),
|
||||
};
|
||||
case 'complete':
|
||||
|
13
src/models/api/common.ts
Normal file
13
src/models/api/common.ts
Normal file
@ -0,0 +1,13 @@
|
||||
type SuccessResponse<Body> = {
|
||||
success: true;
|
||||
body: Body;
|
||||
};
|
||||
|
||||
export type ErrorMessage = string;
|
||||
|
||||
type ErrorResponse = {
|
||||
success: false;
|
||||
message: ErrorMessage;
|
||||
};
|
||||
|
||||
export type BaseResponse<Body> = SuccessResponse<Body> | ErrorResponse;
|
@ -1 +1,2 @@
|
||||
export * from './common';
|
||||
export * from './order';
|
@ -1,6 +1,16 @@
|
||||
/* eslint-disable @typescript-eslint/no-namespace */
|
||||
import { Order } from "../landing";
|
||||
|
||||
import { ErrorMessage } from "./common";
|
||||
|
||||
export namespace GetOrder {
|
||||
export type Response = Order.View;
|
||||
export type Params = {
|
||||
orderId: Order.Id
|
||||
};
|
||||
export type Error = ErrorMessage;
|
||||
}
|
||||
|
||||
export namespace CreateOrder {
|
||||
export type Response = {
|
||||
id: Order.Id
|
||||
@ -8,11 +18,4 @@ export namespace CreateOrder {
|
||||
export type Params = {
|
||||
body: Order.Create
|
||||
};
|
||||
};
|
||||
|
||||
export namespace GetOrder {
|
||||
export type Response = Order.View;
|
||||
export type Params = {
|
||||
orderId: Order.Id
|
||||
};
|
||||
};
|
@ -26,6 +26,8 @@ export type Create = {
|
||||
}
|
||||
};
|
||||
|
||||
export type Number = string;
|
||||
|
||||
export type View = {
|
||||
phone: Customer.PhoneNumber;
|
||||
carNumber: Car.RegistrationNumber;
|
||||
@ -34,6 +36,7 @@ export type View = {
|
||||
location: Washing.Location;
|
||||
startWashTime: Washing.AvailableBeginDateTime;
|
||||
endWashTime: Washing.AvailableEndDateTime;
|
||||
orderNumber: Number,
|
||||
status: Status,
|
||||
notes: string;
|
||||
created: IsoDate;
|
||||
|
@ -1,5 +1,13 @@
|
||||
import React, { FC } from 'react';
|
||||
import { Alert, AlertDescription, AlertIcon, AlertTitle, HStack, Spinner } from '@chakra-ui/react';
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertIcon,
|
||||
AlertTitle,
|
||||
Box,
|
||||
HStack,
|
||||
Spinner,
|
||||
} from '@chakra-ui/react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Container, Heading, VStack } from '@chakra-ui/react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
@ -10,7 +18,8 @@ import {
|
||||
} from '../../containers';
|
||||
import { OrderDetails } from '../../components/order-view';
|
||||
import { Order } from '../../models/landing';
|
||||
import { useGetOrderQuery } from '../../api';
|
||||
import { landingApi } from '../../__data__/service/landing.api';
|
||||
import { ErrorMessage } from '../../models/api';
|
||||
|
||||
const Page: FC = () => {
|
||||
const { t } = useTranslation('~', {
|
||||
@ -21,12 +30,15 @@ const Page: FC = () => {
|
||||
const {
|
||||
isLoading,
|
||||
isSuccess,
|
||||
data: { body: order } = {},
|
||||
data: order,
|
||||
isError,
|
||||
error,
|
||||
} = useGetOrderQuery({
|
||||
orderId,
|
||||
});
|
||||
} = landingApi.useGetOrderQuery(
|
||||
{
|
||||
orderId,
|
||||
},
|
||||
);
|
||||
const errorMessage = error as ErrorMessage;
|
||||
|
||||
return (
|
||||
<LandingThemeProvider>
|
||||
@ -51,7 +63,7 @@ const Page: FC = () => {
|
||||
<>
|
||||
{isSuccess && (
|
||||
<OrderDetails
|
||||
id={order.id}
|
||||
orderNumber={order.orderNumber}
|
||||
status={order.status}
|
||||
phone={order.phone}
|
||||
carNumber={order.carNumber}
|
||||
@ -66,14 +78,14 @@ const Page: FC = () => {
|
||||
</>
|
||||
<>
|
||||
{isError && (
|
||||
<Alert status='error'>
|
||||
<Alert status='error' alignItems='flex-start'>
|
||||
<AlertIcon />
|
||||
<AlertTitle>
|
||||
{t('get-order-query.error.title', {
|
||||
number: orderId,
|
||||
})}
|
||||
</AlertTitle>
|
||||
<AlertDescription>{error.data?.error}</AlertDescription>
|
||||
<Box>
|
||||
<AlertTitle>
|
||||
{t('get-order-query.error.title')}
|
||||
</AlertTitle>
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Box>
|
||||
</Alert>
|
||||
)}
|
||||
</>
|
||||
|
@ -2,7 +2,7 @@
|
||||
/* eslint-disable @typescript-eslint/no-require-imports */
|
||||
const router = require('express').Router();
|
||||
|
||||
const STUBS = { masters: 'success', orders: 'success', orderView: 'success' };
|
||||
const STUBS = { masters: 'success', orders: 'success', orderView: 'success-pending' };
|
||||
|
||||
router.get('/set/:name/:value', (req, res) => {
|
||||
const { name, value } = req.params;
|
||||
@ -28,7 +28,8 @@ router.get('/', (req, res) => {
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Лендинг - Детали заказа</legend>
|
||||
${generateRadioInput('orderView', 'success')}
|
||||
${generateRadioInput('orderView', 'success-pending')}
|
||||
${generateRadioInput('orderView', 'success-working')}
|
||||
${generateRadioInput('orderView', 'error')}
|
||||
</fieldset>
|
||||
</div>`);
|
||||
|
4
stubs/json/landing-order-view/id1-error.json
Normal file
4
stubs/json/landing-order-view/id1-error.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"success": false,
|
||||
"message": "Не удалось загрузить детали заказа"
|
||||
}
|
@ -8,10 +8,11 @@
|
||||
"startWashTime": "2025-01-19T14:03:00.000Z",
|
||||
"endWashTime": "2025-01-19T14:03:00.000Z",
|
||||
"location": "55.793833888711006,49.19037910644527 Республика Татарстан (Татарстан), Казань, жилой район Седьмое Небо",
|
||||
"status": "progress",
|
||||
"orderNumber": "1",
|
||||
"status": "pending",
|
||||
"notes": "",
|
||||
"created": "2025-01-19T14:04:02.985Z",
|
||||
"updated": "2025-01-19T14:04:02.987Z",
|
||||
"id": "678d06527d78ec30be2679d8"
|
||||
"id": "id1"
|
||||
}
|
||||
}
|
18
stubs/json/landing-order-view/id1-success-working.json
Normal file
18
stubs/json/landing-order-view/id1-success-working.json
Normal file
@ -0,0 +1,18 @@
|
||||
{
|
||||
"success": true,
|
||||
"body": {
|
||||
"phone": "+79876543210",
|
||||
"carNumber": "А123АА16",
|
||||
"carBody": 2,
|
||||
"carColor": "#ffffff",
|
||||
"startWashTime": "2025-01-19T14:03:00.000Z",
|
||||
"endWashTime": "2025-01-19T14:03:00.000Z",
|
||||
"location": "55.793833888711006,49.19037910644527 Республика Татарстан (Татарстан), Казань, жилой район Седьмое Небо",
|
||||
"orderNumber": "1",
|
||||
"status": "working",
|
||||
"notes": "",
|
||||
"created": "2025-01-19T14:04:02.985Z",
|
||||
"updated": "2025-01-19T14:04:02.987Z",
|
||||
"id": "id1"
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user