Skip to content
Open
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
4 changes: 2 additions & 2 deletions src/features/decorator/formatter/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
function formatter(formatFn: (value: any) => string): PropertyDecorator {
export function formatter<T = string>(formatFn: (value: any) => T): PropertyDecorator {
// @ts-ignore
return function (target: any, propertyName: string) {
let value: string;
let value: T;

const getter = function () {
return value;
Expand Down
35 changes: 35 additions & 0 deletions src/features/decorator/query-parser/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ParsedUrlQuery } from "querystring";
import { formatter } from "@/features/decorator/formatter";

export type SearchType = 'ID' | 'KEYWORD';

export class QueryParser {
@formatter((value) => Number.isNaN(Number(value)) ? 0 : Number(value))
categoryId: string | string[] | undefined;

@formatter<SearchType>((value) => value === 'ID' ? 'ID' : 'KEYWORD')
searchType: string | string[] | undefined;

@formatter((value) => value?.toString() || '')
searchKeyword: string | string[] | undefined;

@formatter((value) => value === 'true')
isActive: string | string[] | undefined;

constructor(query: ParsedUrlQuery) {
const { categoryId, searchType, searchKeyword, isActive } = query;
this.categoryId = categoryId;
this.searchType = searchType;
this.searchKeyword = searchKeyword;
this.isActive = isActive;
}

getParsedUrlQuery() {
return ({
categoryId: this.categoryId,
searchType: this.searchType,
searchKeyword: this.searchKeyword,
isActive: this.isActive,
});
}
}
34 changes: 34 additions & 0 deletions src/pages/decorator-query-parser.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { QueryParser } from "@/features/decorator/query-parser";
import { useEffect, useState } from "react";
import { useRouter } from "next/router";

export default function DecoratorQueryParser() {
const { query } = useRouter();
const [parsedData, setParsedData] = useState<any>();

useEffect(()=> {
// 페치로 받아왔다고 가정
const queryParser = new QueryParser(query);
setParsedData(queryParser.getParsedUrlQuery());

}, [query])

if (!parsedData) return null;

return (
<ul>
<li>
카테고리 ID: {parsedData.categoryId}
</li>
<li>
검색 타입: {parsedData.searchType}
</li>
<li>
검색 키워드: {`"${parsedData.searchKeyword}"`}
</li>
<li>
활성화 여부: {`${parsedData.isActive}`}
</li>
</ul>
)
}