Skip to content

Commit

Permalink
added search of users
Browse files Browse the repository at this point in the history
  • Loading branch information
tomyRomero committed Nov 23, 2023
1 parent 3a6420b commit 9abe5e9
Show file tree
Hide file tree
Showing 4 changed files with 175 additions and 14 deletions.
7 changes: 4 additions & 3 deletions app/(root)/search/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@ async function Page({
pageSize: 25,
});

console.log("USER RESULTS: ", result.users)

return (
<section>
<h1 className='head-text mb-10'>Search</h1>
<h1 className='head-text mb-10 text-black'>Search</h1>

<Searchbar routeType='search' />

Expand All @@ -36,14 +38,13 @@ async function Page({
<p className='no-result'>No Result</p>
) : (
<>
{result.users.map((person) => (
{result.users.map((person: any) => (
<UserCard
key={person.id}
id={person.id}
name={person.name}
username={person.username}
imgUrl={person.image}
personType='User'
/>
))}
</>
Expand Down
50 changes: 45 additions & 5 deletions components/cards/UserCard.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,49 @@
import React from 'react'
"use client";

import Image from "next/image";
import { useRouter } from "next/navigation";

import { Button } from "../ui/button";

interface Props {
id: string;
name: string;
username: string;
imgUrl: string;
}

function UserCard({ id, name, username, imgUrl}: Props) {
const router = useRouter();

const UserCard = () => {
return (
<div>UserCard</div>
)
<article className='user-card'>
<div className='user-card_avatar'>
<div className='relative h-12 w-12'>
<Image
src={imgUrl}
alt='user_logo'
fill
className='rounded-full object-cover'
/>
</div>

<div className='flex-1 text-ellipsis'>
<h4 className='text-base-semibold text-light-1'>{name}</h4>
<p className='text-small-medium text-gray-1'>@{username}</p>
</div>
</div>

<Button
className='user-card_btn'
onClick={() => {
router.push(`/profile/${id}`);

}}
>
View
</Button>
</article>
);
}

export default UserCard
export default UserCard;
53 changes: 48 additions & 5 deletions components/shared/Searchbar.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,52 @@
import React from 'react'
"use client";

import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

import { Input } from "../ui/input";

interface Props {
routeType: string;
}

function Searchbar({ routeType }: Props) {
const router = useRouter();
const [search, setSearch] = useState("");

// query after 0.3s of no input
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
if (search) {
router.push(`/${routeType}?q=` + search);
} else {
router.push(`/${routeType}`);
}
}, 300);

return () => clearTimeout(delayDebounceFn);
}, [search, routeType]);

const Searchbar = () => {
return (
<div>Searchbar</div>
)
<div className='searchbar'>
<Image
src='/assets/search-gray.svg'
alt='search'
width={24}
height={24}
className='object-contain'
/>
<Input
id='text'
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={`${
routeType !== "/search" ? "Search Users" : "Search creators"
}`}
className='no-focus searchbar_input'
/>
</div>
);
}

export default Searchbar
export default Searchbar;
79 changes: 78 additions & 1 deletion lib/actions/user.actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,81 @@ export const updateOrCreateUser = async (
console.log(`Error Upating or Creating User in Database: ${error}`);
return false;
}
}
}

export const fetchUsers = async ({
userId,
searchString = "",
pageNumber = 1,
pageSize = 20,
sortBy = "desc",
}: {
userId: string;
searchString?: string;
pageNumber?: number;
pageSize?: number;
sortBy?: "asc" | "desc";
}) => {
try {
const connection = connectDb("spark");
const queryAsync = util.promisify(connection.query).bind(connection);

// Calculate the number of users to skip based on the page number and page size.
const skipAmount = (pageNumber - 1) * pageSize;

// Create a case-insensitive regular expression for the provided search string.
const regex = new RegExp(searchString, "i");

// Define the SQL query to fetch users with related data, ordered by createdAt in descending order
const selectQuery = `
SELECT
U.*,
(
SELECT COUNT(*)
FROM user AS U2
WHERE U2.id != ? AND (? = '' OR (U2.username LIKE ? OR U2.name LIKE ?))
) AS total_count
FROM
user AS U
WHERE
U.id != ?
AND (? = '' OR (U.username LIKE ? OR U.name LIKE ?))
ORDER BY
U.id ${sortBy === "desc" ? "DESC" : "ASC"}
LIMIT
?, ?;
`;

// Define query parameters
const selectValues = [
userId,
searchString,
`%${regex.source}%`,
`%${regex.source}%`,
userId,
searchString,
`%${regex.source}%`,
`%${regex.source}%`,
skipAmount,
pageSize,
];

// Execute the SQL query to fetch users

//@ts-ignore
const results: any = await queryAsync(selectQuery, selectValues);

// Close the database connection
connection.end();

// Count the total number of users
const totalUsersCount =
results.length > 0 ? results[0].total_count : results.length;
const isNext = totalUsersCount > skipAmount + results.length;

return { users: results, isNext };
} catch (error) {
console.error("Error fetching users:", error);
throw error;
}
};

0 comments on commit 9abe5e9

Please sign in to comment.