Top Questions

When should i use server actions and API routes to get and post data in the backend?

>

How to choose bettwen react-hook-form and useActionState form to handle forms?

>

Does anyone know a good roadmap to start learning Java Spring Boot?

>

Qual o melhor roadmap para aprender HTML?

>

Popular Tags

Code Review

1

TypeScript

1

Next.js

1

HTML

1

Author Image

Matheus Felipe

0

When should i use server actions and API routes to get and post data in the backend?

Time icon

asked 8 days ago

Like icon

Answers 0

there aere sometimes that i need to get data from the backend and i can't decide which one i should use, usually i prefer server actions but i've never used api routes for anything, i wanted to know what situations one is better than another, for example to get data from a client component.

"use server"

import { prisma } from "../prisma"
import { tags } from "../tagsData";

export async function GetEverything({search} : {search: string}){
    const users = await prisma.user.findMany({
        where: {name: {contains: search}},
        select: {name: true, username: true},
        take: 4
    });

    const filteredUsers = users.map(e => ({
        name: e.name,
        id: e.username,
        href: `/profile/${e.username}`,
        type: "USER"
    }));

    /* ------------------ */

    const posts = await prisma.post.findMany({
        where: {title: {contains: search}},
        select: {id: true, title: true},
        take: 4
    });

    const filteredPosts = posts.map(e => ({
        name: e.title,
        id: e.id,
        href: `/post/${e.id}`,
        type: "POST"
    }));

    /* ------------------ */

    const responses = await prisma.response.findMany({
        where: {content: {contains: search}},
        select: {id: true, content: true},
        take: 4
    });

    const filteredResponses = responses.map(e => ({
        name: e.content,
        id: e.id,
        href: `/response/${e.id}`,
        type: "RESPONSE"
    }));

    /* ------------------ */

    const filteredTags = tags
        .filter(e => e.name.toLowerCase()
        .includes(search.toLowerCase()))
        .map(e => ({name: e.name, id: e.name, href: `/tags?tag=${e.name}`, type: "TAG"}))
        .splice(0,4);

    const allItems = [
        ...filteredPosts,
        ...filteredResponses,
        ...filteredUsers,
        ...filteredTags,
    ].map(item => {
        const text = item.name?.toLowerCase() ?? ""
        const score = text.split(search.toLowerCase() ?? "").length - 1

        return {
        ...item,
        score,
        }
    })

    const topMatches = allItems
        .filter(item => item.score > 0)
        .sort((a, b) => b.score - a.score)
        .slice(0, 4)
        .map(({ score, ...item }) => item)


    return [[...topMatches],[...filteredPosts], [...filteredResponses], [...filteredUsers], [...filteredTags]];
}

Write your answer here

Arrow icon