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

Обновление (offer): заменяет api серверным компонентом #64

Merged
merged 1 commit into from
Aug 14, 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
6 changes: 6 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint", "prettier"],
"rules": {
/**
* Ошибка no-void при использовании
* шаблона предварительной загрузки (Next.js preload)
* подробнее: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching#preloading-data
*/
"no-void": ["error", { "allowAsStatement": true }],
// ошибка no-shadow при использовании Enum
"no-shadow": "off",
"@typescript-eslint/no-shadow": ["error"],
Expand Down
4 changes: 3 additions & 1 deletion app/post/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { notFound } from "next/navigation";

import { getPathsToPosts, getPost } from "@/core/ssr";
import { RoutePost } from "@/routes/Post/Route.Post";
import { preloadOffers } from "@/components/Offer/api";

type Props = {
params: {
Expand Down Expand Up @@ -50,6 +51,7 @@ export const generateMetadata = async ({
const Page = async ({ params }: Props) => {
const { slug } = params;

preloadOffers(slug);
const post = await getPost({ slug });

if (post === null) {
Expand All @@ -58,7 +60,7 @@ const Page = async ({ params }: Props) => {

return (
<RoutePost
id={post.id}
id={slug}
href={post.link}
title={post.title}
blocks={post.blocks}
Expand Down
41 changes: 0 additions & 41 deletions components/Offer/Offer.tsx

This file was deleted.

31 changes: 31 additions & 0 deletions components/Offer/api/getOffers/adapter/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { SearchResponseFrontend } from "@/core/elastic/type";
import { PostCardItem } from "src/entities/card/Post";

type CardItem = PostCardItem & {
id: string;
};

export const offerAdapter = (data: SearchResponseFrontend): CardItem[] =>
data.hits.hits.flatMap(({ _id, _source }) => {
if (!_source) return [];

const { title, link, categories, departments, excerpt, thumbnail } =
_source;

return {
id: _id.toString(),
title,
uri: link,
categories: {
nodes: departments.concat(categories),
},
excerpt,
featuredImage: thumbnail.url
? {
node: {
sourceUrl: thumbnail.url,
},
}
: null,
};
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Nullable } from "@/helpers/typings/utility-types";

export type GetMinimumDataForOfferQuery = {
post: Nullable<{
id: string;
categories: {
nodes: {
name: string;
Expand All @@ -18,7 +19,8 @@ export type GetMinimumDataForOfferQuery = {

export const getMinimumDataForOfferDocument = gql`
query GetMinimumDataForOffer($id: ID!) {
post(id: $id) {
post(id: $id, idType: SLUG) {
id
categories {
nodes {
name
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
/**
* Возвращаем минимально необходимый набор данных
* для последующих запросов на формирование предложения.
* @param id текущей записи
* @param id ярлык текущей записи
*/
export const getMinimumDataForOffer = async (id: string) => {
const { data, error, errors } =
Expand All @@ -22,6 +22,7 @@ export const getMinimumDataForOffer = async (id: string) => {
id,
},
});

if (error !== undefined) throw new ApiError(500, error.message);
if (data === undefined) throw errors;
const { post } = data;
Expand All @@ -32,7 +33,7 @@ export const getMinimumDataForOffer = async (id: string) => {
);

return {
notIn: id,
excludedId: post.id,
keywords: post.postsFields.keywords,
categories: categories.nodes.map((c) => c.name).join(","),
departments: departments.nodes.map((d) => d.name).join(","),
Expand Down
37 changes: 37 additions & 0 deletions components/Offer/api/getOffers/getOffers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { searchQuery } from "@/core/elastic";
import { SearchParams } from "@/core/elastic/type";
import { exceptionLog } from "@/helpers";

import { offerAdapter } from "./adapter";
import { getMinimumDataForOffer } from "./getMinimumDataForOffer";

const fetcher = (arggs: SearchParams) => searchQuery(arggs).then(offerAdapter);

/** @param id ярлык текущей записи */
export const getOffers = async (id: string) => {
try {
const { excludedId, keywords, categories, departments, lteDate } =
await getMinimumDataForOffer(id);

const similarPostsData = keywords
? fetcher({ text: keywords, lteDate, excludedId })
: null;

const postsByCategoryData = fetcher({
categories,
departments,
lteDate,
excludedId,
});

const [similarPosts, postsByCategory] = await Promise.all([
similarPostsData,
postsByCategoryData,
]);

return { similarPosts, postsByCategory };
} catch (error) {
exceptionLog(error);
return null;
}
};
6 changes: 6 additions & 0 deletions components/Offer/api/getOffers/preloadOffers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { getOffers } from "./getOffers";

/** @param id ярлык текущей записи */
export const preloadOffers = (id: string) => {
void getOffers(id);
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Nullable } from "@/helpers/typings/utility-types";

import { convertData } from "../utils";
import { offerAdapter } from "../adapter";

type ConvertData = Nullable<ReturnType<typeof convertData>>;
type ConvertData = Nullable<ReturnType<typeof offerAdapter>>;
export type ResponseOfferData = {
similarPosts: ConvertData;
postsByCategory: ConvertData;
Expand Down
2 changes: 2 additions & 0 deletions components/Offer/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { getOffers } from "./getOffers/getOffers";
export { preloadOffers } from "./getOffers/preloadOffers";
4 changes: 2 additions & 2 deletions components/Offer/components/Tabs/Offer.Tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { Nullable } from "@/helpers/typings/utility-types";
import { CarouselRoot } from "@/components/Carousel/CarouselRoot";
import { PostCard, PostCardItem } from "src/entities/card/Post";

import { createCategoryName } from "../../utils/createCategoryName";
import { handleOnClick } from "../../utils/goal";
import { createCategoryName } from "../../lib/createCategoryName";
import { handleOnClick } from "../../lib/goal";

import {
sxOfferHeader,
Expand Down
8 changes: 8 additions & 0 deletions components/Offer/components/Tabs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"use client";

import dynamic from "next/dynamic";

export const DynamicOfferTabs = dynamic(
() => import("./Offer.Tabs").then((res) => res.OfferTabs),
{ ssr: false },
);
1 change: 1 addition & 0 deletions components/Offer/components/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { DynamicOfferTabs } from "./Tabs";
11 changes: 1 addition & 10 deletions components/Offer/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1 @@
"use client";

import dynamic from "next/dynamic";

export const DynamicOffer = dynamic(
() => import("./Offer").then((res) => res.Offer),
{
ssr: false,
},
);
export { Offer } from "./ui";
File renamed without changes.
22 changes: 22 additions & 0 deletions components/Offer/ui/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { getOffers } from "../api";
import { DynamicOfferTabs } from "../components";

type OfferProps = {
id: string;
categories: string[];
};

export const Offer = async ({ id, categories }: OfferProps) => {
const data = await getOffers(id);

if (!data || !(data.similarPosts?.length || data.postsByCategory?.length))
return null;

return (
<DynamicOfferTabs
categories={categories}
similarPosts={data.similarPosts}
postsByCategory={data.postsByCategory}
/>
);
};
1 change: 0 additions & 1 deletion core/api/offers/index.ts

This file was deleted.

25 changes: 0 additions & 25 deletions core/api/offers/utils/convertData.ts

This file was deleted.

1 change: 0 additions & 1 deletion core/api/offers/utils/index.ts

This file was deleted.

Loading