Building a Job Search Function with Prisma in Next.js
Tags: webdev, nextjs, react, javascript
Published: 2024-06-27 11:52:41

## Introduction

Are you looking to build a robust job search feature for your Next.js application? In this guide, we'll walk through creating a powerful job search function using Prisma. Whether you're a beginner or just looking to refresh your skills, this tutorial will help you implement a search that scans job titles, skills, and descriptions, making it easier for users to find their perfect job match. Let's dive in and make your job search feature both efficient and user-friendly! For a complete implementation, check out my [GitHub repository](https://github.com/ashsajal1/w3jobs).

## Table of Contents

1. [Introduction](#introduction)
2. [Setting Up Prisma](#setting-up-prisma)
3. [Creating the Job Model](#creating-the-job-model)
4. [Fetching Jobs with Prisma](#fetching-jobs-with-prisma)
5. [Implementing the Search Function](#implementing-the-search-function)
6. [Testing Your Job Search](#testing-your-job-search)
7. [Conclusion](#conclusion)
8. [Full Implementation on GitHub](#full-implementation-on-github)

## Setting Up Prisma

Before we start fetching jobs, we need to set up Prisma in our project. If you haven't installed Prisma yet, follow these steps:

1. **Install Prisma CLI and initialize**:
    ```bash
    npm install @prisma/cli --save-dev
    npx prisma init
    ```

2. **Set up your database connection** in the `.env` file created by Prisma.

3. **Generate Prisma Client**:
    ```bash
    npx prisma generate
    ```

## Creating the Job Model

Next, we'll define a `Job` model in our `schema.prisma` file:

```prisma
model Job {
  id          Int      @id @default(autoincrement())
  title       String
  skills      String
  description String
  createdAt   DateTime @default(now())
}
```

After updating the schema, run the following command to apply the changes to your database:

```bash
npx prisma migrate dev --name init
```

## Fetching Jobs with Prisma

Now that we have our database and model set up, let's create a function to fetch jobs. We'll start by fetching all jobs without any filters:

```typescript
const fetchJobs = async (tags: string[] = []) => {
    if (tags.length === 0) {
        return await prisma.job.findMany();
    }

    const orConditions = tags.map(tag => ({
        OR: [
            { title: { contains: tag, mode: 'insensitive' as const } },
            { skills: { contains: tag, mode: 'insensitive' as const } },
            { description: { contains: tag, mode: 'insensitive' as const } }
        ]
    }));

    const jobs = await prisma.job.findMany({
        where: {
            OR: orConditions.flatMap(condition => condition.OR)
        }
    });

    return jobs;
};
```

## Implementing the Search Function

The `fetchJobs` function is designed to search for jobs based on tags. If no tags are provided, it returns all jobs. When tags are provided, it searches for jobs where any of the tags match the title, skills, or description.

Here’s the breakdown:
1. **No tags provided**: Returns all jobs.
2. **Tags provided**: Maps each tag to a condition that checks if the tag is contained (case-insensitive) in the job title, skills, or description.

## Testing Your Job Search

You can now test your job search function by calling it with different sets of tags:

```typescript
(async () => {
    const allJobs = await fetchJobs();
    console.log("All Jobs:", allJobs);

    const searchTags = ["developer", "JavaScript"];
    const searchedJobs = await fetchJobs(searchTags);
    console.log("Searched Jobs:", searchedJobs);
})();
```

Run this code in your server or wherever you have set up your Prisma client to see the results.

## Conclusion

By following this guide, you’ve implemented a powerful job search feature using Prisma and Next.js. This function allows users to search for jobs based on keywords found in job titles, skills, or descriptions. For a complete implementation, you can refer to my [GitHub repository](https://github.com/ashsajal1/w3jobs).

## Full Implementation on GitHub

For a detailed implementation and more advanced features, visit my [GitHub repository](https://github.com/ashsajal1/w3jobs). Here, you’ll find the complete code along with additional features to enhance your job search application. Happy coding!