Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ const ManageClubRegistrationScreen = () => {
try {
const { clubs } = await clubService.searchClubs({
query: clubSearchQuery,
record_recent_search: "false",
});
setSearchResults(clubs);
} catch {
Expand Down
4 changes: 4 additions & 0 deletions apps/mobile/src/repositories/club.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export type ClubSearchMinActivityPeriod = "0" | "1" | "2" | "3_plus";

export type SearchClubsRequest = {
query: string;
record_recent_search?: ClubSearchBooleanString;
affiliation_type?: ClubSearchAffiliationType;
is_recruiting?: ClubSearchBooleanString;
recruit_type?: ClubSearchRecruitType;
Expand Down Expand Up @@ -366,6 +367,9 @@ export const getClubRepository = (): ClubRepository => ({
searchClubs: async (req, signal) => {
const searchParams = new URLSearchParams();
searchParams.append("query", req.query.toLowerCase().trim());
if (req.record_recent_search !== undefined) {
searchParams.append("record_recent_search", req.record_recent_search);
}
if (req.affiliation_type && req.affiliation_type !== "전체") {
searchParams.append("affiliation_type", req.affiliation_type);
}
Expand Down
49 changes: 49 additions & 0 deletions apps/mobile/src/repositories/clubSearchHistory.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { getClubRepository } from "@/repositories/club";
import { apiConnector } from "@/shared/utils/api";

jest.mock("@/shared/utils/api", () => ({
apiConnector: { get: jest.fn() },
}));

const get = apiConnector.get as jest.MockedFunction<typeof apiConnector.get>;

describe("club search history request", () => {
beforeEach(() => {
jest.clearAllMocks();
});

it.each(["true", "false"] as const)(
"forwards the explicit history preference %s without changing search filters",
async (flag) => {
const response = { clubs: [], totalSize: 0 };
get.mockResolvedValue(response);
const signal = new AbortController().signal;
const result = await getClubRepository().searchClubs(
{
query: " WAFFLE ",
record_recent_search: flag,
affiliation_type: "중앙동아리",
},
signal,
);
const [path, params, passedSignal] = get.mock.calls[0];
expect(path).toBe("/v2/clubs/search");
expect(params).toBeInstanceOf(URLSearchParams);
expect((params as URLSearchParams).get("query")).toBe("waffle");
expect((params as URLSearchParams).get("affiliation_type")).toBe(
"중앙동아리",
);
expect((params as URLSearchParams).get("record_recent_search")).toBe(
flag,
);
expect(passedSignal).toBe(signal);
expect(result).toBe(response);
},
);

it("omits the preference for normal exploration searches", async () => {
await getClubRepository().searchClubs({ query: "와플" });
const params = get.mock.calls[0][1] as URLSearchParams;
expect(params.has("record_recent_search")).toBe(false);
});
});
6 changes: 5 additions & 1 deletion apps/web/pages/api/v2/clubs/search/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ export default async function handler(
}

let filters: SearchFilters
let recordRecentSearch: boolean
try {
filters = parseSearchFilters(req.query)
recordRecentSearch = parseOptionalBoolean(req.query.record_recent_search) ?? true
} catch (err) {
if (err instanceof InvalidSearchFilterError) {
return res.status(400).send(err.message)
Expand All @@ -50,7 +52,9 @@ export default async function handler(

const { clubs, correctedQuery, isTypoCorrected } =
await searchService.searchWithTypoCorrection(query, { filters })
await saveRecentSearchBestEffort(auth, query)
if (recordRecentSearch) {
await saveRecentSearchBestEffort(auth, query)
}
return res.status(200).json({
clubs: clubs,
totalSize: clubs.length,
Expand Down
78 changes: 78 additions & 0 deletions apps/web/server/api/club-search-history.handler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const mocks = vi.hoisted(() => ({
search: vi.fn(),
auth: vi.fn(),
save: vi.fn(),
}))
vi.mock('server/provider', () => ({
Provider: { getService: () => ({ searchWithTypoCorrection: mocks.search }) },
}))
vi.mock('server/service/search.service', () => ({ SearchService: class SearchService {} }))
vi.mock('server/util/optional-auth', () => ({ resolveOptionalAuth: mocks.auth }))
vi.mock('server/service/recent-search.service', () => ({ saveRecentSearchBestEffort: mocks.save }))

import handler from '../../pages/api/v2/clubs/search'

async function request(query: NextApiRequest['query']) {
const response = { status: vi.fn(), json: vi.fn(), send: vi.fn() }
response.status.mockReturnValue(response)
await handler({ method: 'GET', query } as NextApiRequest, response as unknown as NextApiResponse)
return response
}

describe('club search recent-history contract', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.auth.mockResolvedValue({ type: 'member', accountId: 'test-account' })
mocks.search.mockResolvedValue({
clubs: [{ uuid: 'club-id', name: '와플스튜디오' }],
correctedQuery: null,
isTypoCorrected: false,
})
})

it.each([undefined, 'true'])(
'preserves normal search history with record flag %s',
async (flag) => {
const response = await request({ query: '와플', record_recent_search: flag })
expect(response.status).toHaveBeenCalledWith(200)
expect(mocks.save).toHaveBeenCalledWith({ type: 'member', accountId: 'test-account' }, '와플')
},
)

it('returns the same search results without recording manager-registration lookup history', async () => {
const response = await request({ query: '와플', record_recent_search: 'false' })
expect(response.status).toHaveBeenCalledWith(200)
expect(response.json).toHaveBeenCalledWith({
clubs: [{ uuid: 'club-id', name: '와플스튜디오' }],
totalSize: 1,
query: '와플',
correctedQuery: null,
isTypoCorrected: false,
})
expect(mocks.save).not.toHaveBeenCalled()
})

it.each(['no', '', ['false', 'true']])(
'rejects invalid record flags %j before search or writes',
async (flag) => {
const response = await request({ query: '와플', record_recent_search: flag })
expect(response.status).toHaveBeenCalledWith(400)
expect(mocks.search).not.toHaveBeenCalled()
expect(mocks.save).not.toHaveBeenCalled()
},
)

it.each(['true', 'false'])('respects guest history preference %s', async (flag) => {
mocks.auth.mockResolvedValue({ type: 'guest', guestId: 'test-guest' })
const response = await request({ query: '와플', record_recent_search: flag })
expect(response.status).toHaveBeenCalledWith(200)
if (flag === 'true') {
expect(mocks.save).toHaveBeenCalledWith({ type: 'guest', guestId: 'test-guest' }, '와플')
} else {
expect(mocks.save).not.toHaveBeenCalled()
}
})
})
4 changes: 4 additions & 0 deletions apps/web/server/http/schemas/clubs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export const MinActivityPeriodFilterSchema = z.enum(['0', '1', '2', '3_plus'])
export const ClubSearchQuerySchema = z
.object({
query: z.string(),
record_recent_search: z
.enum(['true', 'false'])
.optional()
.describe('최근 검색어 저장 여부. 생략 시 true, 운영진 등록 검색은 false.'),
affiliation_type: z.enum(['전체', '중앙동아리', '학과/단과대동아리']).optional(),
is_recruiting: z.string().optional(),
recruit_type: z.enum(['정기', '상시']).optional(),
Expand Down
3 changes: 2 additions & 1 deletion apps/web/server/service/club.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,8 @@ export class ClubService {
status: PUBLIC_CLUB_STATUS,
deletedAt: IsNull(),
})
return club.map((it) => toClubDomain(it))
const clubReview = await this.getClubReviews(club.map((it) => it.uuid))
return club.map((it) => toClubDomain(it, clubReview.get(it.uuid)))
}

async saveClubToMyCollection(serviceUserId: string, clubId: string) {
Expand Down
63 changes: 63 additions & 0 deletions apps/web/server/service/saved-club-reviews.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { describe, expect, it, vi } from 'vitest'

vi.mock('../provider', () => ({
Inject: () => () => undefined,
InjectRepository: () => () => undefined,
Service: () => undefined,
}))

import type { ClubEntity } from '../infra/database/entities'
import { ClubService } from './club.service'

describe('ClubService.findMySavedClubs review summaries', () => {
it('returns existing review counts and ranked keywords for saved clubs', async () => {
const service = Object.create(ClubService.prototype) as ClubService
const reviewedClub = { uuid: 'reviewed', name: '와플스튜디오', imageUri: '' } as ClubEntity
const emptyClub = { uuid: 'empty', name: '후기 없는 동아리', imageUri: '' } as ClubEntity
Object.defineProperties(service, {
userSavedClubRepository: {
value: { findBy: vi.fn().mockResolvedValue([{ clubId: 'reviewed' }, { clubId: 'empty' }]) },
},
clubRepository: {
value: { findBy: vi.fn().mockResolvedValue([reviewedClub, emptyClub]) },
},
userClubReviewRepository: {
value: {
find: vi.fn().mockResolvedValue([
{ clubId: 'reviewed', reviewKeywordIds: ['friendly', 'learning'] },
{ clubId: 'reviewed', reviewKeywordIds: ['learning'] },
]),
},
},
clubReviewKeywordRepository: {
value: {
find: vi.fn().mockResolvedValue([
{ id: 'friendly', title: '친목', iconUri: '😊' },
{ id: 'learning', title: '배움', iconUri: '📚' },
]),
},
},
})

const result = await service.findMySavedClubs('test-user')

expect(result.map((club) => club.uuid)).toEqual(['reviewed', 'empty'])
expect(result[0]).toMatchObject({
totalReviews: 2,
reviewKeywords: [
{ id: 'learning', title: '배움', totalUpvotes: 2 },
{ id: 'friendly', title: '친목', totalUpvotes: 1 },
],
})
expect(result[1]).toMatchObject({ totalReviews: 0, reviewKeywords: [] })
})

it('returns no clubs without querying review repositories when the saved list is empty', async () => {
const service = Object.create(ClubService.prototype) as ClubService
Object.defineProperties(service, {
userSavedClubRepository: { value: { findBy: vi.fn().mockResolvedValue([]) } },
clubRepository: { value: { findBy: vi.fn().mockResolvedValue([]) } },
})
expect(await service.findMySavedClubs('test-user')).toEqual([])
})
})
Loading